diff --git a/src/eva2/server/go/enums/BOAScoringMethods.java b/src/eva2/server/go/enums/BOAScoringMethods.java new file mode 100644 index 00000000..d23f00ab --- /dev/null +++ b/src/eva2/server/go/enums/BOAScoringMethods.java @@ -0,0 +1,9 @@ +package eva2.server.go.enums; + +public enum BOAScoringMethods { + BDM, K2, BIC; + + public static String[] getInfoStrings(){ + return new String[] {"The Bayesian Dirichlet Metric", "The K2 Metric", "The Bayesian Information Criterion"}; + } +} \ No newline at end of file diff --git a/src/eva2/server/go/strategies/BOA.java b/src/eva2/server/go/strategies/BOA.java index 542a07d8..17a05c58 100644 --- a/src/eva2/server/go/strategies/BOA.java +++ b/src/eva2/server/go/strategies/BOA.java @@ -1,5 +1,11 @@ package eva2.server.go.strategies; +import java.io.File; +import java.io.FileWriter; +import java.io.IOException; +import java.io.PrintWriter; +import java.io.Writer; +import java.text.DateFormat; import java.util.BitSet; import java.util.Date; import java.util.LinkedList; @@ -8,6 +14,7 @@ import java.util.List; import eva2.gui.BeanInspector; import eva2.gui.GenericObjectEditor; import eva2.server.go.InterfacePopulationChangedEventListener; +import eva2.server.go.enums.BOAScoringMethods; import eva2.server.go.individuals.AbstractEAIndividual; import eva2.server.go.individuals.GAIndividualBinaryData; import eva2.server.go.individuals.InterfaceDataTypeBinary; @@ -21,69 +28,108 @@ import eva2.server.go.problems.InterfaceOptimizationProblem; import eva2.tools.Pair; import eva2.tools.math.BayNet; import eva2.tools.math.RNG; +import java.io.BufferedWriter; /** * Basic implementation of the Bayesian Optimization Algorithm * - * Martin Pelikan, David E. Goldberg and Erick Cantu-Paz: 'BOA: The Bayesian Optimization Algorithm' - * the works by Martin Pelikan and David E. Goldberg. + * Martin Pelikan, David E. Goldberg and Erick Cantu-Paz: 'BOA: The Bayesian + * Optimization Algorithm' the works by Martin Pelikan and David E. Goldberg. + * Genetic and Evolutionary Computation Conference (GECCO-99), pp. 525-532 + * (1999) * * @author seitz - * + * */ public class BOA implements InterfaceOptimizer, java.io.Serializable { - private static boolean TRACE = false; - transient private InterfacePopulationChangedEventListener m_Listener = null; - private String m_Identifier = "BOA"; + private static boolean TRACE = false; + transient private InterfacePopulationChangedEventListener m_Listener = null; + private String m_Identifier = "BOA"; - private int probDim = 3; - private int fitCrit = -1; - private int PopSize = 50; - private int numberOfParents = 3; - private boolean replaceNetwork = true; - private transient BayNet network = null; - private Population population = new Population(); - private AbstractOptimizationProblem problem = new BKnapsackProblem(); - private AbstractEAIndividual template = null; - private double learningSetRatio = 0.5; - private double resampleRatio = 0.5; - private double upperProbLimit = 0.9; - private double lowerProbLimit = 0.1; + private int probDim = 8; + private int fitCrit = -1; + private int PopSize = 50; + private int numberOfParents = 3; + private transient BayNet network = null; + private Population population = new Population(); + private AbstractOptimizationProblem problem = new BKnapsackProblem(); + private AbstractEAIndividual template = null; + private double learningSetRatio = 0.5; + private double resampleRatio = 0.5; + private double upperProbLimit = 0.9; + private double lowerProbLimit = 0.1; + private int count = 0; + private String netFolder = "BOAOutput"; + private int[][] edgeRate = null; - // private networkGenerationMethod netGenMethod = networkGenerationMethod.GREEDY; - // public enum networkGenerationMethod { GREEDY, K2 }; + private BOAScoringMethods scoringMethod = BOAScoringMethods.BDM; + private boolean printNetworks = false; + private boolean printEdgeRate = false; + private boolean printTimestamps = false; + private boolean printMetrics = false; + private boolean printExtraOutput = false; - public BOA(){ + public BOA() { } - - public BOA(int numberOfParents, int popSize, boolean replaceNetwork, double learningSetRatio, double resampleRatio){ + + public BOA(int numberOfParents, int popSize, BOAScoringMethods method, + double learningSetRatio, double resampleRatio, String outputFolder, + boolean printExtraOutput, double upperProbLimit, + double lowerProbLimit, boolean printNetworks, + boolean printEdgeRate, boolean printMetrics, boolean printTimestamps) { this.numberOfParents = numberOfParents; this.PopSize = popSize; - this.replaceNetwork = replaceNetwork; + this.scoringMethod = method; this.learningSetRatio = learningSetRatio; this.resampleRatio = resampleRatio; + this.netFolder = outputFolder; + this.printExtraOutput = printExtraOutput; + this.upperProbLimit = upperProbLimit; + this.lowerProbLimit = lowerProbLimit; + this.printEdgeRate = printEdgeRate; + this.printNetworks = printNetworks; + this.printMetrics = printMetrics; + this.printTimestamps = printTimestamps; + if (printEdgeRate || printNetworks || printMetrics || printTimestamps) { + this.printExtraOutput = true; + } } - public BOA(BOA b){ - this.m_Listener = b.m_Listener; - this.m_Identifier = b.m_Identifier; - this.probDim = b.probDim; - this.fitCrit = b.fitCrit; - this.PopSize = b.PopSize; - this.numberOfParents = b.numberOfParents; - this.replaceNetwork = b.replaceNetwork; - this.network = (BayNet) b.network.clone(); - this.population = (Population) b.population.clone(); - this.problem = (AbstractOptimizationProblem) b.problem.clone(); - this.template = (AbstractEAIndividual) b.template.clone(); - this.learningSetRatio = b.learningSetRatio; - this.resampleRatio = b.resampleRatio; - this.upperProbLimit = b.upperProbLimit; + public BOA(BOA b) { + this.m_Listener = b.m_Listener; + this.m_Identifier = b.m_Identifier; + this.probDim = b.probDim; + this.fitCrit = b.fitCrit; + this.PopSize = b.PopSize; + this.numberOfParents = b.numberOfParents; + this.network = (BayNet) b.network.clone(); + this.population = (Population) b.population.clone(); + this.problem = (AbstractOptimizationProblem) b.problem.clone(); + this.template = (AbstractEAIndividual) b.template.clone(); + this.learningSetRatio = b.learningSetRatio; + this.resampleRatio = b.resampleRatio; + this.upperProbLimit = b.upperProbLimit; + this.lowerProbLimit = b.lowerProbLimit; + this.count = b.count; + this.netFolder = b.netFolder; + this.scoringMethod = b.scoringMethod; + this.edgeRate = new int[b.edgeRate.length][b.edgeRate.length]; + for (int i = 0; i < this.edgeRate.length; i++) { + for (int j = 0; j < this.edgeRate[i].length; j++) { + this.edgeRate[i][j] = b.edgeRate[i][j]; + } + } + this.scoringMethod = b.scoringMethod; + this.printExtraOutput = b.printExtraOutput; + this.printNetworks = b.printNetworks; + this.printMetrics = b.printMetrics; + this.printEdgeRate = b.printEdgeRate; + this.printTimestamps = b.printTimestamps; } - public Object clone(){ + public Object clone() { return new BOA(this); } @@ -94,66 +140,103 @@ public class BOA implements InterfaceOptimizer, java.io.Serializable { public static String globalInfo() { return "Basic implementation of the Bayesian Optimization Algorithm based on the works by Martin Pelikan and David E. Goldberg."; } - + public void hideHideable() { - GenericObjectEditor.setHideProperty(this.getClass(), "population", true); + GenericObjectEditor + .setHideProperty(this.getClass(), "population", true); + GenericObjectEditor.setHideProperty(getClass(), "printNetworks", + !printExtraOutput); + GenericObjectEditor.setHideProperty(getClass(), "printEdgeRate", + !printExtraOutput); + GenericObjectEditor.setHideProperty(getClass(), "printMetrics", + !printExtraOutput); + GenericObjectEditor.setHideProperty(getClass(), "printTimestamps", + !printExtraOutput); } - + public void addPopulationChangedEventListener( InterfacePopulationChangedEventListener ea) { this.m_Listener = ea; } + private void createDirectoryIfNeeded(String directoryName) { + File theDir = new File(directoryName); + // if the directory does not exist, create it + if (!theDir.exists()) { + System.out.println("creating directory: " + directoryName); + theDir.mkdir(); + } + } + public boolean removePopulationChangedEventListener( InterfacePopulationChangedEventListener ea) { - if (m_Listener==ea) { - m_Listener=null; + if (m_Listener == ea) { + m_Listener = null; return true; - } else return false; + } else + return false; } private static BitSet getBinaryData(AbstractEAIndividual indy) { - if (indy instanceof InterfaceGAIndividual) return ((InterfaceGAIndividual)indy).getBGenotype(); - else if (indy instanceof InterfaceDataTypeBinary) return ((InterfaceDataTypeBinary)indy).getBinaryData(); + if (indy instanceof InterfaceGAIndividual) + return ((InterfaceGAIndividual) indy).getBGenotype(); + else if (indy instanceof InterfaceDataTypeBinary) + return ((InterfaceDataTypeBinary) indy).getBinaryData(); else { - throw new RuntimeException("Unable to get binary representation for " + indy.getClass()); + throw new RuntimeException( + "Unable to get binary representation for " + + indy.getClass()); } } /** - * evaluate the given Individual and increments the counter. if the individual is null, only the counter is incremented - * @param indy the individual you want to evaluate + * evaluate the given Individual and increments the counter. if the + * individual is null, only the counter is incremented + * + * @param indy + * the individual you want to evaluate */ - private void evaluate(AbstractEAIndividual indy){ + private void evaluate(AbstractEAIndividual indy) { // evaluate the given individual if it is not null - if(indy == null){ + if (indy == null) { System.err.println("tried to evaluate null"); return; } this.problem.evaluate(indy); - // increment the number of evaluations + // increment the number of evaluations this.population.incrFunctionCalls(); } /** * the default initialization */ - private void defaultInit(){ - if (population==null) { + private void defaultInit() { + this.count = 0; + if (printExtraOutput) { + if (printTimestamps) { + printTimeStamp(); + } + } + if (population == null) { this.population = new Population(this.PopSize); } else { this.population.setTargetPopSize(this.PopSize); } this.template = this.problem.getIndividualTemplate(); - if (!(template instanceof InterfaceDataTypeBinary)){ + if (!(template instanceof InterfaceDataTypeBinary)) { System.err.println("Requiring binary data!"); - }else{ - Object dim = BeanInspector.callIfAvailable(problem, "getProblemDimension", null); - if (dim==null) System.err.println("Couldnt get problem dimension!"); - probDim = (Integer)dim; - ((InterfaceDataTypeBinary)this.template).SetBinaryGenotype(new BitSet(probDim)); + } else { + Object dim = BeanInspector.callIfAvailable(problem, + "getProblemDimension", null); + if (dim == null) + System.err.println("Couldnt get problem dimension!"); + probDim = (Integer) dim; + ((InterfaceDataTypeBinary) this.template) + .SetBinaryGenotype(new BitSet(probDim)); } this.network = new BayNet(this.probDim, upperProbLimit, lowerProbLimit); + this.network.setScoringMethod(this.scoringMethod); + this.edgeRate = new int[this.probDim][this.probDim]; } public void init() { @@ -164,128 +247,111 @@ public class BOA implements InterfaceOptimizer, java.io.Serializable { } private void evaluatePopulation(Population pop) { - for (int i=0; i> bestNetworks = new LinkedList>(); - while(improvement){ + while (improvement) { improvement = false; -// System.out.println("score:"+score); - for(int i=0; i= score){ - if(tmpScore == score){ - bestNetworks.add(new Pair(i, j)); - }else{ + for (int i = 0; i < this.probDim; i++) { + for (int j = 0; j < this.probDim; j++) { + // if we are allowed to add the edge + if ((!this.network.hasEdge(i, j)) + && (i != j) + && (this.network.getNode(j).getNumberOfParents() < this.numberOfParents)) { + // add the edge + this.network.addEdge(i, j); + // if it is still acyclic + if (this.network.isACyclic(i, j)) { + // calculate the new score + double tmpScore = this.network.getNewScore(pop, j); + // if we have a score larger or equal to the current score + if (tmpScore >= score && tmpScore != score1) { + // if the score is equal + if (tmpScore == score) { + // add the edge to the list of possible new edges + bestNetworks + .add(new Pair(i, + j)); + // if we have a better score + } else { + // delete the current possible edges bestNetworks.clear(); - bestNetworks.add(new Pair(i, j)); + // add the edge to the list fo possible new edges + bestNetworks + .add(new Pair(i, + j)); + // adapt the score score = tmpScore; + // we could improve the network improvement = true; } } } + // remove the edge from the network and try the next one this.network.removeEdge(i, j); } } } - if(bestNetworks.size() > 0){ + // if we found at least one edge that could improve the network + if (bestNetworks.size() > 0) { + // get one edge randomly from the list of possible edges int val = RNG.randomInt(bestNetworks.size()); Pair pair = bestNetworks.get(val); + // add it to the network this.network.addEdge(pair.getHead(), pair.getTail()); + // adapt the array that allowes the fast calculation of the scores + this.network.updateScoreArray(pop, pair.getTail()); } + // adapt the score + score = this.network.getNewScore(pop, -1); + score1 = score; bestNetworks.clear(); } -// time = new Date(); -// System.out.println("Stop: "+time.getHours()+":"+time.getMinutes()+":"+time.getSeconds()); - } - - private boolean expandGreedy(Population pop){ - BayNet net = (BayNet) this.network.clone(); - BayNet best = (BayNet) this.network.clone(); - boolean improv = false; - boolean improvement = true; - double score = net.bayesianDirichletMetric(pop); - Date time = new Date(); -// System.out.println("Start: "+time.getHours()+":"+time.getMinutes()+":"+time.getSeconds()); - while(improvement){ - improvement = false; -// System.out.println("score:"+score); - for(int i=0; i score){ - best = (BayNet) tmp.clone(); - score = tmpScore; - improvement = true; - improv = true; - } - } - } - } - } - net = (BayNet) best.clone();; - } - time = new Date(); -// System.out.println("Stop: "+time.getHours()+":"+time.getMinutes()+":"+time.getSeconds()); - this.network = (BayNet) best.clone(); - return improv; + score = this.network.getScore(pop); } /** - * Generate a Bayesian network with the individuals of the population as a reference Point - * @param pop the individuals the network is based on + * Generate a Bayesian network with the individuals of the population as a + * reference Point + * + * @param pop + * the individuals the network is based on */ - private void constructNetwork(Population pop){ - if(this.replaceNetwork){ - generateGreedy(pop); - }else{ - boolean improve = expandGreedy(pop); - if(!improve){ - generateGreedy(pop); - } - } - //TODO + private void constructNetwork(Population pop) { + generateGreedy(pop); } /** * generate new individuals based on the bayesian network - * @return the new individuals + * + * @return the new individuals */ - private Population generateNewIndys(int sampleSetSize){ + private Population generateNewIndys(int sampleSetSize) { Population pop = new Population(sampleSetSize); - if (TRACE) System.out.println("Resampling " + sampleSetSize + " indies..."); - while(pop.size() < sampleSetSize){ - AbstractEAIndividual indy = (AbstractEAIndividual) this.template.clone(); + if (TRACE) + System.out.println("Resampling " + sampleSetSize + " indies..."); + while (pop.size() < sampleSetSize) { + AbstractEAIndividual indy = (AbstractEAIndividual) this.template + .clone(); BitSet data = this.network.sample(getBinaryData(indy)); ((InterfaceDataTypeBinary) indy).SetBinaryGenotype(data); evaluate(indy); @@ -295,46 +361,220 @@ public class BOA implements InterfaceOptimizer, java.io.Serializable { } /** - * Calculate a plausible number of individuals to be resampled per iteration. + * Calculate a plausible number of individuals to be resampled per + * iteration. + * * @return */ private int calcResampleSetSize() { - int result = (int)Math.min(PopSize, Math.max(1.0, ((double)PopSize)*resampleRatio)); -// System.out.println(result); + int result = (int) Math.min(PopSize, + Math.max(1.0, ((double) PopSize) * resampleRatio)); return result; } /** - * Calculate a plausible number of individuals from which the BayNet is learned. - * In principle this can be independent of the resampling set size. + * Calculate a plausible number of individuals from which the BayNet is + * learned. In principle this can be independent of the resampling set size. + * * @return */ private int calcLearningSetSize() { - return (int)Math.min(PopSize, Math.max(1.0, ((double)PopSize)*learningSetRatio)); + return (int) Math.min(PopSize, + Math.max(1.0, ((double) PopSize) * learningSetRatio)); } - - public void remove(Population pop){ - for(Object indy: pop){ + + /** + * remove the individuals in pop from the population + * @param pop + */ + public void remove(Population pop) { + for (Object indy : pop) { this.population.remove(indy); } } - public void optimize() { - Population best = this.population.getBestNIndividuals(calcLearningSetSize(), this.fitCrit); - constructNetwork(best); - Population newlyGenerated = generateNewIndys(calcResampleSetSize()); - Population toRemove = this.population.getWorstNIndividuals(calcResampleSetSize(), this.fitCrit); - remove(toRemove); - this.population.addAll(newlyGenerated); -// print(); - this.firePropertyChangedEvent(Population.nextGenerationPerformed); + private void printEdgeRate() { + String filename = this.netFolder + "/edgeRate.m"; + Writer w = null; + PrintWriter out = null; + String message = "edgeRate" + this.scoringMethod + " = ["; + createDirectoryIfNeeded(this.netFolder); + for (int i = 0; i < this.edgeRate.length; i++) { + for (int j = 0; j < this.edgeRate.length; j++) { + message = message + // we devide through count+1, because we have a generation 0 + + (((double) edgeRate[i][j]) / (this.count + 1)); + if (j != this.edgeRate.length - 1) { + message = message + ","; + } + } + if (i != this.edgeRate.length - 1) { + message = message + ";"; + } + } + message = message + "];"; + try { + w = new FileWriter(filename); + out = new PrintWriter(w); + out.write(message); + } catch (IOException e) { + e.printStackTrace(); + } finally { + out.close(); + try { + w.close(); + } catch (IOException e) { + e.printStackTrace(); + } + } } + private void printNetworkToFile(String i) { + String filename = this.netFolder + "/network_" + i + ".graphml"; + Writer w = null; + PrintWriter out = null; + String message = this.network.generateYFilesCode(); + createDirectoryIfNeeded(this.netFolder); + try { + w = new FileWriter(filename); + out = new PrintWriter(w); + out.write(message); + } catch (Exception e) { + e.printStackTrace(); + } finally { + out.close(); + try { + w.close(); + } catch (IOException e) { + e.printStackTrace(); + } + } + } - /** Something has changed + private void printTimeStamp() { + String fileName = this.netFolder + "/timestamps.txt"; + Date d = new Date(); + DateFormat df = DateFormat.getTimeInstance(DateFormat.MEDIUM); + String message = this.count + "\t" + df.format(d) + "\n"; + createDirectoryIfNeeded(this.netFolder); + boolean exists = (new File(fileName)).exists(); + if (exists) { + try { + // Create file + FileWriter fstream = new FileWriter((fileName), true); + BufferedWriter out = new BufferedWriter(fstream); + + out.write(message); + out.newLine(); + // Close the output stream + out.close(); + } catch (Exception e) {// Catch exception if any + System.err.println("Error: " + e.getMessage()); + } + + } else { + try { + // Create file + FileWriter fstream = new FileWriter((fileName), false); + BufferedWriter out = new BufferedWriter(fstream); + out.newLine(); + out.write(message); + out.newLine(); + // Close the output stream + out.close(); + } catch (Exception e) {// Catch exception if any + System.err.println("Error: " + e.getMessage()); + } + } + } + + private void printMetrics(Population pop) { + this.network.setScoringMethod(BOAScoringMethods.BDM); + double bdmMetric = this.network.getScore(pop); + this.network.setScoringMethod(BOAScoringMethods.K2); + double k2Metric = this.network.getScore(pop); + this.network.setScoringMethod(BOAScoringMethods.BIC); + double bicMetric = this.network.getScore(pop); + this.network.setScoringMethod(this.scoringMethod); + String fileName = this.netFolder + "/" + "metrics.csv"; + createDirectoryIfNeeded(this.netFolder); + boolean exists = (new File(fileName)).exists(); + if (exists) { + try { + // Create file + FileWriter fstream = new FileWriter((fileName), true); + BufferedWriter out = new BufferedWriter(fstream); + + out.write("" + bdmMetric + "," + k2Metric + "," + bicMetric); + out.newLine(); + // Close the output stream + out.close(); + } catch (Exception e) {// Catch exception if any + System.err.println("Error: " + e.getMessage()); + } + + } else { + try { + // Create file + FileWriter fstream = new FileWriter((fileName), false); + BufferedWriter out = new BufferedWriter(fstream); + out.write("BDMMetric, " + "K2Metric, " + "BIC"); + out.newLine(); + out.write("" + bdmMetric + "," + k2Metric + "," + bicMetric); + out.newLine(); + // Close the output stream + out.close(); + } catch (Exception e) {// Catch exception if any + System.err.println("Error: " + e.getMessage()); + } + } + } + + public void optimize() { + this.problem.evaluatePopulationStart(this.population); + // get the best individuals from the population + Population best = this.population.getBestNIndividuals( + calcLearningSetSize(), this.fitCrit); + // generate the network with these individuals + constructNetwork(best); + if(this.printExtraOutput && this.printEdgeRate){ + this.edgeRate = this.network.adaptEdgeRate(this.edgeRate); + } + // sample new individuals from the network + Population newlyGenerated = generateNewIndys(calcResampleSetSize()); + // remove the worst individuals from the population + Population toRemove = this.population.getWorstNIndividuals( + calcResampleSetSize(), this.fitCrit); + remove(toRemove); + // add the newly generated Individuals to the population + this.population.addAll(newlyGenerated); + this.count++; + // we are done with one generation + this.firePropertyChangedEvent(Population.nextGenerationPerformed); + this.problem.evaluatePopulationEnd(this.population); + // print output if desired + if (this.printExtraOutput) { + if (printNetworks) { + printNetworkToFile("" + this.count); + } + if (printEdgeRate) { + printEdgeRate(); + } + if (printMetrics) { + printMetrics(best); + } + if (printTimestamps) { + printTimeStamp(); + } + } + } + + /** + * Something has changed */ - protected void firePropertyChangedEvent (String name) { - if (this.m_Listener != null) this.m_Listener.registerPopulationStateChanged(this, name); + protected void firePropertyChangedEvent(String name) { + if (this.m_Listener != null) + this.m_Listener.registerPopulationStateChanged(this, name); } public Population getPopulation() { @@ -373,102 +613,46 @@ public class BOA implements InterfaceOptimizer, java.io.Serializable { } - //------------------------------- - //-------------GUI--------------- - //------------------------------- + // ------------------------------- + // -------------GUI--------------- + // ------------------------------- - public int getNumberOfParents(){ + public int getNumberOfParents() { return this.numberOfParents; } - public void setNumberOfParents(int i){ + public void setNumberOfParents(int i) { this.numberOfParents = i; } - public String numberOfParentsTipText(){ + public String numberOfParentsTipText() { return "The maximum number of parents a node in the Bayesian Network can have"; } - public boolean getReplaceNetwork(){ - return this.replaceNetwork; - } - - public void setReplaceNetwork(boolean b){ - this.replaceNetwork = b; - } - - public String replaceNetworkTipText(){ + public String replaceNetworkTipText() { return "if set, the network will be completely replaced. If not, it will be tried to improve the last network, if that is not possible, it will be replaced"; } - // public networkGenerationMethod getNetworkGenerationMethod(){ - // return this.netGenMethod; - // } - // - // public void setNetworkGenerationMethod(networkGenerationMethod n){ - // this.netGenMethod = n; - // } - // - // public String networkGenerationMethodTipText(){ - // return "The Method with which the Bayesian Network will be gererated"; - // } - - public void print(){ - this.network.print(); + public BOAScoringMethods getNetworkGenerationMethod() { + return this.scoringMethod; } - - public static void main(String[] args){ - Population pop = new Population(); - GAIndividualBinaryData indy1 = new GAIndividualBinaryData(); - indy1.setBinaryDataLength(3); - GAIndividualBinaryData indy2 = (GAIndividualBinaryData) indy1.clone(); - GAIndividualBinaryData indy3 = (GAIndividualBinaryData) indy1.clone(); - GAIndividualBinaryData indy4 = (GAIndividualBinaryData) indy1.clone(); - GAIndividualBinaryData indy5 = (GAIndividualBinaryData) indy1.clone(); - BitSet data1 = indy1.getBinaryData(); - BitSet data2 = indy2.getBinaryData(); - BitSet data3 = indy3.getBinaryData(); - BitSet data4 = indy4.getBinaryData(); - BitSet data5 = indy5.getBinaryData(); - data1.set(0, true); - data1.set(1, true); - data1.set(2, false); - data2.set(0, true); - data2.set(1, true); - data2.set(2, true); - data3.set(0, false); - data3.set(1, true); - data3.set(2, false); - data4.set(0, false); - data4.set(1, true); - data4.set(2, true); - data5.set(0, true); - data5.set(1, false); - data5.set(2, false); - indy1.SetBinaryGenotype(data1); - indy2.SetBinaryGenotype(data2); - indy3.SetBinaryGenotype(data3); - indy4.SetBinaryGenotype(data4); - indy5.SetBinaryGenotype(data5); - pop.add(indy1); - pop.add(indy2); - AbstractEAIndividual ind = (AbstractEAIndividual) indy2.clone(); - pop.add(ind); -// pop.add(indy3); -// pop.add(indy4); -// pop.add(indy5); - BOA b = new BOA(); - b.generateGreedy(pop); - System.out.println(pop.getStringRepresentation()); - b.print(); + + public void setNetworkGenerationMethod(BOAScoringMethods n) { + this.scoringMethod = n; + } + + public String networkGenerationMethodTipText() { + return "The Method with which the Bayesian Network will be gererated"; } public int getPopulationSize() { return PopSize; } + public void setPopulationSize(int popSize) { PopSize = popSize; } + public String populationSizeTipText() { return "Define the pool size used by BOA"; } @@ -476,23 +660,27 @@ public class BOA implements InterfaceOptimizer, java.io.Serializable { public double getResamplingRatio() { return resampleRatio; } + public void setResamplingRatio(double resampleRat) { this.resampleRatio = resampleRat; } + public String resamplingRatioTipText() { return "Ratio of individuals to be resampled from the Bayesian network per iteration"; } - + public double getLearningRatio() { return learningSetRatio; } + public void setLearningRatio(double rat) { this.learningSetRatio = rat; } + public String learningRatioTipText() { return "Ratio of individuals to be used to learn the Bayesian network"; } - + public double getProbLimitHigh() { return upperProbLimit; } @@ -500,8 +688,8 @@ public class BOA implements InterfaceOptimizer, java.io.Serializable { public void setProbLimitHigh(double upperProbLimit) { this.upperProbLimit = upperProbLimit; } - - public String probLimitHighTipText(){ + + public String probLimitHighTipText() { return "the upper limit of the probability to set one Bit to 1"; } @@ -512,13 +700,266 @@ public class BOA implements InterfaceOptimizer, java.io.Serializable { public void setProbLimitLow(double lowerProbLimit) { this.lowerProbLimit = lowerProbLimit; } - - public String probLimitLowTipText(){ + + public String probLimitLowTipText() { return "the lower limit of the probability to set one Bit to 1"; } - + public String[] customPropertyOrder() { - return new String[] {"learningRatio", "resamplingRatio"}; + return new String[] { "learningRatio", "resamplingRatio" }; + } + + public boolean isPrintExtraOutput() { + return this.printExtraOutput; + } + + public void setPrintExtraOutput(boolean b) { + this.printExtraOutput = b; + GenericObjectEditor.setHideProperty(getClass(), "printNetworks", + !printExtraOutput); + GenericObjectEditor.setHideProperty(getClass(), "printEdgeRate", + !printExtraOutput); + GenericObjectEditor.setHideProperty(getClass(), "printMetrics", + !printExtraOutput); + GenericObjectEditor.setHideProperty(getClass(), "printTimestamps", + !printExtraOutput); + } + + public String printExtraOutputTipText() { + return "do you want to print extra output files"; + } + + public boolean isPrintNetworks() { + return this.printNetworks; + } + + public void setPrintNetworks(boolean b) { + this.printNetworks = b; + } + + public String printNetworksTipText() { + return "Print the underlying networks of each generation"; + } + + public boolean isPrintEdgeRate() { + return this.printEdgeRate; + } + + public void setPrintEdgeRate(boolean b) { + this.printEdgeRate = b; + } + + public String printEdgeRateTipText() { + return "Print the rate with which each edge is used in the optimization run"; + } + + public boolean isPrintMetrics() { + return this.printMetrics; + } + + public void setPrintMetrics(boolean b) { + this.printMetrics = b; + } + + public String printMetricsTipText() { + return "Print the values of all the metrics for every network"; + } + + public boolean isPrintTimestamps() { + return this.printTimestamps; + } + + public void setPrintTimestamps(boolean b) { + this.printTimestamps = b; + } + + public String printTimestampsTipText() { + return "Print the time starting time and a timestamp after each generation"; } -} + + public static void main(String[] args) { + Population pop = new Population(); + GAIndividualBinaryData indy1 = new GAIndividualBinaryData(); + indy1.setBinaryDataLength(8); + GAIndividualBinaryData indy2 = (GAIndividualBinaryData) indy1.clone(); + GAIndividualBinaryData indy3 = (GAIndividualBinaryData) indy1.clone(); + GAIndividualBinaryData indy4 = (GAIndividualBinaryData) indy1.clone(); + GAIndividualBinaryData indy5 = (GAIndividualBinaryData) indy1.clone(); + BitSet data1 = indy1.getBinaryData(); + BitSet data2 = indy2.getBinaryData(); + BitSet data3 = indy3.getBinaryData(); + BitSet data4 = indy4.getBinaryData(); + BitSet data5 = indy5.getBinaryData(); + BitSet data6 = indy5.getBinaryData(); + BitSet data7 = indy5.getBinaryData(); + BitSet data8 = indy5.getBinaryData(); + BitSet data9 = indy5.getBinaryData(); + BitSet data10 = indy5.getBinaryData(); + BitSet data11 = indy5.getBinaryData(); + BitSet data12 = indy5.getBinaryData(); + BitSet data13 = indy5.getBinaryData(); + BitSet data14 = indy5.getBinaryData(); + BitSet data15 = indy5.getBinaryData(); + BitSet data16 = indy5.getBinaryData(); + + data1.set(0, true); + data1.set(1, false); + data1.set(2, true); + data1.set(3, false); + data1.set(4, true); + data1.set(5, true); + data1.set(6, false); + data1.set(7, false); + + data5.set(0, true); + data5.set(1, false); + data5.set(2, true); + data5.set(3, false); + data5.set(4, false); + data5.set(5, true); + data5.set(6, true); + data5.set(7, true); + data6.set(0, true); + data6.set(1, false); + data6.set(2, true); + data6.set(3, false); + data6.set(4, true); + data6.set(5, true); + data6.set(6, false); + data6.set(7, false); + data7.set(0, true); + data7.set(1, false); + data7.set(2, true); + data7.set(3, false); + data7.set(4, true); + data7.set(5, true); + data7.set(6, false); + data7.set(7, false); + + data2.set(0, true); + data2.set(1, false); + data2.set(2, true); + data2.set(3, false); + data2.set(4, true); + data2.set(5, true); + data2.set(6, false); + data2.set(7, false); + data8.set(0, true); + data8.set(1, false); + data8.set(2, true); + data8.set(3, false); + data8.set(4, true); + data8.set(5, true); + data8.set(6, false); + data8.set(7, false); + data9.set(0, true); + data9.set(1, false); + data9.set(2, true); + data9.set(3, false); + data9.set(4, true); + data9.set(5, true); + data9.set(6, false); + data9.set(7, false); + data10.set(0, true); + data10.set(1, false); + data10.set(2, true); + data10.set(3, false); + data10.set(4, true); + data10.set(5, true); + data10.set(6, false); + data10.set(7, false); + + data3.set(0, true); + data3.set(1, false); + data3.set(2, true); + data3.set(3, false); + data3.set(4, false); + data3.set(5, false); + data3.set(6, true); + data3.set(7, true); + data11.set(0, true); + data11.set(1, false); + data11.set(2, true); + data11.set(3, false); + data11.set(4, false); + data11.set(5, false); + data11.set(6, true); + data11.set(7, true); + data12.set(0, true); + data12.set(1, false); + data12.set(2, true); + data12.set(3, false); + data12.set(4, false); + data12.set(5, false); + data12.set(6, true); + data12.set(7, true); + data13.set(0, true); + data13.set(1, false); + data13.set(2, true); + data13.set(3, false); + data13.set(4, false); + data13.set(5, false); + data13.set(6, true); + data13.set(7, true); + + data4.set(0, true); + data4.set(1, false); + data4.set(2, true); + data4.set(3, false); + data4.set(4, false); + data4.set(5, false); + data4.set(6, true); + data4.set(7, true); + data14.set(0, true); + data14.set(1, false); + data14.set(2, true); + data14.set(3, false); + data14.set(4, false); + data14.set(5, false); + data14.set(6, true); + data14.set(7, true); + data15.set(0, true); + data15.set(1, false); + data15.set(2, true); + data15.set(3, false); + data15.set(4, false); + data15.set(5, false); + data15.set(6, true); + data15.set(7, true); + data16.set(0, true); + data16.set(1, false); + data16.set(2, true); + data16.set(3, false); + data16.set(4, false); + data16.set(5, false); + data16.set(6, true); + data16.set(7, true); + + // data5.set(0, true); + // data5.set(1, true); + // data5.set(2, true); + indy1.SetBinaryGenotype(data1); + indy2.SetBinaryGenotype(data2); + indy3.SetBinaryGenotype(data3); + indy4.SetBinaryGenotype(data4); + indy5.SetBinaryGenotype(data5); + pop.add(indy1); + pop.add(indy2); + pop.add(indy3); + pop.add(indy4); + pop.add(indy5); + BOA b = new BOA(); + b.init(); + b.optimize(); + b.optimize(); + b.optimize(); + b.optimize(); + b.optimize(); + // b.generateGreedy(pop); + // System.out.println(pop.getStringRepresentation()); + // b.print(); + // b.printNetworkToFile("test"); + } + +} \ No newline at end of file diff --git a/src/eva2/tools/math/BayNet.java b/src/eva2/tools/math/BayNet.java index 4baefd3d..2400009d 100644 --- a/src/eva2/tools/math/BayNet.java +++ b/src/eva2/tools/math/BayNet.java @@ -3,12 +3,13 @@ package eva2.tools.math; import java.util.ArrayList; import java.util.Arrays; import java.util.BitSet; +import java.util.HashSet; import java.util.LinkedList; import java.util.List; import eva2.gui.BeanInspector; +import eva2.server.go.enums.BOAScoringMethods; import eva2.server.go.individuals.AbstractEAIndividual; -import eva2.server.go.individuals.GAIndividualBinaryData; import eva2.server.go.individuals.InterfaceDataTypeBinary; import eva2.server.go.individuals.InterfaceGAIndividual; import eva2.server.go.populations.Population; @@ -16,12 +17,15 @@ import eva2.tools.Pair; public class BayNet { - private boolean[][] network = null; - private int dimension = 5; - private BayNode[] nodes = null; - private List rootNodes = new LinkedList(); - private double upperProbLimit = 0.9; - private double lowerProbLimit = 0.1; + private boolean[][] network = null; + private int dimension = 3; + private BayNode[] nodes = null; + private List rootNodes = new LinkedList(); + private double upperProbLimit = 0.9; + private double lowerProbLimit = 0.1; + private BOAScoringMethods scoringMethod = BOAScoringMethods.BDM; + private double[] scoreArray = null; +// private String tables = ""; public BayNet(int dimension, double upperLimit, double lowerLimit){ this.dimension = dimension; @@ -37,9 +41,9 @@ public class BayNet { for(int i=0; i(); - for(BayNode node: b.rootNodes){ - this.rootNodes.add(this.nodes[node.getId()]); + this.rootNodes = new LinkedList(); + for(Integer node: b.rootNodes){ + this.rootNodes.add(node); } this.upperProbLimit = b.upperProbLimit; this.lowerProbLimit = b.lowerProbLimit; @@ -69,8 +73,10 @@ public class BayNet { this.nodes = new BayNode[this.dimension]; for(int i=0; i result = new LinkedList(); + for(Integer i: this.rootNodes){ + result.add(this.nodes[i]); + } + return result; } /** @@ -183,7 +193,7 @@ public class BayNet { * @param i the node from which the edge comes * @param j the node to which the edge points */ - public void removeEdge(int i, int j){ + public void removeEdge(Integer i, Integer j){ if(this.network[i][j]){ this.network[i][j] = false; this.nodes[j].decrNumberOfParents(); @@ -191,7 +201,7 @@ public class BayNet { this.nodes[j].removeParent(i); this.nodes[j].generateNewPTable(); if(this.nodes[j].getNumberOfParents() == 0){ - this.rootNodes.add(nodes[j]); + this.rootNodes.add(j); } } } @@ -201,16 +211,41 @@ public class BayNet { * @param i edge from this node * @param j edge to this node */ - public void addEdge(int i, int j){ - if(!this.network[i][j]){ - this.network[i][j] = true; - this.nodes[j].incrNumberOfParents(); - this.nodes[j].generateNewPTable(); - this.rootNodes.remove(this.nodes[j]); - this.nodes[i].addChild(j); - this.nodes[j].addParent(i); + public void addEdge(Integer i, Integer j){ + if(i!=j){ + if(!this.network[i][j]){ + this.network[i][j] = true; + this.rootNodes.remove(j); + this.nodes[j].incrNumberOfParents(); + this.nodes[j].generateNewPTable(); + this.nodes[i].addChild(j); + this.nodes[j].addParent(i); + } } } + + private int findNext(double[] probabilities){ + int result = -1; + for(int i=0; i parents = getParents(currentNode); + boolean possible = true; + for(BayNode node: parents){ + if(probabilities[node.getId()]==-1){ + possible = false; + } + } + if(!possible){ + continue; + } + result = i; + break; + } + return result; + } /** * find the next value where all the parents are already set @@ -218,7 +253,12 @@ public class BayNet { * @return */ private int findNext(double[] probabilities, List nodes){ + nodes = removeDuplicate(nodes); for(BayNode node: nodes){ + if(node.getCalculated()){ + continue; + } + node.setCalculated(true); List parents = getParents(node); boolean possible = false; for(BayNode p: parents){ @@ -230,12 +270,23 @@ public class BayNet { } } if(possible){ + resetCalculated(); return node.getId(); } } + resetCalculated(); return -1; } + private List removeDuplicate(List nodes) { + //Create a HashSet which allows no duplicates + HashSet hashSet = new HashSet(nodes); + + //Assign the HashSet to a new ArrayList + ArrayList arrayList2 = new ArrayList(hashSet) ; + return arrayList2; + } + /** * calculate a new BitSet according to the network * @param data the BitSet that will be calculated @@ -254,19 +305,50 @@ public class BayNet { int id = node.getId(); probabilities[id] = node.getProbability(0); data.set(id, RNG.flipCoin(probabilities[id])); + node.setCalculated(true); } // find the next node that can be evaluated - List toCalculate = getChildren(nodes); - int next = findNext(probabilities, toCalculate); +// List toCalculate = getChildren(nodes); +// int next = findNext(probabilities, toCalculate); + int next = findNext(probabilities); while(next != -1){ - toCalculate.remove(this.nodes[next]); - probabilities[next] = calculateNextProbability(data, toCalculate, next); +// toCalculate.remove(this.nodes[next]); + this.nodes[next].setCalculated(true); +// toCalculate = addToToCalculate(toCalculate, this.nodes[next]); +// toCalculate.addAll(getChildren(this.nodes[next])); +// probabilities[next] = calculateNextProbability(data, toCalculate, next); + probabilities[next] = calculateNextProbability(data, next); data.set(next, RNG.flipCoin(probabilities[next])); - next = findNext(probabilities, toCalculate); +// next = findNext(probabilities, toCalculate); + next = findNext(probabilities); } + resetCalculated(); return data; } + private List addToToCalculate(List toCalculate, + BayNode next) { + List toAdd = getChildren(next); + for(int i=0; i=0; i--){ + if(data.get(parId[i])){ + par += Math.pow(2, i); + } + } + return this.nodes[next].getProbability(par); + } + /** * calculate the next probability * @param data the already calculated data @@ -279,10 +361,12 @@ public class BayNet { toCalculate.addAll(getChildren(this.nodes[next])); int[] parId = calculateSortedParentIds(next); int prob = 0; + int cnt = 0; for(int j=parId.length-1; j>=0; j--){ if(data.get(parId[j])){ prob += (int) Math.pow(2, j); } + cnt++; } return this.nodes[next].getProbability(prob); } @@ -304,23 +388,23 @@ public class BayNet { return parId; } - /** - * generate an array of the parents plus the given node, sorted by there id - * @param id the id of the node - * @return the sorted parent-ids - */ - private int[] calculateSortedParentPlusNodeIds(int id) { - List nodes = getParents(this.nodes[id]); - nodes.add(this.nodes[id]); - int[] sortedIds = new int[nodes.size()]; - int i=0; - for(BayNode nod: nodes){ - sortedIds[i] = nod.getId(); - i++; - } - Arrays.sort(sortedIds); - return sortedIds; - } +// /** +// * generate an array of the parents plus the given node, sorted by there id +// * @param id the id of the node +// * @return the sorted parent-ids +// */ +// private int[] calculateSortedParentPlusNodeIds(int id) { +// List nodes = getParents(this.nodes[id]); +// nodes.add(this.nodes[id]); +// int[] sortedIds = new int[nodes.size()]; +// int i=0; +// for(BayNode nod: nodes){ +// sortedIds[i] = nod.getId(); +// i++; +// } +// Arrays.sort(sortedIds); +// return sortedIds; +// } private void resetCalculated(){ for(int i=0; i edge : deletedEdges) { this.network[edge.head][edge.tail] = true; } @@ -402,28 +485,21 @@ public class BayNet { } private double getPrior(List parents, Population pop){ - return (double) pop.size() / Math.pow(2.0, (double) parents.size()); + double result = 1.0; + switch(this.scoringMethod){ + case BDM: result = ((double) pop.size()) / Math.pow(2.0, (double) parents.size()); break; + case K2: result = 2.0; + } + return result; } private double getPrior(List parents, BayNode current, Population pop){ - return getPrior(parents, pop) / 2.0; - } - - private void setRootPTables(Population pop){ - List rootNodes = getRootNodes(); - for(BayNode node: rootNodes){ - int id = node.getId(); - double count = 0; - for(int i=0; i parents = getParents(currentNode); -// System.out.println("parents: "+parents.size()); // get the parentIds sorted (for the lookup) + int[] parId = new int[0]; if(!parents.isEmpty()){ - int[] parId = calculateSortedParentIds(i); - // the parentIds plus the id of the current node sorted (for the lookup - int[] nodeIds = calculateSortedParentPlusNodeIds(i); - double[] pTable = currentNode.getPTable(); - for(int j=0; j 0){ for(int k=0; k<2; k++){ - double cnt = numberSetCorrectly(pop2, j, k, nodeIds, parId); - double numeratorSecondFraction = SpecialFunction.gamma(getPrior(parents, currentNode, pop) + cnt); - double denumeratorSecondFraction = SpecialFunction.gamma(getPrior(parents, currentNode, pop)); - double secondFraction = numeratorSecondFraction / denumeratorSecondFraction; - result = result * secondFraction; - double prob = cnt / (double) pop2.size(); - setProbability(currentNode, j, prob); - cnt = 0; +// double secondFraction = 0.0; + switch(this.scoringMethod){ + case BDM: result = result + Math.log(secondFractionBDM(pop, currentNode, parents, j, pop2, k)); break; + case K2: result = result + Math.log(secondFractionBDM(pop, currentNode, parents, j, pop2, k)); break; + case BIC: result = result + secondFractionBIC(pop2, currentNode, k, j); break; + } +// result = result + Math.log(secondFraction); } } } @@ -479,46 +564,239 @@ public class BayNet { return result; } + public void initScoreArray(Population pop){ + //for every node + for(int i=0; i parents = getParents(currentNode); + // get the parentIds sorted (for the lookup) + int[] parId = new int[0]; + if(!parents.isEmpty()){ + parId = calculateSortedParentIds(i); + } + double[] pTable = currentNode.getPTable(); + switch(this.scoringMethod){ + case BIC: result = result - (Math.log(pop.size()) * pTable.length * 2)/2;break; + default: break; + } + for(int j=0; j 0){ + for(int k=0; k<2; k++){ +// double secondFraction = 0.0; + switch(this.scoringMethod){ + case BDM: result = result + Math.log(secondFractionBDM(pop, currentNode, parents, j, pop2, k)); break; + case K2: result = result + Math.log(secondFractionBDM(pop, currentNode, parents, j, pop2, k)); break; + case BIC: result = result + secondFractionBIC(pop2, currentNode, k, j); break; + } +// result = result + Math.log(secondFraction); + } + } + } + scoreArray[i] = result; + } + } + + public void updateScoreArray(Population pop, int i){ + //for every node + double result = 0.0; + BayNode currentNode = this.nodes[i]; + //get the parents + List parents = getParents(currentNode); + // get the parentIds sorted (for the lookup) + int[] parId = new int[0]; + if(!parents.isEmpty()){ + parId = calculateSortedParentIds(i); + } + double[] pTable = currentNode.getPTable(); + switch(this.scoringMethod){ + case BIC: result = result - (Math.log(pop.size()) * pTable.length * 2)/2;break; + default: break; + } + for(int j=0; j 0){ + for(int k=0; k<2; k++){ + switch(this.scoringMethod){ + case BDM: result = result + Math.log(secondFractionBDM(pop, currentNode, parents, j, pop2, k)); break; + case K2: result = result + Math.log(secondFractionBDM(pop, currentNode, parents, j, pop2, k)); break; + case BIC: result = result + secondFractionBIC(pop2, currentNode, k, j); break; + } + } + } + } + scoreArray[i] = result; + } + + public double getNewScore(Population pop, int i){ + double result = 0; + for(int j=0; j parents = getParents(currentNode); + // get the parentIds sorted (for the lookup) + int[] parId = new int[0]; + if(!parents.isEmpty()){ + parId = calculateSortedParentIds(i); + } + double[] pTable = currentNode.getPTable(); + switch(this.scoringMethod){ + case BIC: result = result - (Math.log(pop.size()) * pTable.length * 2)/2;break; + default: break; + } + for(int j=0; j 0){ + for(int k=0; k<2; k++){ + switch(this.scoringMethod){ + case BDM: result = result + Math.log(secondFractionBDM(pop, currentNode, parents, j, pop2, k)); break; + case K2: result = result + Math.log(secondFractionBDM(pop, currentNode, parents, j, pop2, k)); break; + case BIC: result = result + secondFractionBIC(pop2, currentNode, k, j); break; + } + } + } + } + return result; + } + + private double secondFractionBIC(Population pop2, BayNode currentNode, int k, int j){ + double result = 0.0; + double Nijk = numberSetCorrectly(pop2, k, currentNode.getId()); + if(Nijk>0){ + result = (double)Nijk * Math.log((double) Nijk); + } + if(k==1){ + double prob = Nijk / (double) pop2.size(); + setProbability(currentNode, j, prob); + } + return result; + } + + private double firstFractionBIC(Population pop2){ + double result = 0.0; + if(pop2.size()>0){ + result = ((double) pop2.size()) * Math.log((double) pop2.size()); + } + return result; + } + + private double secondFractionBDM(Population pop, BayNode currentNode, + List parents, int j, Population pop2, int k) { + double mXiPiXi = numberSetCorrectly(pop2, k, currentNode.getId()); + double mDashXiPiXi = getPrior(parents, currentNode, pop); + double numeratorSecondFraction = gamma(mDashXiPiXi + mXiPiXi); + double denumeratorSecondFraction = gamma(mDashXiPiXi); + double secondFraction = numeratorSecondFraction / denumeratorSecondFraction; + if(k==1){ + double prob = mXiPiXi / (double) pop2.size(); + setProbability(currentNode, j, prob); + } + return secondFraction; + } + + private double firstFractionBDM(Population pop, List parents, + Population pop2) { + double mPiXi = (double) pop2.size(); + double mDashPiXi = getPrior(parents, pop); + double numeratorFirstFraction = gamma(mDashPiXi); + double denominatorFirstFraction = gamma(mDashPiXi + mPiXi); + double firstFraction = numeratorFirstFraction / denominatorFirstFraction; + return firstFraction; + } + +// public String getTables(){ +// return this.tables; +// } + +// public void setTables(String s){ +// this.tables = ""; +// this.tables = s; +// } + private void setProbability(BayNode n, int j, double prob){ n.setPTable(j, Math.min(upperProbLimit, Math.max(lowerProbLimit, prob))); } - private double numberSetCorrectly(Population pop, int j, int k, int[] Ids, int[] parIds){ + private double numberSetCorrectly(Population pop, int k, int Id){ double result = 0.0; - String binaryString = Integer.toBinaryString(j); - while(binaryString.length() < parIds.length){ - binaryString = "0"+binaryString; - } - boolean found = false; - boolean end = false; - int different = 0; - for(int i=0; iBitSet from the position offset by the + * given amount of bits. + * + * @param bitSet the BitSet to operate on + * @param offset the offset in the bit set + * @param length the length of the bit string that should represent the given value + * @param value the value to encode in the bit set + * @return the modified bit set + * @throws RuntimeException if length is greater than the amount of bits in an + * integer value + * @throws RuntimeException if value is greather than the value encodeable by the + * given amount of bits or if value == Integer.MIN_VALUE (no absolute value awailable as + * int) + */ + public static BitSet intToBitSet(BitSet bitSet, int offset, int length, int value) + { + // checking the bit length + if (length > Integer.SIZE) + throw new RuntimeException("You can not set a higher length than " + Integer.SIZE + + " bits."); + length += 1; + // checking whether the value fits into the bit string of length - 1 + int absValue = Math.abs(value); + if (absValue > Math.pow(2.0, length - 1 - 1) * 2 - 1 || value == Integer.MIN_VALUE) + throw new RuntimeException("The value of " + value + + " does not fit into a bit string of " + (length - 1) + " bits."); + + // setting all bits to zero + bitSet.clear(offset, offset + length - 1); + + // setting up the number in reverse order + int mask = 1; + for (int i = 0; i < length; ++i, mask <<= 1) + if ((mask & absValue) > 0) + bitSet.set(offset + i); + + // setting up the sign + if (value < 0) + bitSet.set(offset + length - 1); + + return bitSet; + } /** * is the BitSet of the individual set correctly corresponding to the binary String and the parId @@ -546,18 +868,14 @@ public class BayNet { * @return is the data set correctly */ private boolean isSetCorrectly(int[] ids, BitSet data, int j) { - boolean setCorrectly = false; - for(int m=0; m0) && (data.get(ids[m]))){ - setCorrectly = true; - }else if(!((j & (1<0) && (!data.get(ids[m]))){ - setCorrectly = true; - }else{ - setCorrectly = false; - m = j+10; + int value = 0; +// BitSet toTest = new BitSet(length); + for(int i=0; i\n"; + result = result + "\n"; + result = result + " \n"; + result = result + " \n"; + result = result + " \n"; + result = result + " \n"; + result = result + " \n"; + result = result + " \n"; + result = result + " \n"; + result = result + " \n"; + result = result + " \n"; + result = result + " \n"; + result = result + " \n"; + result = result + " \n"; + result = result + " \n"; + result = result + " \n"; + for(int i=0; i pair = generateTable(i); + Integer length = pair.getHead(); + String table = pair.getTail(); + int x = 40+100*(i % 20); + int y = (int) (40+100*Math.floor(((double)i) / 20)); + Double height = 40+11*Math.pow(2, length-1); + Double width = (double) (40+10*length); + result = result + " \n"; + result = result + " \n"; + result = result + " \n"; + result = result + " \n"; + result = result + " \n"; + result = result + " \n"; + result = result + " \n"; + result = result + " " + i + table + "\n"; + result = result + " \n"; + result = result + " \n"; + result = result + " \n"; + result = result + " \n"; + } + int cnt = 0; + for(int i=0; i\n"; + result = result + " \n"; + result = result + " \n"; + result = result + " \n"; + result = result + " \n"; + result = result + " \n"; + result = result + " \n"; + result = result + " \n"; + result = result + " \n"; + result = result + " \n"; + result = result + " \n"; + cnt++; + } + } + } + result = result + " \n"; + result = result + " \n"; + result = result + " \n"; + result = result + " \n"; + result = result + "\n"; + return result; + } + + private Pair generateTable(int i) { + String result = ""; + double [] pTable = nodes[i].getPTable(); + int length = Integer.toBinaryString(pTable.length).length(); + for(int j=0; j p = new Pair(); + p.setHead(length); + p.setTail(result); + return p; + } /** * has the network already an edge from node i to node j @@ -587,51 +989,82 @@ public class BayNet { } public static void main(String[] args){ - BayNet b = new BayNet(3, 0.9, 0.1); - b.addEdge(0, 2); - b.addEdge(1, 2); - Population pop = new Population(); - GAIndividualBinaryData indy1 = new GAIndividualBinaryData(); - indy1.setBinaryDataLength(3); - GAIndividualBinaryData indy2 = (GAIndividualBinaryData) indy1.clone(); - GAIndividualBinaryData indy3 = (GAIndividualBinaryData) indy1.clone(); - GAIndividualBinaryData indy4 = (GAIndividualBinaryData) indy1.clone(); - GAIndividualBinaryData indy5 = (GAIndividualBinaryData) indy1.clone(); - BitSet data1 = indy1.getBinaryData(); - BitSet data2 = indy2.getBinaryData(); - BitSet data3 = indy3.getBinaryData(); - BitSet data4 = indy4.getBinaryData(); - BitSet data5 = indy5.getBinaryData(); - data1.set(0, true); - data1.set(1, true); - data1.set(2, false); - data2.set(0, true); - data2.set(1, true); - data2.set(2, true); - data3.set(0, false); - data3.set(1, true); - data3.set(2, false); - data4.set(0, false); - data4.set(1, true); - data4.set(2, true); - data5.set(0, true); - data5.set(1, false); - data5.set(2, false); - indy1.SetBinaryGenotype(data1); - indy2.SetBinaryGenotype(data2); - indy3.SetBinaryGenotype(data3); - indy4.SetBinaryGenotype(data4); - indy5.SetBinaryGenotype(data5); - pop.add(indy1); - pop.add(indy2); - pop.add(indy3); - pop.add(indy4); - pop.add(indy5); - -// System.out.println("-----"); +// BayNet b = new BayNet(3, 0.9, 0.1); +//// b.addEdge(0, 2); +// b.addEdge(1, 2); +// Population pop = new Population(); +// GAIndividualBinaryData indy1 = new GAIndividualBinaryData(); +// indy1.setBinaryDataLength(3); +// GAIndividualBinaryData indy2 = (GAIndividualBinaryData) indy1.clone(); +// GAIndividualBinaryData indy3 = (GAIndividualBinaryData) indy1.clone(); +// GAIndividualBinaryData indy4 = (GAIndividualBinaryData) indy1.clone(); +// GAIndividualBinaryData indy5 = (GAIndividualBinaryData) indy1.clone(); +// BitSet data1 = indy1.getBinaryData(); +// BitSet data2 = indy2.getBinaryData(); +// BitSet data3 = indy3.getBinaryData(); +// BitSet data4 = indy4.getBinaryData(); +// BitSet data5 = indy5.getBinaryData(); +// data1.set(0, false); +// data1.set(1, true); +// data1.set(2, true); +// +// data2.set(0, true); +// data2.set(1, false); +// data2.set(2, true); +// +// data3.set(0, true); +// data3.set(1, true); +// data3.set(2, true); +// +// data4.set(0, true); +// data4.set(1, true); +// data4.set(2, true); +// +// data5.set(0, true); +// data5.set(1, true); +// data5.set(2, true); +// indy1.SetBinaryGenotype(data1); +// indy2.SetBinaryGenotype(data2); +// indy3.SetBinaryGenotype(data3); +// indy4.SetBinaryGenotype(data4); +// indy5.SetBinaryGenotype(data5); +// pop.add(indy1); +// pop.add(indy2); +// pop.add(indy3); +// pop.add(indy4); +// pop.add(indy5); +// +//// System.out.println("-----"); // System.out.println(pop.getStringRepresentation()); // System.out.println("-----"); - System.out.println(b.bayesianDirichletMetric(pop)); +// System.out.println(b.bayesianDirichletMetric(pop)); +// b.print(); + double val = SpecialFunction.gamma(26); + double val2 = SpecialFunction.gamma(51); + double val3 = (SpecialFunction.gamma(12+12.5))/SpecialFunction.gamma(12.5); + double val4 = (SpecialFunction.gamma(13+12.5))/SpecialFunction.gamma(12.5); + double erg = val/val2; + erg = erg * val3 * val4; + System.out.println(erg); + } + + public void setScoringMethod(BOAScoringMethods method){ + this.scoringMethod = method; + } + + public BOAScoringMethods getScoringMethod(){ + return this.scoringMethod; } -} + public int[][] adaptEdgeRate(int[][] edgeRate) { + for(int i=0; i