diff --git a/src/javaeva/OptimizerFactory.java b/src/javaeva/OptimizerFactory.java index 03a2f62d..7ce14ab6 100644 --- a/src/javaeva/OptimizerFactory.java +++ b/src/javaeva/OptimizerFactory.java @@ -5,18 +5,21 @@ import javaeva.server.go.IndividualInterface; import javaeva.server.go.InterfaceTerminator; import javaeva.server.go.individuals.AbstractEAIndividual; import javaeva.server.go.individuals.InterfaceESIndividual; +import javaeva.server.go.operators.cluster.ClusteringDensityBased; import javaeva.server.go.operators.crossover.CrossoverESDefault; import javaeva.server.go.operators.mutation.MutateESCovarianceMartixAdaption; -import javaeva.server.go.operators.mutation.MutateESDefault; import javaeva.server.go.operators.mutation.MutateESGlobal; import javaeva.server.go.operators.terminators.CombinedTerminator; import javaeva.server.go.operators.terminators.EvaluationTerminator; import javaeva.server.go.populations.Population; import javaeva.server.go.problems.AbstractOptimizationProblem; +import javaeva.server.go.strategies.ClusterBasedNichingEA; import javaeva.server.go.strategies.DifferentialEvolution; import javaeva.server.go.strategies.EvolutionStrategies; import javaeva.server.go.strategies.GeneticAlgorithm; +import javaeva.server.go.strategies.HillClimbing; import javaeva.server.go.strategies.InterfaceOptimizer; +import javaeva.server.go.strategies.MonteCarloSearch; import javaeva.server.go.strategies.ParticleSwarmOptimization; import javaeva.server.go.strategies.Tribes; import javaeva.server.modules.GOParameters; @@ -37,6 +40,9 @@ public class OptimizerFactory { public final static int PSO = 4; public final static int DE = 5; public final static int TRIBES = 6; + public final static int RANDOM = 7; + public final static int HILLCL = 8; + public final static int CBN_ES = 9; public final static int defaultFitCalls = 10000; public final static int randSeed = 0; @@ -47,7 +53,7 @@ public class OptimizerFactory { * @return a String listing the accessible optimizers */ public static String showOptimizers() { - return "1: Standard ES; 2: CMA-ES; 3: GA; 4: PSO; 5: DE; 6: Tribes"; + return "1: Standard ES; 2: CMA-ES; 3: GA; 4: PSO; 5: DE; 6: Tribes; 7: Random (Monte Carlo); 8: HillClimbing; 9: Cluster-based niching ES"; } /** @@ -84,22 +90,45 @@ public class OptimizerFactory { } public static OptimizerRunnable getOptRunnable(final int optType, AbstractOptimizationProblem problem, String outputFilePrefix) { + return getOptRunnable(optType, problem, defaultFitCalls, outputFilePrefix); + } + + public static OptimizerRunnable getOptRunnable(final int optType, AbstractOptimizationProblem problem, int fitCalls, String outputFilePrefix) { + OptimizerRunnable opt = null; switch (optType) { case STD_ES: - return new OptimizerRunnable(standardES(problem), outputFilePrefix); + opt = new OptimizerRunnable(standardES(problem), outputFilePrefix); + break; case CMA_ES: - return new OptimizerRunnable(cmaES(problem), outputFilePrefix); + opt = new OptimizerRunnable(cmaES(problem), outputFilePrefix); + break; case STD_GA: - return new OptimizerRunnable(standardGA(problem), outputFilePrefix); + opt = new OptimizerRunnable(standardGA(problem), outputFilePrefix); + break; case PSO: - return new OptimizerRunnable(standardPSO(problem), outputFilePrefix); + opt = new OptimizerRunnable(standardPSO(problem), outputFilePrefix); + break; case DE: - return new OptimizerRunnable(standardDE(problem), outputFilePrefix); + opt = new OptimizerRunnable(standardDE(problem), outputFilePrefix); + break; case TRIBES: - return new OptimizerRunnable(tribes(problem), outputFilePrefix); + opt = new OptimizerRunnable(tribes(problem), outputFilePrefix); + break; + case RANDOM: + opt = new OptimizerRunnable(monteCarlo(problem), outputFilePrefix); + break; + case HILLCL: + opt = new OptimizerRunnable(hillClimbing(problem), outputFilePrefix); + break; + case CBN_ES: + opt = new OptimizerRunnable(cbnES(problem), outputFilePrefix); + break; + default: + System.err.println("Error: optimizer type " + optType + " is unknown!"); + return null; } - System.err.println("Error: optimizer type " + optType + " is unknown!"); - return null; + if (fitCalls != defaultFitCalls) opt.getGOParams().setTerminator(new EvaluationTerminator(fitCalls)); + return opt; } public static InterfaceTerminator defaultTerminator() { @@ -167,6 +196,7 @@ public class OptimizerFactory { es.setLambda(50); es.setPlusStrategy(false); + // TODO improve this by adding getEAIndividual to AbstractEAIndividual? Object maybeTemplate = BeanInspector.callIfAvailable(problem, "getEAIndividual", null); if ((maybeTemplate != null) && (maybeTemplate instanceof InterfaceESIndividual)) { // Set CMA operator for mutation @@ -227,4 +257,40 @@ public class OptimizerFactory { problem.initPopulation(pop); return makeParams(tr, pop, problem, randSeed, defaultTerminator()); } + + public static GOParameters hillClimbing(AbstractOptimizationProblem problem) { + HillClimbing hc = new HillClimbing(); + hc.SetProblem(problem); + Population pop = new Population(); + pop.setPopulationSize(50); + problem.initPopulation(pop); + return makeParams(hc, pop, problem, randSeed, defaultTerminator()); + } + + public static GOParameters monteCarlo(AbstractOptimizationProblem problem) { + MonteCarloSearch mc = new MonteCarloSearch(); + Population pop = new Population(); + pop.setPopulationSize(50); + problem.initPopulation(pop); + return makeParams(mc, pop, problem, randSeed, defaultTerminator()); + } + + public static GOParameters cbnES(AbstractOptimizationProblem problem) { + ClusterBasedNichingEA cbn = new ClusterBasedNichingEA(); + EvolutionStrategies es = new EvolutionStrategies(); + es.setMyu(15); + es.setLambda(50); + es.setPlusStrategy(false); + cbn.setOptimizer(es); + ClusteringDensityBased clustering = new ClusteringDensityBased(0.1); + cbn.setConvergenceCA((ClusteringDensityBased)clustering.clone()); + cbn.setDifferentationCA(clustering); + cbn.setShowCycle(10); // dont do graphical output + + Population pop = new Population(); + pop.setPopulationSize(100); + problem.initPopulation(pop); + + return makeParams(cbn, pop, problem, randSeed, defaultTerminator()); + } } diff --git a/src/javaeva/OptimizerRunnable.java b/src/javaeva/OptimizerRunnable.java index 2d747469..e50b6b69 100644 --- a/src/javaeva/OptimizerRunnable.java +++ b/src/javaeva/OptimizerRunnable.java @@ -25,9 +25,15 @@ import javaeva.server.stat.StatisticsStandalone; public class OptimizerRunnable implements Runnable { Processor proc; boolean isFinished = false; + boolean doRestart = false; // indicate whether start or restart should be done --> whether pop will be reinitialized. public OptimizerRunnable(GOParameters params, String outputFilePrefix) { + this(params, outputFilePrefix, false); + } + + public OptimizerRunnable(GOParameters params, String outputFilePrefix, boolean restart) { proc = new Processor(new StatisticsStandalone(outputFilePrefix), null, params); + doRestart = restart; } public InterfaceGOParameters getGOParams() { @@ -37,7 +43,9 @@ public class OptimizerRunnable implements Runnable { public void run() { isFinished = false; try { - proc.startOpt(); + proc.setSaveParams(false); + if (doRestart) proc.restartOpt(); + else proc.startOpt(); proc.runOptOnce(); } catch(Exception e) { proc.getStatistics().printToTextListener("Exception in OptimizeThread::run: " + e.getMessage() + "\n"); @@ -62,12 +70,15 @@ public class OptimizerRunnable implements Runnable { public IndividualInterface getSolution() { return proc.getStatistics().getBestSolution(); } - + + public int getProgress() { + return proc.getGOParams().getOptimizer().getPopulation().getFunctionCalls(); + } + public String terminatedBecause() { if (isFinished) { InterfaceTerminator term = proc.getGOParams().getTerminator(); - if (term instanceof CombinedTerminator) return ((CombinedTerminator)term).terminatedBecause(proc.getGOParams().getOptimizer().getPopulation()); - else return "Terminated because " + BeanInspector.toString(term) + " terminated;"; + return term.terminatedBecause(proc.getGOParams().getOptimizer().getPopulation()); } else return "Not yet terminated"; } diff --git a/src/javaeva/gui/BeanInspector.java b/src/javaeva/gui/BeanInspector.java index 684cd25c..e029a92e 100644 --- a/src/javaeva/gui/BeanInspector.java +++ b/src/javaeva/gui/BeanInspector.java @@ -12,9 +12,13 @@ package javaeva.gui; /*==========================================================================* * IMPORTS *==========================================================================*/ -import java.beans.*; +import java.beans.BeanInfo; +import java.beans.IntrospectionException; +import java.beans.Introspector; +import java.beans.PropertyDescriptor; import java.lang.reflect.Array; import java.lang.reflect.Method; +import java.util.List; /* * ==========================================================================* @@ -143,6 +147,19 @@ public class BeanInspector { return sbuf.toString(); } + if (Target instanceof List) { // handle the list case + StringBuffer sbuf = new StringBuffer("[ "); + List lst = (List)Target; + for (Object o : lst) { + sbuf.append(o.toString()); + sbuf.append("; "); + } + sbuf.setCharAt(sbuf.length()-2, ' '); + sbuf.setCharAt(sbuf.length()-1, ']'); + return sbuf.toString(); + } + + Method[] methods = Target.getClass().getDeclaredMethods(); for (int ii = 0; ii < methods.length; ii++) { // check if the object has its own toString method, in this case use it if ((methods[ii].getName().equals("toString") /*|| (methods[ii].getName().equals("getStringRepresentation"))*/) && (methods[ii].getParameterTypes().length == 0)) { diff --git a/src/javaeva/gui/FunctionArea.java b/src/javaeva/gui/FunctionArea.java index 9145b9b5..1016205e 100644 --- a/src/javaeva/gui/FunctionArea.java +++ b/src/javaeva/gui/FunctionArea.java @@ -268,18 +268,33 @@ public class FunctionArea extends DArea implements Serializable { /** * */ - public void setConnectedPoint(double x, double y, int GraphLabel) { - if (m_log == true && y <= 0.0) { - y = 1; -// y = Double.MIN_VALUE; - if (notifyNegLog) { - System.err.println("Warning: trying to plot value (" + x + "/" + y + ") with y < 0 in logarithmic mode! Setting y to " + y); - notifyNegLog = false; - } + public void setConnectedPoint(double x, double y, int graphLabel) { + if (!checkLogValidYValue(x, y, graphLabel)) { + if (m_log) toggleLog(); } - getGraphPointSet(GraphLabel).addDPoint(x, y); +// if (y <= 0.0) { +//// y = Double.MIN_VALUE; +// if (notifyNegLog) { +// System.err.println("Warning: trying to plot value (" + x + "/" + y + ") with y <= 0 in logarithmic mode! Setting y to " + 1e-30); +// notifyNegLog = false; +// } +// y = 1e-30; +// } + getGraphPointSet(graphLabel).addDPoint(x, y); } +// public void setConnectedPoint(double x, double y, int GraphLabel) { +// if (m_log == true && y <= 0.0) { +//// y = Double.MIN_VALUE; +// if (notifyNegLog) { +// System.err.println("Warning: trying to plot value (" + x + "/" + y + ") with y <= 0 in logarithmic mode! Setting y to " + 1e-30); +// notifyNegLog = false; +// } +// y = 1e-30; +// } +// getGraphPointSet(GraphLabel).addDPoint(x, y); +// +// } public void addGraphPointSet(GraphPointSet d) { this.m_PointSetContainer.add(d); @@ -297,9 +312,9 @@ public class FunctionArea extends DArea implements Serializable { /** * */ - public void clearGraph(int GraphLabel) { - getGraphPointSet(GraphLabel).removeAllPoints(); - m_PointSetContainer.remove(getGraphPointSet(GraphLabel)); + public void clearGraph(int graphLabel) { + getGraphPointSet(graphLabel).removeAllPoints(); + m_PointSetContainer.remove(getGraphPointSet(graphLabel)); repaint(); notifyNegLog = true; } @@ -403,18 +418,35 @@ public class FunctionArea extends DArea implements Serializable { * */ public void setUnconnectedPoint(double x, double y, int GraphLabel) { - if (m_log == true && y <= 0.0) { - if (notifyNegLog) { - System.err.println("Warning: trying to plot value (" + x + "/" + y + ") with y < 0 in logarithmic mode! Setting y to " + y ); - notifyNegLog = false; - } - y = 1; + if (!checkLogValidYValue(x, y, GraphLabel)) { + if (m_log) toggleLog(); } this.getGraphPointSet(GraphLabel).addDPoint(x, y); this.getGraphPointSet(GraphLabel).setConnectedMode(false); repaint(); } + + protected boolean checkLoggable() { + double minY = Double.MAX_VALUE; + for (int i = 0; i < m_PointSetContainer.size(); i++) { + DPointSet pSet = (m_PointSetContainer.get(i).getConnectedPointSet()); + if (pSet.getSize() > 0) minY = Math.min(minY, pSet.getMinYVal()); + } +// if (TRACE) System.out.println("min is " + minY); + return (minY > 0); + } + protected boolean checkLogValidYValue(double x, double y, int graphLabel) { + if (y <= 0.0) { + if (m_log && notifyNegLog) { + System.err.println("Warning: trying to plot value (" + x + "/" + y + ") with y <= 0 in logarithmic mode!" ); + notifyNegLog = false; + } + return false; + } + return true; + } + Color[] Colors = new Color[] {Color.black, Color.red, Color.blue, Color.green,Color.magenta, Color.orange, Color.pink, Color.yellow}; public void setGraphColor(int GraphLabel,int colorindex) { @@ -467,6 +499,10 @@ public class FunctionArea extends DArea implements Serializable { */ public void toggleLog() { //System.out.println("ToggleLog log was: "+m_log); + if (!m_log && !checkLoggable()) { + System.err.println("Cant toggle log with values <= 0!"); + return; + } if (m_log == false) { setMinRectangle(0.001, 0.001, 1, 1); //setVisibleRectangle( 0.001, 0.001, 100000, 1000 ); diff --git a/src/javaeva/gui/Graph.java b/src/javaeva/gui/Graph.java index 5e52518d..d62bb677 100644 --- a/src/javaeva/gui/Graph.java +++ b/src/javaeva/gui/Graph.java @@ -79,7 +79,7 @@ public class Graph implements Serializable { * Add a graph to this graph object. Uses "force" for mismatching point counts, but returns false * if force was used and points possibly have been lost. * - * @return true if the graph could be added direcly or false if the graph was added by force losing some data points + * @return true if the graph could be added directly or false if the graph was added by force losing some data points * @see PlotInterface.addGraph */ public boolean addGraph(Graph x) { diff --git a/src/javaeva/gui/GraphPointSet.java b/src/javaeva/gui/GraphPointSet.java index d14bf197..6bdbebe0 100644 --- a/src/javaeva/gui/GraphPointSet.java +++ b/src/javaeva/gui/GraphPointSet.java @@ -105,26 +105,32 @@ public class GraphPointSet { // else // if (GraphLabel == 10) m_Color = (Color.black); - int k = GraphLabel%10; - switch(k) { - case 0: m_Color = Color.black; break; - case 1: m_Color = Color.red; break; - case 2: m_Color = Color.blue; break; - case 3: m_Color = Color.pink; break; - case 4: m_Color = Color.orange; break; - case 5: m_Color = Color.gray; break; - case 6: m_Color = Color.green; break; - case 7: m_Color = Color.magenta; break; - case 8: m_Color = Color.cyan; break; - case 9: m_Color = Color.darkGray; break; - } - + m_Color=labelToColor(GraphLabel); + m_ConnectedPointSet.setColor(m_Color); // m_PointSet_1.setColor(m_Color); // m_PointSet_2.setColor(m_Color); // m_PointSet_3.setColor(m_Color); initGraph(Area); } + + private Color labelToColor(int label) { + Color c = Color.black; + int k = label%10; + switch(k) { + case 0: c = Color.black; break; + case 1: c = Color.red; break; + case 2: c = Color.blue; break; + case 3: c = Color.pink; break; + case 4: c = Color.orange; break; + case 5: c = Color.gray; break; + case 6: c = Color.green; break; + case 7: c = Color.magenta; break; + case 8: c = Color.cyan; break; + case 9: c = Color.darkGray; break; + } + return c; + } /** * */ @@ -158,40 +164,11 @@ public class GraphPointSet { m_ConnectedPointSet.setConnected(true); m_Color = Color.black; - // int colors = 5; -// int b = GraphLabel*(int)(255/10)%255; -// int r = (GraphLabel-colors)*(int)(255/10)%255; -// int g = (GraphLabel-2*colors)*(int)(255/10)%255; -// if (r<0) r = 0; -// if (g<0) g = 0; -// m_Color = new Color(r,g,b); - if (GraphLabel == 0) m_Color = (Color.black); - else - if (GraphLabel == 1) m_Color = (Color.red); - else - if (GraphLabel == 2) m_Color = (Color.blue); - else - if (GraphLabel == 3) m_Color = (Color.red); - else - if (GraphLabel == 4) m_Color = (Color.black); - else - if (GraphLabel == 5) m_Color = (Color.red); - else - if (GraphLabel == 6) m_Color = (Color.blue); - else - if (GraphLabel == 7) m_Color = (Color.red); - else - if (GraphLabel == 8) m_Color = (Color.blue); - else - if (GraphLabel == 9) m_Color = (Color.red); - else - if (GraphLabel == 10) m_Color = (Color.black); + m_Color = labelToColor(GraphLabel); m_ConnectedPointSet.setColor(m_Color); -// m_PointSet_1.setColor(m_Color); -// m_PointSet_2.setColor(m_Color); -// m_PointSet_3.setColor(m_Color); + } /** * diff --git a/src/javaeva/gui/JTextoutputFrame.java b/src/javaeva/gui/JTextoutputFrame.java index c2ee490f..caeb79db 100644 --- a/src/javaeva/gui/JTextoutputFrame.java +++ b/src/javaeva/gui/JTextoutputFrame.java @@ -52,16 +52,20 @@ public class JTextoutputFrame implements JTextoutputFrameInterface, /** * */ - public void print (String Text) { + public void print(String Text) { //System.out.println("Print:"+Text); if (m_firstprint==true) { m_firstprint = false; createFrame(); } - m_TextArea.append (Text+"\n"); + m_TextArea.append(Text); m_TextArea.repaint(); } + public void println(String txt) { + print(txt+'\n'); + } + public void setShow(boolean bShow) { if (frame.isVisible() != bShow) { if (frame.isVisible()) { diff --git a/src/javaeva/gui/TopoPlot.java b/src/javaeva/gui/TopoPlot.java index 4848b233..39b7f114 100644 --- a/src/javaeva/gui/TopoPlot.java +++ b/src/javaeva/gui/TopoPlot.java @@ -90,7 +90,8 @@ public class TopoPlot extends Plot { ry = problem.get2DBorder()[1][0]+y*rh; pos[0] = rx; pos[1] = ry; DRectangle rect = new DRectangle(rx,ry,rw,rh); - Color color = new Color(colorBar.getRGB((float)(problem.functionValue(pos)/fitRange))); // Color color = new Color(255,(int)(problem.doEvaluation(pos)[0]/fitRange*255),(int)(problem.doEvaluation(pos)[0]/fitRange*255)); + Color color = new Color(colorBar.getRGB((float)((problem.functionValue(pos)-min)/fitRange))); // Color color = new Color(255,(int)(problem.doEvaluation(pos)[0]/fitRange*255),(int)(problem.doEvaluation(pos)[0]/fitRange*255)); +// Color color = new Color(colorBar.getRGB((float)(problem.functionValue(pos)/fitRange))); // Color color = new Color(255,(int)(problem.doEvaluation(pos)[0]/fitRange*255),(int)(problem.doEvaluation(pos)[0]/fitRange*255)); rect.setColor(color); rect.setFillColor(color); m_PlotArea.addDElement(rect); diff --git a/src/javaeva/server/go/InterfaceGOParameters.java b/src/javaeva/server/go/InterfaceGOParameters.java index 93cd9d46..58833525 100644 --- a/src/javaeva/server/go/InterfaceGOParameters.java +++ b/src/javaeva/server/go/InterfaceGOParameters.java @@ -1,5 +1,7 @@ package javaeva.server.go; +import javaeva.gui.GenericObjectEditor; +import javaeva.server.go.operators.postprocess.InterfacePostProcessParams; import javaeva.server.go.problems.InterfaceOptimizationProblem; import javaeva.server.go.strategies.InterfaceOptimizer; @@ -62,4 +64,20 @@ public interface InterfaceGOParameters { // public void setOutputFileName (String name); // public String getOutputFileName (); // public String outputFileNameTipText(); + + public InterfacePostProcessParams getPostProcessParams(); + public void setPostProcessParams(InterfacePostProcessParams ppp); + public String postProcessParamsTipText(); + public void setDoPostProcessing(boolean doPP); +// public int getPostProcessSteps(); +// public void setPostProcessSteps(int ppSteps); +// public String postProcessStepsTipText(); +// +// public boolean isPostProcess(); +// public void setPostProcess(boolean postProcess); +// public String postProcessTipText(); +// +// public double getPostProcessClusterSigma(); +// public void setPostProcessClusterSigma(double postProcessClusterSigma); +// public String postProcessClusterSigmaTipText(); } diff --git a/src/javaeva/server/go/InterfacePopulationChangedEventListener.java b/src/javaeva/server/go/InterfacePopulationChangedEventListener.java index 4714a63f..4e021463 100644 --- a/src/javaeva/server/go/InterfacePopulationChangedEventListener.java +++ b/src/javaeva/server/go/InterfacePopulationChangedEventListener.java @@ -1,6 +1,5 @@ package javaeva.server.go; -import javaeva.server.go.populations.Population; /** * Created by IntelliJ IDEA. diff --git a/src/javaeva/server/go/individuals/AbstractEAIndividual.java b/src/javaeva/server/go/individuals/AbstractEAIndividual.java index 8ad3f7f0..88de753f 100644 --- a/src/javaeva/server/go/individuals/AbstractEAIndividual.java +++ b/src/javaeva/server/go/individuals/AbstractEAIndividual.java @@ -645,7 +645,7 @@ public abstract class AbstractEAIndividual implements IndividualInterface, java. public static String getDefaultStringRepresentation(AbstractEAIndividual individual) { StringBuffer sb = new StringBuffer(getDefaultDataString(individual)); - sb.append("Fitness :"); + sb.append(", fitness: "); sb.append(BeanInspector.toString(individual.getFitness())); return sb.toString(); } @@ -661,49 +661,41 @@ public abstract class AbstractEAIndividual implements IndividualInterface, java. StringBuffer sb = new StringBuffer(""); char left = '['; char right = ']'; + sb.append(left); if (individual instanceof InterfaceDataTypeBinary) { - sb.append(left); BitSet b = ((InterfaceDataTypeBinary)individual).getBinaryData(); for (int i = 0; i < ((InterfaceDataTypeBinary)individual).size(); i++) { if (b.get(i)) sb.append("1"); else sb.append("0"); } - sb.append(right); } else if (individual instanceof InterfaceDataTypeInteger) { - sb.append(left); int[] b = ((InterfaceDataTypeInteger)individual).getIntegerData(); for (int i = 0; i < b.length; i++) { sb.append(b[i]); if ((i+1) < b.length) sb.append("; "); } - sb.append(right); } else if (individual instanceof InterfaceDataTypeDouble) { - sb.append(left); double[] b = ((InterfaceDataTypeDouble)individual).getDoubleData(); for (int i = 0; i < b.length; i++) { sb.append(b[i]); if ((i+1) < b.length) sb.append("; "); } - sb.append(right); } else if (individual instanceof InterfaceDataTypePermutation) { - sb.append(left); int[] b = ((InterfaceDataTypePermutation)individual).getPermutationData()[0]; for (int i = 0; i < b.length; i++) { sb.append(b[i]); if ((i+1) < b.length) sb.append("; "); } - sb.append(right); } else if (individual instanceof InterfaceDataTypeProgram) { - sb.append(left); InterfaceProgram[] b = ((InterfaceDataTypeProgram)individual).getProgramData(); for (int i = 0; i < b.length; i++) { sb.append(b[i].getStringRepresentation()); if ((i+1) < b.length) sb.append("; "); } - sb.append(right); } else { System.err.println("error in AbstractEAIndividual::getDefaultDataString: type " + individual.getClass() + " not implemented"); } + sb.append(right); return sb.toString(); } diff --git a/src/javaeva/server/go/operators/cluster/ClusteringDensityBased.java b/src/javaeva/server/go/operators/cluster/ClusteringDensityBased.java index ec558a8f..b5fad117 100644 --- a/src/javaeva/server/go/operators/cluster/ClusteringDensityBased.java +++ b/src/javaeva/server/go/operators/cluster/ClusteringDensityBased.java @@ -1,13 +1,12 @@ package javaeva.server.go.operators.cluster; -import javaeva.server.go.individuals.AbstractEAIndividual; -import javaeva.server.go.individuals.InterfaceDataTypeDouble; -import javaeva.server.go.operators.distancemetric.InterfaceDistanceMetric; -import javaeva.server.go.operators.distancemetric.PhenotypeMetricDoubleData; -import javaeva.server.go.populations.Population; - import java.util.ArrayList; +import javaeva.server.go.individuals.AbstractEAIndividual; +import javaeva.server.go.operators.distancemetric.InterfaceDistanceMetric; +import javaeva.server.go.operators.distancemetric.PhenotypeMetric; +import javaeva.server.go.populations.Population; + /** The DBSCAN method. As far as I recall this is an hierachical * clustering method like the single-link method. * Created by IntelliJ IDEA. @@ -18,7 +17,7 @@ import java.util.ArrayList; */ public class ClusteringDensityBased implements InterfaceClustering, java.io.Serializable { - private InterfaceDistanceMetric m_Metric = new PhenotypeMetricDoubleData(); + private InterfaceDistanceMetric m_Metric = new PhenotypeMetric(); private double m_ClusterDistance = 0.1; private int m_MinimumGroupSize = 3; private boolean[][] ConnectionMatrix; @@ -26,9 +25,16 @@ public class ClusteringDensityBased implements InterfaceClustering, java.io.Seri private boolean m_TestConvergingSpeciesOnBestOnly = true; public ClusteringDensityBased() { - } - + + /** + * Directly set the minimum cluster distance sigma. + * @param sigma the minimum cluster distance + */ + public ClusteringDensityBased(double sigma) { + m_ClusterDistance = sigma; + } + public ClusteringDensityBased(ClusteringDensityBased a) { if (a.m_Metric != null) this.m_Metric = (InterfaceDistanceMetric)a.m_Metric.clone(); this.m_TestConvergingSpeciesOnBestOnly = a.m_TestConvergingSpeciesOnBestOnly; @@ -62,7 +68,7 @@ public class ClusteringDensityBased implements InterfaceClustering, java.io.Seri /** This method allows you to search for clusters in a given population. The method * returns Number of populations. The first population contains all individuals that - * could not be asociated with any cluster and may be empty. + * could not be associated with any cluster and may be empty. * All other populations group individuals into clusters. * @param pop The population of individuals that is to be clustered. * @return Population[] @@ -83,7 +89,7 @@ public class ClusteringDensityBased implements InterfaceClustering, java.io.Seri for (int i = 0; i < pop.size(); i++) { tmpIndy1 = (AbstractEAIndividual)pop.get(i); ConnectionMatrix[i][i] = true; - for (int j = i; j < pop.size(); j++) { + for (int j = i+1; j < pop.size(); j++) { tmpIndy2 = (AbstractEAIndividual)pop.get(j); if (this.m_Metric.distance(tmpIndy1, tmpIndy2) < this.m_ClusterDistance) { ConnectionMatrix[i][j] = true; diff --git a/src/javaeva/server/go/operators/cluster/ClusteringKMeans.java b/src/javaeva/server/go/operators/cluster/ClusteringKMeans.java index f16a886a..f961add5 100644 --- a/src/javaeva/server/go/operators/cluster/ClusteringKMeans.java +++ b/src/javaeva/server/go/operators/cluster/ClusteringKMeans.java @@ -1,20 +1,15 @@ package javaeva.server.go.operators.cluster; +import javaeva.gui.Chart2DDPointIconCircle; +import javaeva.gui.Chart2DDPointIconText; +import javaeva.gui.GraphPointSet; +import javaeva.gui.Plot; import javaeva.server.go.individuals.AbstractEAIndividual; import javaeva.server.go.individuals.ESIndividualDoubleData; import javaeva.server.go.individuals.InterfaceDataTypeDouble; -import javaeva.server.go.operators.distancemetric.InterfaceDistanceMetric; -import javaeva.server.go.operators.distancemetric.PhenotypeMetricDoubleData; import javaeva.server.go.populations.Population; import javaeva.server.go.problems.F1Problem; import javaeva.server.go.tools.RandomNumberGenerator; -import javaeva.gui.Plot; -import javaeva.gui.GraphPointSet; -import javaeva.gui.Chart2DDPointIconText; -import javaeva.gui.Chart2DDPointIconCircle; - -import java.util.ArrayList; - import wsi.ra.chart2d.DPoint; /** The k-mean clustering algorithms. I guess it is not a hierachical @@ -217,7 +212,10 @@ public class ClusteringKMeans implements InterfaceClustering, java.io.Serializab double[][] data = this.extractClusterDataFrom(pop); int clusterAssigned; - for (int i = 0; i < result.length; i++) result[i] = new Population(); + for (int i = 0; i < result.length; i++) { + result[i] = new Population(); + result[i].setSameParams(pop); + } // let's assign the elements of the population to a c for (int i = 0; i < data.length; i++) { // find the closest c diff --git a/src/javaeva/server/go/operators/cluster/InterfaceClustering.java b/src/javaeva/server/go/operators/cluster/InterfaceClustering.java index cfe158a0..048e6072 100644 --- a/src/javaeva/server/go/operators/cluster/InterfaceClustering.java +++ b/src/javaeva/server/go/operators/cluster/InterfaceClustering.java @@ -3,11 +3,9 @@ package javaeva.server.go.operators.cluster; import javaeva.server.go.individuals.AbstractEAIndividual; import javaeva.server.go.populations.Population; -import java.util.ArrayList; -//import javaeva.server.oa.go.GraphicUserInterface.Plot.TopoPlot; - -/** This the interface to clustering algorithms, but since there - * is no true concept on how to calculate a possbily problem +/** + * This the interface to clustering algorithms, but since there + * is no true concept on how to calculate a possibly problem * specific distance between two individuals, this is still to * be considered as under construction. * Created by IntelliJ IDEA. @@ -26,14 +24,14 @@ public interface InterfaceClustering { /** This method allows you to search for clusters in a given population. The method * returns Number of populations. The first population contains all individuals that - * could not be asociated with any cluster and may be empty. + * could not be associated with any cluster and may be empty. * All other populations group individuals into clusters. * @param pop The population of individuals that is to be clustered. * @return Population[] */ public Population[] cluster(Population pop); - /** This method allows you to decied if two species converge. + /** This method allows you to decide if two species converge. * @param species1 The first species. * @param species2 The second species. * @return True if species converge, else False. @@ -46,9 +44,4 @@ public interface InterfaceClustering { * @return True or False. */ public boolean belongsToSpecies(AbstractEAIndividual indy, Population species); - -// /** For debuggy only -// * @param plot TopoPlot -// */ -// public void draw(TopoPlot plot, Population pop); } diff --git a/src/javaeva/server/go/operators/distancemetric/PhenotypeMetricDoubleData.java b/src/javaeva/server/go/operators/distancemetric/PhenotypeMetricDoubleData.java deleted file mode 100644 index 0831281f..00000000 --- a/src/javaeva/server/go/operators/distancemetric/PhenotypeMetricDoubleData.java +++ /dev/null @@ -1,66 +0,0 @@ -package javaeva.server.go.operators.distancemetric; - -import javaeva.server.go.individuals.AbstractEAIndividual; -import javaeva.server.go.individuals.InterfaceDataTypeDouble; - -/** A Phenotype distance for double data, i guess - * this is guess for the clustering based niching. - * Created by IntelliJ IDEA. - * User: streiche - * Date: 24.04.2003 - * Time: 13:27:39 - * To change this template use Options | File Templates. - */ -public class PhenotypeMetricDoubleData implements InterfaceDistanceMetric, java.io.Serializable { - - public PhenotypeMetricDoubleData() { - } - - public PhenotypeMetricDoubleData(PhenotypeMetricDoubleData a) { - } - - public Object clone() { - return (Object) new PhenotypeMetricDoubleData(this); - } - - /** This method allows you to compute the distance between two individuals. - * Depending on the metric this method may reject some types of individuals. - * The default return value would be 1.0. - * @param indy1 The first individual. - * @param indy2 The second individual. - * @return double - */ - public double distance(AbstractEAIndividual indy1, AbstractEAIndividual indy2) { - double[] dIndy1, dIndy2; - double[][] range1, range2; - double result = 0; - - if ((indy1 instanceof InterfaceDataTypeDouble) && (indy2 instanceof InterfaceDataTypeDouble)) { - dIndy1 = ((InterfaceDataTypeDouble) indy1).getDoubleData(); - range1 = ((InterfaceDataTypeDouble) indy1).getDoubleRange(); - dIndy2 = ((InterfaceDataTypeDouble) indy2).getDoubleData(); - range2 = ((InterfaceDataTypeDouble) indy2).getDoubleRange(); - } else return 1.0; - - for (int i = 0; (i < dIndy1.length) && (i < dIndy2.length); i++) { - result += Math.pow(((dIndy1[i] - range1[i][0])/(range1[i][1] - range1[i][0])) - ((dIndy2[i] - range2[i][0])/(range2[i][1] - range2[i][0])), 2); - } - return Math.sqrt(result); - } -/********************************************************************************************************************** - * These are for GUI - */ - /** This method returns a global info string - * @return description - */ - public String globalInfo() { - return "This is a phenotype based method suited for double data. Metric is computed on a normalized search space."; - } - /** This method will return a naming String - * @return The name of the algorithm - */ - public String getName() { - return "Phenotype Metric"; - } -} - diff --git a/src/javaeva/server/go/operators/fitnessmodifier/FitnessSharing.java b/src/javaeva/server/go/operators/fitnessmodifier/FitnessSharing.java index 5e6fe276..753fe1c7 100644 --- a/src/javaeva/server/go/operators/fitnessmodifier/FitnessSharing.java +++ b/src/javaeva/server/go/operators/fitnessmodifier/FitnessSharing.java @@ -2,7 +2,7 @@ package javaeva.server.go.operators.fitnessmodifier; import javaeva.server.go.individuals.AbstractEAIndividual; import javaeva.server.go.operators.distancemetric.InterfaceDistanceMetric; -import javaeva.server.go.operators.distancemetric.PhenotypeMetricDoubleData; +import javaeva.server.go.operators.distancemetric.PhenotypeMetric; import javaeva.server.go.populations.Population; /** The fitness modifier are defunct and are to be moved to @@ -16,7 +16,7 @@ import javaeva.server.go.populations.Population; public class FitnessSharing implements java.io.Serializable, InterfaceFitnessModifier { private double m_SharingDistance = 0.05; - private InterfaceDistanceMetric m_Metric = new PhenotypeMetricDoubleData(); + private InterfaceDistanceMetric m_Metric = new PhenotypeMetric(); /** This method allows you to modify the fitness of the individuals * of a population. Note that by altering the fitness you may require diff --git a/src/javaeva/server/go/operators/postprocess/InterfacePostProcessParams.java b/src/javaeva/server/go/operators/postprocess/InterfacePostProcessParams.java new file mode 100644 index 00000000..d5598845 --- /dev/null +++ b/src/javaeva/server/go/operators/postprocess/InterfacePostProcessParams.java @@ -0,0 +1,28 @@ +package javaeva.server.go.operators.postprocess; + +/** + * Parameters for an optional post processing of found solutions. Mainly contains + * parameters for a hill climbing step, namely the number of evaluations and + * the sigma condition for clustering. The idea is to optimize the best + * individual within each cluster. + * + * @author mkron + * + */ +public interface InterfacePostProcessParams { + public int getPostProcessSteps(); + public void setPostProcessSteps(int ppSteps); + public String postProcessStepsTipText(); + + public boolean isDoPostProcessing(); + public void setDoPostProcessing(boolean postProcess); + public String doPostProcessingTipText(); + + public double getPostProcessClusterSigma(); + public void setPostProcessClusterSigma(double postProcessClusterSigma); + public String postProcessClusterSigmaTipText(); + + public int getPrintNBest(); + public void setPrintNBest(int nBest); + public String printNBestTipText(); +} diff --git a/src/javaeva/server/go/operators/postprocess/PostProcess.java b/src/javaeva/server/go/operators/postprocess/PostProcess.java new file mode 100644 index 00000000..029dca5e --- /dev/null +++ b/src/javaeva/server/go/operators/postprocess/PostProcess.java @@ -0,0 +1,515 @@ +package javaeva.server.go.operators.postprocess; + +import java.io.PrintStream; +import java.util.Collection; +import java.util.List; + +import javaeva.OptimizerFactory; +import javaeva.OptimizerRunnable; +import javaeva.gui.BeanInspector; +import javaeva.server.go.InterfaceTerminator; +import javaeva.server.go.individuals.AbstractEAIndividual; +import javaeva.server.go.operators.cluster.ClusteringDensityBased; +import javaeva.server.go.operators.cluster.InterfaceClustering; +import javaeva.server.go.operators.distancemetric.InterfaceDistanceMetric; +import javaeva.server.go.operators.distancemetric.PhenotypeMetric; +import javaeva.server.go.operators.mutation.InterfaceMutation; +import javaeva.server.go.operators.mutation.MutateESFixedStepSize; +import javaeva.server.go.operators.terminators.EvaluationTerminator; +import javaeva.server.go.populations.Population; +import javaeva.server.go.problems.AbstractOptimizationProblem; +import javaeva.server.go.problems.FM0Problem; +import javaeva.server.go.problems.InterfaceMultimodalProblem; +import javaeva.server.go.problems.InterfaceMultimodalProblemKnown; +import javaeva.server.go.strategies.HillClimbing; +import javaeva.server.stat.InterfaceTextListener; +import javaeva.tools.Pair; + +/** + * Postprocess a population / list of individuals to find out a set of distinct optima. + * + * @author mkron + * + */ +public class PostProcess { + protected static InterfaceDistanceMetric metric = new PhenotypeMetric(); + private static final boolean TRACE = false; + // the default mutation step size for HC post processing + private static double defaultMutationStepSize = 0.01; + + public static final int BEST_ONLY = 1; + public static final int BEST_RAND = 2; + public static final int RAND_ONLY = 3; + + public static final int KEEP_LONERS = 11; + public static final int DISCARD_LONERS = 12; + public static final int LONERS_AS_CLUSTERS = 13; + /** + * This method returns a set of individuals corresponding to an optimum in a given list. + * The individuals returned are to be nearer than epsilon to a given optimum. For each optimum, there is + * returned zero or one individual at max. + * If there are several individuals close to an optimum, the fitter one or the closer one + * may be selected, indicated by the boolean flag bTakeFitter. This means, that an individual may be + * returned in more than one copy if the optima are close together and the individual lies in between. + * The returned array may contain null values if an optimum is not considered found at all. + * + * @param pop A population of possible solutions. + * @param optima a set of predefined optima + * @param epsilon the threshold up to which an optimum is considered found. + * @param bTakeFitter if true, the fitter of two close individuals is selected, otherwise the closer one + * @return an array of individuals corresponding to the optimum with the same index + */ + public static AbstractEAIndividual[] getFoundOptimaArray(Population pop, Population optima, double epsilon, boolean bTakeFitter) { + AbstractEAIndividual candidate, opt; +// Population result = new Population(5); + AbstractEAIndividual[] found = new AbstractEAIndividual[optima.size()]; + double indDist; + for (int i = 0; i < found.length; i++) found[i] = null; + + for (int i = 0; i < pop.size(); i++) { + candidate = (AbstractEAIndividual) pop.get(i); + for (int j = 0; j < optima.size(); j++) { + opt = (AbstractEAIndividual) optima.get(j); + indDist = metric.distance(candidate, opt); + if (found[j] == null) { // current optimum has not been found yet + if (indDist < epsilon) { + found[j] = (AbstractEAIndividual)candidate.clone(); +// result.add(found[j]); + } + } else {// there was another one found. set the fitter one or the closer one + if (indDist < epsilon) { + if ((bTakeFitter && (candidate.isDominatingDebConstraints(found[j]))) // flag "fitter" and new one is fitter + || (!bTakeFitter && (indDist < metric.distance(found[j], opt)))) { // flag "closer" and new one is closer +// int index = result.indexOf(found[j]); // do replacement + found[j] = (AbstractEAIndividual)candidate.clone(); +// result.set(index, found[j]); + } + } + } + } + } + return found; + } + + /** + * Convenience method for getFoundOptimaArray(), returning the same set of optima in a Population. + * + * @see getFoundOptimaArray(Population pop, Population optima, double epsilon, boolean bTakeFitter) + * @param pop A population of possible solutions. + * @param optima a set of known optima + * @param epsilon the threshold up to which an optimum is considered found. + * @param bTakeFitter if true, the fitter of two close individuals is selected, otherwise the closer one + * @return a Population of individuals corresponding to the given optima + */ + public static Population getFoundOptima(Population pop, Population optima, double epsilon, boolean bTakeFitter) { + Population result = new Population(5); + AbstractEAIndividual[] optsFound = getFoundOptimaArray(pop, optima, epsilon, bTakeFitter); + + for (int i=0; i 0, at least one is kept. + * lonerMode defines whether loners are discarded, kept, or treated as clusters, meaning they are kept if returnQuota > 0. + * takOverMode defines whether, of a cluster with size > 1, which n individuals are kept. Either the n best only, + * or the single best and random n-1, or all n random. + * + * @param pop + * @param clustering + * @param returnQuota + * @param lonerMode + * @param takeOverMode + * @return for every cluster a population of representatives which are the best individuals or a random subset of the cluster + */ + public static Population clusterBest(Population pop, InterfaceClustering clustering, double returnQuota, int lonerMode, int takeOverMode) { + //cluster the undifferentiated population + Population result = new Population(10); + result.setSameParams(pop); + Population[] clusters = clustering.cluster(pop); + if (TRACE) { + System.out.println("found " + clusters.length + " clusters!"); + int sum=0; + for (int j=0; j= 1) result.addAll((Collection)clusters[j]); // easy case + else { + int n = Math.max(1, (int)(returnQuota*clusters[j].size())); // return at least one per cluster! + switch (takeOverMode) { + case BEST_ONLY: // another easy case + result.addAll((Collection)(clusters[j].getBestNIndividuals(n))); + break; + case BEST_RAND: + Population exclude = new Population(); + exclude.add(clusters[j].getBestEAIndividual()); + result.add(exclude.getEAIndividual(0)); + result.addAll(clusters[j].getRandNIndividualsExcept(n-1, exclude)); + break; + case RAND_ONLY: + result.addAll(clusters[j].getRandNIndividuals(n)); + break; + default: System.err.println("Unknown mode in PostProcess:clusterBest!"); break; + } + } + } + result.setPopulationSize(result.size()); + return result; + } + + public static double[] populationMeasures(Population pop) { + double[] measures = pop.getPopulationMeasures(); + return measures; + } + + /** + * Filter the individuals of a population which have a fitness norm within given bounds. + * Returns shallow copies! + * + * @param pop + * @param lower + * @param upper + * @return + */ + public static Population filterFitnessIn(Population pop, double lower, double upper) { + Population result = filterFitness(pop, upper, true); + return filterFitness(result, lower, false); + } + + /** + * Filter the individuals of a population which have a fitness norm below a given value. + * Returns shallow copies! + * + * @param pop + * @param fitNorm + * @param bSmaller if true, return individuals with lower or equal, else with higher fitness norm only + * @return + */ + public static Population filterFitness(Population pop, double fitNorm, boolean bSmallerEq) { + AbstractEAIndividual indy; + Population result = new Population(); + for (int i=0; ifitNorm)) result.add(indy); + } + return result; + } + + /** + * Create a fitness histogram of an evaluated population within the given interval and nBins number of bins. + * Therefore a bin is of size (upperBound-lowerBound)/nBins, and bin 0 starts at lowerBound. + * Returns an integer array with the number of individuals in each bin. + * + * @param pop the population to scan. + * @param lowerBound lower bound of the fitness interval + * @param upperBound upper bound of the fitness interval + * @param nBins number of bins + * @return an integer array with the number of individuals in each bin + * @see filterFitnessIn() + */ + public static int[] createFitNormHistogram(Population pop, double lowerBound, double upperBound, int nBins) { + int[] res = new int[nBins]; + double lower = lowerBound; + double step = (upperBound - lowerBound) / nBins; + for (int i=0; i getClosestFoundOptima(Population pop, Population optima, double epsilon) { +// AbstractEAIndividual indy; +// ArrayList result = new ArrayList(5); +// AbstractEAIndividual[] foundIndy = new AbstractEAIndividual[optima.size()]; +// +// for (int i = 0; i < pop.size(); i++) { +// indy = (AbstractEAIndividual) pop.get(i); +// IndexFitnessPair bestHit = getClosestIndy(indy, optima); +// if (foundIndy[bestHit.index] == null) { // there has no indy been assigned yet +// // assign the current indy if no epsilon is required, or epsilon-threshold is fulfilled +// if (epsilon < 0 || (bestHit.dist < epsilon)) foundIndy[bestHit.index] = indy; +// } else { +// // assign current indy only if it is better than the earlier assigned one +// // in that case, epsilon is fulfilled automatically +// double oldDist = metric.distance(foundIndy[bestHit.index], (AbstractEAIndividual)optima.get(bestHit.index)); +// if (bestHit.dist < oldDist) foundIndy[bestHit.index] = indy; +// } +// } +// return result; +// } + + /** + * Search a population and find the closest individual to a given individual. Return the + * best distance and corresponding index in a pair structure. + * + * @param indy + * @param pop + * @return index and distance to the closest individual in the population + */ + public static Pair getClosestIndy(AbstractEAIndividual indy, Population pop) { + double bestDist = -1, tmpDist = -1; + int bestIndex = -1; + AbstractEAIndividual opt; + for (int j = 0; j < pop.size(); j++) { + opt = (AbstractEAIndividual) pop.get(j); + tmpDist = metric.distance(indy, opt); // distance current indy to current optimum + if (bestDist < 0 || (tmpDist < bestDist)) { // we have a better hit + bestIndex = j; + bestDist = tmpDist; + } + } + return new Pair(bestDist, bestIndex); + } + + /** + * Optimize a population with a default hill-climbing heuristic for a number of fitness evaluations. + * As mutation operator, a fixed step size ES mutation is used. + * + * @param pop + * @param problem + * @param maxSteps + * @param fixedStepSize + */ + public static void processWithHC(Population pop, AbstractOptimizationProblem problem, int maxSteps, double fixedStepSize) { +// pop.SetFunctionCalls(0); // or else optimization wont restart on an "old" population +// pop.setGenerationTo(0); + processWithHC(pop, problem, new EvaluationTerminator(pop.getFunctionCalls()+maxSteps), new MutateESFixedStepSize(fixedStepSize)); + } + + public static void processWithHC(Population pop, AbstractOptimizationProblem problem, int maxSteps) { + processWithHC(pop, problem, maxSteps, defaultMutationStepSize); + } + /** + * Optimize a population with a default hill-climbing heuristic with a given termination criterion and mutation operator. + * + * @param pop + * @param problem + * @param term + * @param mute + */ + public static void processWithHC(Population pop, AbstractOptimizationProblem problem, InterfaceTerminator term, InterfaceMutation mute) { + HillClimbing hc = new HillClimbing(); + // HC depends heavily on the selected mutation operator! + hc.SetProblem(problem); + hc.SetMutationOperator(mute); + if (pop.size() != pop.getPopulationSize()) { + System.err.println(pop.size() + " vs. "+ pop.getPopulationSize()); + System.err.println("warning: population size and vector size dont match! (PostProcess::processWithHC)"); + } + hc.setPopulation(pop); +// hc.initByPopulation(pop, false); + OptimizerRunnable runnable = new OptimizerRunnable(OptimizerFactory.makeParams(hc, pop, problem, 0, term), null, true); + runnable.getGOParams().setDoPostProcessing(false); + runnable.run(); + + } + + public static void main(String[] args) { + AbstractOptimizationProblem problem = new FM0Problem(); + InterfaceMultimodalProblemKnown mmp = (InterfaceMultimodalProblemKnown)problem; + OptimizerRunnable runnable = OptimizerFactory.getOptRunnable(OptimizerFactory.STD_GA, problem, 500, null); + runnable.run(); + Population pop = runnable.getGOParams().getOptimizer().getPopulation(); +// System.out.println("no optima found: " + mmp.getNumberOfFoundOptima(pop)); + Population found = getFoundOptima(pop, mmp.getRealOptima(), 0.05, true); + System.out.println("all found (" + found.size() + "): " + BeanInspector.toString(found)); + + Pair popD = new Pair(pop, 1.); + int i=0; + int evalCnt = 0; + while (popD.tail() > 0.01) { + i++; +// public static PopDoublePair clusterHC(pop, problem, sigmaCluster, funCalls, keepClusterRatio, mute) { + + popD = clusterHC(popD.head(), problem, 0.01, 1000 - (evalCnt % 1000), 0.5, new MutateESFixedStepSize(0.02)); + evalCnt += popD.head().getFunctionCalls(); + } + found = getFoundOptima(popD.head(), mmp.getRealOptima(), 0.05, true); + System.out.println("found at " + i + " (" + found.size() + "): " + BeanInspector.toString(found)); + System.out.println("funcalls: " + evalCnt); +// System.out.println(BeanInspector.toString(pop.getMeanFitness())); + +// System.out.println("no optima found: " + mmp.getNumberOfFoundOptima(pop)); +// System.out.println("best after: " + AbstractEAIndividual.getDefaultStringRepresentation(pop.getBestEAIndividual())); + + } + + /** + * Cluster a population and reduce it by a certain ratio, then optimize the remaining individuals for a given number of function calls with a HC. + * Return a pair of the optimized population and the improvement in the mean fitness (not normed) that was achieved by the HC run. The returned + * individuals are deep clones, so the given population is not altered. Of a cluster of individuals, the given + * ratio of individuals is kept, more precisely, the best one is kept while the remaining are selected randomly. All loners are kept. + * + * @param pop the population to work on + * @param problem the target problem instance + * @param sigmaCluster minimum clustering distance + * @param funCalls number of function calls for the optimization step + * @param keepClusterRatio of a cluster of individuals, this ratio of individuals is kept for optimization + * @param mute the mutation operator to be used by the hill climber + * @return a pair of the optimized population and the improvement in the mean fitness (not normed) achieved by the HC run + */ + public static Pair clusterHC(Population pop, AbstractOptimizationProblem problem, double sigmaCluster, int funCalls, double keepClusterRatio, InterfaceMutation mute) { + Population clust = (Population)clusterBest(pop, new ClusteringDensityBased(sigmaCluster), keepClusterRatio, KEEP_LONERS, BEST_RAND).clone(); +// System.out.println("keeping " + clust.size() + " for hc...."); + double[] meanFit = clust.getMeanFitness(); + processWithHC(clust, problem, new EvaluationTerminator(pop.getFunctionCalls()+funCalls), mute); + double improvement = PhenotypeMetric.euclidianDistance(meanFit, clust.getMeanFitness()); + System.out.println("improvement by " + improvement); + return new Pair(clust, improvement); + } + +// /** +// * Do some post processing on a multimodal problem. If the real optima are known, only the number of +// * found optima is printed. Otherwise, the population is clustered and for the population of cluster-representatives, +// * some diversity measures and a fitness histogram are printed. +// * +// * @see Population.getPopulationMeasures() +// * @see createFitNormHistogram +// * @param mmProb the target problem +// * @param pop the solution set +// * @param sigmaCluster the min clustering distance +// * @param out a PrintStream for data output +// * @param minBnd lower fitness bound +// * @param maxBnd upper fitness bound +// * @param bins number of bins for the fitness histogram +// * @return +// */ +// public static Population outputResult(AbstractOptimizationProblem mmProb, Population pop, double sigmaCluster, PrintStream out, double minBnd, double maxBnd, int bins, int hcSteps) { +// ClusteringDensityBased clust = new ClusteringDensityBased(sigmaCluster); +// clust.setMinimumGroupSize(2); +// Population clusteredBest = clusterBest(pop, clust, 0, KEEP_LONERS, BEST_ONLY); +// if (hcSteps > 0) { // HC post process +// Population tmpPop = (Population)clusteredBest.clone(); +// processWithHC(tmpPop, (AbstractOptimizationProblem)mmProb, hcSteps, 0.001); +// clusteredBest = clusterBest(tmpPop, clust, 0, KEEP_LONERS, BEST_ONLY); +// } +// double[] meas = clusteredBest.getPopulationMeasures(); +// int[] sols = createFitNormHistogram(clusteredBest, minBnd, maxBnd, bins); +// out.println("measures: " + BeanInspector.toString(meas)); +// out.println("solution hist.: " + BeanInspector.toString(sols)); +// +// Object[] bestArr = clusteredBest.toArray(); +// for (Object locOpt : bestArr) { +//// out.print((AbstractEAIndividual.getDefaultDataString((IndividualInterface)locOpt))); +// out.println(AbstractEAIndividual.getDefaultStringRepresentation(((AbstractEAIndividual)locOpt))); +// } +// return clusteredBest; +// } + +// public static Population outputResultKnown(InterfaceMultimodalProblemKnown mmProb, Population pop, double sigmaCluster, PrintStream out, double minBnd, double maxBnd, int bins) { +// Population found = getFoundOptima(pop, ((InterfaceMultimodalProblemKnown)mmProb).getRealOptima(), ((InterfaceMultimodalProblemKnown)mmProb).getEpsilon(), true); +// for (double epsilon=0.1; epsilon > 0.00000001; epsilon/=10.) { +// //out.println("no optima found: " + ((InterfaceMultimodalProblemKnown)mmProb).getNumberOfFoundOptima(pop)); +// out.println("found " + getFoundOptima(pop, ((InterfaceMultimodalProblemKnown)mmProb).getRealOptima(), epsilon, true).size() + " for epsilon = " + epsilon); +// } +// out.println("max peak ratio is " + mmProb.getMaximumPeakRatio(found)); +// return found; +// } + + /** + * Do some data output for multimodal problems with known optima. + */ + public static void procMultiModalKnown(Population solutions, InterfaceMultimodalProblemKnown mmkProb, InterfaceTextListener listener) { +// Population found = getFoundOptima(solutions, mmkProb.getRealOptima(), mmkProb.getEpsilon(), true); + listener.println("default epsilon is " + mmkProb.getEpsilon()); + listener.println("max peak ratio is " + mmkProb.getMaximumPeakRatio(getFoundOptima(solutions, mmkProb.getRealOptima(), mmkProb.getEpsilon(), true))); + for (double epsilon=0.1; epsilon > 0.00000001; epsilon/=10.) { + // out.println("no optima found: " + ((InterfaceMultimodalProblemKnown)mmProb).getNumberOfFoundOptima(pop)); + listener.println("found " + getFoundOptima(solutions, mmkProb.getRealOptima(), epsilon, true).size() + " for epsilon = " + epsilon); + } + } + + /** + * Universal post processing method, receiving parameter instance for specification. + * Optional clustering and HC step, output contains population measures, fitness histogram and + * a list of solutions after post processing. + * + * @param params + * @param solutions + * @param problem + * @param listener + */ + public static void postProcess(InterfacePostProcessParams params, Population solutions, AbstractOptimizationProblem problem, InterfaceTextListener listener) { + if (params.isDoPostProcessing()) { + Population outputPop; + if (params.getPostProcessClusterSigma() > 0) { + outputPop = (Population)PostProcess.clusterBest(solutions, params.getPostProcessClusterSigma(), 0, PostProcess.KEEP_LONERS, PostProcess.BEST_ONLY).clone(); + if (outputPop.size() < solutions.size()) { + listener.println("Clustering reduced population size from " + solutions.size() + " to " + outputPop.size()); + } else listener.println("Clustering yielded no size reduction."); + } else outputPop = solutions; + if (params.getPostProcessSteps() > 0) { + processWithHC(outputPop, problem, params.getPostProcessSteps()); + listener.println("HC post processing done."); + } + double upBnd = PhenotypeMetric.norm(outputPop.getWorstEAIndividual().getFitness())*1.1; + upBnd = Math.pow(10,Math.floor(Math.log10(upBnd)+1)); + double lowBnd = 0; + int[] sols = PostProcess.createFitNormHistogram(outputPop, lowBnd, upBnd, 20); +// PostProcessInterim.outputResult((AbstractOptimizationProblem)goParams.getProblem(), outputPop, 0.01, System.out, 0, 2000, 20, goParams.getPostProcessSteps()); + listener.println("measures: " + BeanInspector.toString(outputPop.getPopulationMeasures())); + listener.println("solution histogram in [" + lowBnd + "," + upBnd + "]: " + BeanInspector.toString(sols)); + + //////////// multimodal data output? + if (problem instanceof InterfaceMultimodalProblemKnown) procMultiModalKnown(outputPop, (InterfaceMultimodalProblemKnown)problem, listener); + + //////////// output some individual data + List bestList = outputPop.getBestNIndividuals(params.getPrintNBest()); // n individuals are returned and sorted, all of them if n<=0 + listener.println("Best after post process:" + ((outputPop.size()>bestList.size()) ? ( "(first " + bestList.size() + " of " + outputPop.size() + ")") : "")); + for (AbstractEAIndividual indy : bestList) { + listener.println(AbstractEAIndividual.getDefaultStringRepresentation(indy)); + } + } + } +} + diff --git a/src/javaeva/server/go/operators/postprocess/PostProcessParams.java b/src/javaeva/server/go/operators/postprocess/PostProcessParams.java new file mode 100644 index 00000000..f0dbeabd --- /dev/null +++ b/src/javaeva/server/go/operators/postprocess/PostProcessParams.java @@ -0,0 +1,96 @@ +package javaeva.server.go.operators.postprocess; + +import java.io.Serializable; + +import javaeva.gui.GenericObjectEditor; + +public class PostProcessParams implements InterfacePostProcessParams, Serializable { + + protected int postProcessSteps = 5000; + private boolean postProcess = false; + protected double postProcessClusterSigma = 0.05; + protected int printNBest = 10; + + public PostProcessParams() { + postProcessSteps = 5000; + postProcess = false; + postProcessClusterSigma = 0.05; + printNBest = 10; + } + + public PostProcessParams(boolean doPP) { + postProcessSteps = 5000; + postProcess = doPP; + postProcessClusterSigma = 0.05; + } + + public PostProcessParams(int steps, double clusterSigma) { + postProcessSteps = steps; + postProcess = true; + postProcessClusterSigma = clusterSigma; + } + + public void hideHideable() { + setDoPostProcessing(isDoPostProcessing()); + } + + /** + * @return the postProcess + */ + public boolean isDoPostProcessing() { + return postProcess; + } + /** + * @param postProcess the postProcess to set + */ + public void setDoPostProcessing(boolean postProcess) { + this.postProcess = postProcess; + GenericObjectEditor.setShowProperty(this.getClass(), "postProcessSteps", postProcess); + GenericObjectEditor.setShowProperty(this.getClass(), "postProcessClusterSigma", postProcess); + GenericObjectEditor.setShowProperty(this.getClass(), "printNBest", postProcess); + } + public String doPostProcessingTipText() { + return "Toggle post processing of the solutions."; + } + /** + * @return the postProcessClusterSigma + */ + public double getPostProcessClusterSigma() { + return postProcessClusterSigma; + } + /** + * @param postProcessClusterSigma the postProcessClusterSigma to set + */ + public void setPostProcessClusterSigma(double postProcessClusterSigma) { + this.postProcessClusterSigma = postProcessClusterSigma; + } + public String postProcessClusterSigmaTipText() { + return "Set the sigma parameter for clustering during post processing. Set to zero for no clustering."; + } + + public String postProcessStepsTipText() { + return "The number of HC post processing steps in fitness evaluations."; + } + public int getPostProcessSteps() { + return postProcessSteps; + } + public void setPostProcessSteps(int ppSteps) { + postProcessSteps = ppSteps; + } + + public int getPrintNBest() { + return printNBest; + } + public void setPrintNBest(int nBest) { + printNBest = nBest; + } + public String printNBestTipText() { + return "Print as many solutions at max. Set to -1 to print all"; + } + //////////////////////// GUI + + public String getName() { + return "PostProcessing " + (postProcess ? (postProcessSteps + "/" + postProcessClusterSigma) : "off"); + } + +} diff --git a/src/javaeva/server/go/operators/selection/probability/SelProbFitnessSharing.java b/src/javaeva/server/go/operators/selection/probability/SelProbFitnessSharing.java index f2b894ba..16e180bd 100644 --- a/src/javaeva/server/go/operators/selection/probability/SelProbFitnessSharing.java +++ b/src/javaeva/server/go/operators/selection/probability/SelProbFitnessSharing.java @@ -2,7 +2,7 @@ package javaeva.server.go.operators.selection.probability; import javaeva.server.go.individuals.AbstractEAIndividual; import javaeva.server.go.operators.distancemetric.InterfaceDistanceMetric; -import javaeva.server.go.operators.distancemetric.PhenotypeMetricDoubleData; +import javaeva.server.go.operators.distancemetric.PhenotypeMetric; import javaeva.server.go.populations.Population; /** Here we have the infamous fitness sharing method. @@ -15,7 +15,7 @@ import javaeva.server.go.populations.Population; public class SelProbFitnessSharing extends AbstractSelProb implements java.io.Serializable { private InterfaceSelectionProbability m_BasicNormationMethod = new SelProbStandard(); - private InterfaceDistanceMetric m_DistanceMetric = new PhenotypeMetricDoubleData(); + private InterfaceDistanceMetric m_DistanceMetric = new PhenotypeMetric(); private double m_SharingDistance = 0.1; public SelProbFitnessSharing() { diff --git a/src/javaeva/server/go/operators/terminators/EvaluationTerminator.java b/src/javaeva/server/go/operators/terminators/EvaluationTerminator.java index c32349e1..fb164849 100644 --- a/src/javaeva/server/go/operators/terminators/EvaluationTerminator.java +++ b/src/javaeva/server/go/operators/terminators/EvaluationTerminator.java @@ -40,8 +40,10 @@ public class EvaluationTerminator implements InterfaceTerminator, public String globalInfo() { return "Terminates after the given number of fitness calls."; } + /** - * + * Construct Terminator with a maximum number of fitness calls. + * @param maximum number of fitness calls */ public EvaluationTerminator(int x) { m_FitnessCalls = x; diff --git a/src/javaeva/server/go/populations/Population.java b/src/javaeva/server/go/populations/Population.java index 2e750bbd..c82e73e9 100644 --- a/src/javaeva/server/go/populations/Population.java +++ b/src/javaeva/server/go/populations/Population.java @@ -1,17 +1,19 @@ package javaeva.server.go.populations; -import javaeva.server.go.IndividualInterface; -import javaeva.server.go.PopulationInterface; -import javaeva.server.go.individuals.AbstractEAIndividual; -import javaeva.server.go.individuals.GAIndividualBinaryData; -import javaeva.server.go.operators.distancemetric.PhenotypeMetric; -import javaeva.server.go.tools.RandomNumberGenerator; - - import java.util.ArrayList; import java.util.LinkedList; +import java.util.List; import java.util.PriorityQueue; +import javaeva.server.go.IndividualInterface; +import javaeva.server.go.InterfacePopulationChangedEventListener; +import javaeva.server.go.PopulationInterface; +import javaeva.server.go.individuals.AbstractEAIndividual; +import javaeva.server.go.individuals.AbstractEAIndividualComparator; +import javaeva.server.go.individuals.GAIndividualBinaryData; +import javaeva.server.go.operators.distancemetric.PhenotypeMetric; +import javaeva.server.go.tools.RandomNumberGenerator; + /** This is a basic implementation for a EA Population. * Copyright: Copyright (c) 2003 * Company: University of Tuebingen, Computer Architecture @@ -27,7 +29,11 @@ public class Population extends ArrayList implements PopulationInterface, Clonea protected int m_FunctionCalls = 0; protected int m_Size = 50; protected Population m_Archive = null; - + transient protected InterfacePopulationChangedEventListener m_Listener = null; + protected int notifyEvalInterval = 0; + + public static String funCallIntervalReached = "FunCallIntervalReached"; + boolean useHistory = false; public ArrayList m_History = new ArrayList(); @@ -39,9 +45,7 @@ public class Population extends ArrayList implements PopulationInterface, Clonea } public Population(Population population) { - this.m_Generation = population.m_Generation; - this.m_FunctionCalls = population.m_FunctionCalls; - this.m_Size = population.m_Size; + setSameParams(population); for (int i = 0; i < population.size(); i++) { if (population.get(i) != null) this.add((((AbstractEAIndividual)population.get(i))).clone()); @@ -49,6 +53,19 @@ public class Population extends ArrayList implements PopulationInterface, Clonea if (population.m_Archive != null) this.m_Archive = (Population)population.m_Archive.clone(); if (population.m_History != null) this.m_History = (ArrayList)population.m_History.clone(); } + + /** + * Takes over all scalar parameters of the given population. + * @param population + */ + public void setSameParams(Population population) { + this.m_Generation = population.m_Generation; + this.m_FunctionCalls = population.m_FunctionCalls; + this.m_Size = population.m_Size; + this.useHistory = population.useHistory; + this.notifyEvalInterval = population.notifyEvalInterval; + this.m_Listener = population.m_Listener; + } public Object clone() { return (Object) new Population(this); @@ -99,14 +116,41 @@ public class Population extends ArrayList implements PopulationInterface, Clonea */ public void incrFunctionCalls() { this.m_FunctionCalls++; + if (doEvalNotify()) { +// System.out.println("checking funcall event..."); + if ((m_FunctionCalls % notifyEvalInterval) == 0) firePropertyChangedEvent(funCallIntervalReached); + } } - /** This method will allow cou to increment the current number of function calls. + /** + * This method will allow you to increment the current number of function calls by a number > 1. + * Notice that it might slightly disturb notification if a notifyEvalInterval is set. + * * @param d The number of function calls to increment. */ public void incrFunctionCallsby(int d) { - this.m_FunctionCalls += d; + if (doEvalNotify()) { + System.out.println("checking funcall event..."); + int nextStep = ((m_FunctionCalls/notifyEvalInterval)+1) * notifyEvalInterval; // next interval boundary + if (nextStep <= (m_FunctionCalls+d)) { + // the notify interval will be stepped over or hit + int toHit = (nextStep - m_FunctionCalls); + this.m_FunctionCalls += toHit; // little cheat, notify may be after some more evals + firePropertyChangedEvent(funCallIntervalReached); + this.m_FunctionCalls += (d-toHit); + } + } else this.m_FunctionCalls += d; } - + + /** Something has changed + */ + protected void firePropertyChangedEvent(String name) { + if (this.m_Listener != null) this.m_Listener.registerPopulationStateChanged(this, name); + } + + private boolean doEvalNotify() { + return ((this.m_Listener != null) && (notifyEvalInterval > 0)); + } + /** This method return the current number of function calls performed. * @return The number of function calls performed. */ @@ -131,6 +175,7 @@ public class Population extends ArrayList implements PopulationInterface, Clonea if (useHistory && (this.size() >= 1)) this.m_History.add(this.getBestEAIndividual()); for (int i=0; i getBestNIndividuals(int n) { + LinkedList indList = new LinkedList(); + PriorityQueue queue = new PriorityQueue(super.size(), new AbstractEAIndividualComparator()); + + for (int i = 0; i < super.size(); i++) { + queue.add(getEAIndividual(i)); + } + if (n <= 0) n = queue.size(); + for (int i = 0; i getRandNIndividuals(int n) { + return getRandNIndividualsExcept(n, new Population()); + } + /** This method returns the n current best individuals from the population in an object array. * * @param n number of individuals to look out for * @return The n best individuals * */ - public Object[] getBestNIndividuals(int n) { - LinkedList indList = new LinkedList(); - PriorityQueue queue = new PriorityQueue(n); - AbstractEAIndividual indy; - double curNBestFitness = Double.POSITIVE_INFINITY; - - for (int i = 0; i < super.size(); i++) { - indy = (AbstractEAIndividual)super.get(i); - if ((!indy.violatesConstraint()) && (indy.getFitness(0) < curNBestFitness)) { - if (indList.size() >= n) { - indList.removeLast(); - queue.remove(); - } - indList.addFirst((AbstractEAIndividual)super.get(i)); - // use negative fitness, because queue orders the smallest to top. - queue.add(new Double(- indy.getFitness(0))); - if (indList.size() == n) curNBestFitness = - ((Double)queue.peek()).doubleValue(); - } - } - return indList.toArray(); + public Population getRandNIndividualsExcept(int n, Population exclude) { + return moveNInds(n, filter(exclude), new Population()); } + /** + * Moves n random individuals from src Population to dst Population and returns dst Population. + * + * @param n + * @param from + * @param to + * @return + */ + public static Population moveNInds(int n, Population src, Population dst) { + if ((n == 0) || (src.size() == 0)) return dst; + else { // Ingenious superior Scheme tail recursive style! + moveRandIndFromTo(src, dst); + return moveNInds(n-1, src, dst); + } + } + + /** + * Move one random individual from src to dst population. + * @param from + * @param to + */ + public static void moveRandIndFromTo(Population src, Population dst) { + int k = RandomNumberGenerator.randomInt(src.size()); + dst.add(src.remove(k)); + } + + /** + * Returns a subset of this population which does not contain the individuals + * in the given exclude list as shallow copies. + * @param exclude + * @return + */ + public Population filter(Population exclude) { + if (exclude.size() == 0) return this; + Population pop = new Population(); + for (Object o : this) { + if (!exclude.contains(o)) pop.add(o); + } + return pop; + } /** This method returns the currently worst individual from the population * @return The best individual @@ -560,4 +670,13 @@ public class Population extends ArrayList implements PopulationInterface, Clonea public int getGenerations() { return this.m_Generation; } + + /** + * Fire an event every n function calls, the event sends the public String funCallIntervalReached. + * + * @param notifyEvalInterval the notifyEvalInterval to set + */ + public void setNotifyEvalInterval(int notifyEvalInterval) { + this.notifyEvalInterval = notifyEvalInterval; + } } diff --git a/src/javaeva/server/go/problems/AbstractOptimizationProblem.java b/src/javaeva/server/go/problems/AbstractOptimizationProblem.java index fd8f9be6..3b80806c 100644 --- a/src/javaeva/server/go/problems/AbstractOptimizationProblem.java +++ b/src/javaeva/server/go/problems/AbstractOptimizationProblem.java @@ -83,78 +83,10 @@ public abstract class AbstractOptimizationProblem implements InterfaceOptimizati } /** This method evaluate a single individual and sets the fitness values - * @param individual The individual that is to be evalutated + * @param individual The individual that is to be evaluated */ public abstract void evaluate(AbstractEAIndividual individual); - /** This method should be used to calculate the distance between two - * individuals. Per default i implemented a phenotypic distance metric. - * @param indy1 The first individual. - * @param indy2 The second individual. - * @return The distance. - */ - public double distanceBetween(AbstractEAIndividual indy1, AbstractEAIndividual indy2) { - double result = 1; - if ((indy1 instanceof InterfaceDataTypeBinary) && (indy2 instanceof InterfaceDataTypeBinary)) { - BitSet b1, b2; - b1 = ((InterfaceDataTypeBinary)indy1).getBinaryData(); - b2 = ((InterfaceDataTypeBinary)indy2).getBinaryData(); - if (b1.length() != b2.length()) return Math.max(b1.length(), b2.length()); - result = b1.length(); - for (int i = 0; i < b1.length(); i++) { - if (b1.get(i) == b2.get(i)) result--; - } - result = result/((double)b1.length()); - } - if ((indy1 instanceof InterfaceDataTypeInteger) && (indy2 instanceof InterfaceDataTypeInteger)) { - int[] b1, b2; - int[][] range; - int max = 0; - b1 = ((InterfaceDataTypeInteger)indy1).getIntegerData(); - b2 = ((InterfaceDataTypeInteger)indy2).getIntegerData(); - if (b1.length != b2.length) return Math.max(b1.length, b2.length); - range = ((InterfaceDataTypeInteger)indy2).getIntRange(); - result = 0; - for (int i = 0; i < b1.length; i++) { - result += Math.abs(b1[i]-b2[i]); - max += range[i][1]-range[i][0]; - } - result = result/((double)max); - } - if ((indy1 instanceof InterfaceDataTypeDouble) && (indy2 instanceof InterfaceDataTypeDouble)) { - double[] b1, b2; - double[][] range; - double max = 0; - b1 = ((InterfaceDataTypeDouble)indy1).getDoubleData(); - b2 = ((InterfaceDataTypeDouble)indy2).getDoubleData(); - if (b1.length != b2.length) return Math.max(b1.length, b2.length); - result = 0; - range = ((InterfaceDataTypeDouble)indy1).getDoubleRange(); - for (int i = 0; i < (Math.min(b1.length, b2.length)); i++) { - result += Math.abs(b1[i]-b2[i]); - max += range[i][1]-range[i][0]; - } - result = result/max; - } - if ((indy1 instanceof InterfaceDataTypePermutation) && (indy2 instanceof InterfaceDataTypePermutation)) { - int[] b1, b2; - b1 = ((InterfaceDataTypePermutation)indy1).getPermutationData()[0]; - b2 = ((InterfaceDataTypePermutation)indy2).getPermutationData()[0]; - if (b1.length != b2.length) return Math.max(b1.length, b2.length); - result = b1.length; - int tmp; - for (int i = 0; i < b1.length; i++) { - tmp = b1.length; - for (int j = 0; j < b1.length; j++) { - if (b1[j] != b2[(j+i)%b1.length]) tmp++; - } - result = Math.min(result, tmp); - } - result = result/((double)b1.length); - } - return result; - } - /******************** Some output methods *******************************************/ /** This method allows you to output a string that describes a found solution @@ -238,7 +170,8 @@ public abstract class AbstractOptimizationProblem implements InterfaceOptimizati } /** - * TODO + * For some evaluation cases it may be necessary to inform the problem class about the optimizer in use. + * * @param opt */ public void informAboutOptimizer(InterfaceOptimizer opt) { diff --git a/src/javaeva/server/go/problems/F10Problem.java b/src/javaeva/server/go/problems/F10Problem.java index 2f784318..f712d238 100644 --- a/src/javaeva/server/go/problems/F10Problem.java +++ b/src/javaeva/server/go/problems/F10Problem.java @@ -1,6 +1,5 @@ package javaeva.server.go.problems; -import javaeva.server.go.individuals.AbstractEAIndividual; import javaeva.server.go.individuals.ESIndividualDoubleData; /** @@ -10,7 +9,7 @@ import javaeva.server.go.individuals.ESIndividualDoubleData; * Time: 14:33:07 * To change this template use File | Settings | File Templates. */ -public class F10Problem extends F1Problem implements java.io.Serializable { +public class F10Problem extends F1Problem implements InterfaceMultimodalProblem, java.io.Serializable { private double m_D = 1.5; private double m_b = 2.3; @@ -20,17 +19,7 @@ public class F10Problem extends F1Problem implements java.io.Serializable { this.m_Template = new ESIndividualDoubleData(); } public F10Problem(F10Problem b) { - //AbstractOptimizationProblem - if (b.m_Template != null) - this.m_Template = (AbstractEAIndividual)((AbstractEAIndividual)b.m_Template).clone(); - //F1Problem - if (b.m_OverallBest != null) - this.m_OverallBest = (AbstractEAIndividual)((AbstractEAIndividual)b.m_OverallBest).clone(); - this.m_ProblemDimension = b.m_ProblemDimension; - this.m_Noise = b.m_Noise; - this.m_XOffSet = b.m_XOffSet; - this.m_YOffSet = b.m_YOffSet; - this.m_UseTestConstraint = b.m_UseTestConstraint; + super(b); this.m_D = b.m_D; this.m_b = b.m_b; this.m_Iterations = b.m_Iterations; diff --git a/src/javaeva/server/go/problems/F11Problem.java b/src/javaeva/server/go/problems/F11Problem.java index 274efa99..931eb3f5 100644 --- a/src/javaeva/server/go/problems/F11Problem.java +++ b/src/javaeva/server/go/problems/F11Problem.java @@ -12,7 +12,7 @@ import javaeva.server.go.populations.Population; * Time: 14:59:23 * To change this template use File | Settings | File Templates. */ -public class F11Problem extends F1Problem implements java.io.Serializable { +public class F11Problem extends F1Problem implements InterfaceMultimodalProblem, java.io.Serializable { private double m_D = 4000; @@ -23,17 +23,7 @@ public class F11Problem extends F1Problem implements java.io.Serializable { } public F11Problem(F11Problem b) { - //AbstractOptimizationProblem - if (b.m_Template != null) - this.m_Template = (AbstractEAIndividual)((AbstractEAIndividual)b.m_Template).clone(); - //F1Problem - if (b.m_OverallBest != null) - this.m_OverallBest = (AbstractEAIndividual)((AbstractEAIndividual)b.m_OverallBest).clone(); - this.m_ProblemDimension = b.m_ProblemDimension; - this.m_Noise = b.m_Noise; - this.m_XOffSet = b.m_XOffSet; - this.m_YOffSet = b.m_YOffSet; - this.m_UseTestConstraint = b.m_UseTestConstraint; + super(b); this.m_D = b.m_D; } diff --git a/src/javaeva/server/go/problems/F12Problem.java b/src/javaeva/server/go/problems/F12Problem.java index 105718ec..183649b4 100644 --- a/src/javaeva/server/go/problems/F12Problem.java +++ b/src/javaeva/server/go/problems/F12Problem.java @@ -18,17 +18,7 @@ public class F12Problem extends F1Problem implements java.io.Serializable { this.m_Template = new ESIndividualDoubleData(); } public F12Problem(F12Problem b) { - //AbstractOptimizationProblem - if (b.m_Template != null) - this.m_Template = (AbstractEAIndividual)((AbstractEAIndividual)b.m_Template).clone(); - //F1Problem - if (b.m_OverallBest != null) - this.m_OverallBest = (AbstractEAIndividual)((AbstractEAIndividual)b.m_OverallBest).clone(); - this.m_ProblemDimension = b.m_ProblemDimension; - this.m_Noise = b.m_Noise; - this.m_XOffSet = b.m_XOffSet; - this.m_YOffSet = b.m_YOffSet; - this.m_UseTestConstraint = b.m_UseTestConstraint; + super(b); } /** This method returns a deep clone of the problem. @@ -44,7 +34,7 @@ public class F12Problem extends F1Problem implements java.io.Serializable { public void initPopulation(Population population) { AbstractEAIndividual tmpIndy; - this.m_OverallBest = null; +// this.m_OverallBest = null; population.clear(); diff --git a/src/javaeva/server/go/problems/F13Problem.java b/src/javaeva/server/go/problems/F13Problem.java index 225abaa6..05e1e0a9 100644 --- a/src/javaeva/server/go/problems/F13Problem.java +++ b/src/javaeva/server/go/problems/F13Problem.java @@ -9,23 +9,13 @@ import javaeva.server.go.populations.Population; * Schwefels sine root function (1981) with a minimum at 420.9687^n of value 0. * Function f(x) = (418.9829 * n) - sum_n(x_i * sin(sqrt(abs(x_i)))) + (418.9829 * n); */ -public class F13Problem extends F1Problem { +public class F13Problem extends F1Problem implements InterfaceMultimodalProblem { public F13Problem() { this.m_Template = new ESIndividualDoubleData(); } public F13Problem(F13Problem b) { - //AbstractOptimizationProblem - if (b.m_Template != null) - this.m_Template = (AbstractEAIndividual)((AbstractEAIndividual)b.m_Template).clone(); - //F1Problem - if (b.m_OverallBest != null) - this.m_OverallBest = (AbstractEAIndividual)((AbstractEAIndividual)b.m_OverallBest).clone(); - this.m_ProblemDimension = b.m_ProblemDimension; - this.m_Noise = b.m_Noise; - this.m_XOffSet = b.m_XOffSet; - this.m_YOffSet = b.m_YOffSet; - this.m_UseTestConstraint = b.m_UseTestConstraint; + super(b); } /** This method returns a deep clone of the problem. diff --git a/src/javaeva/server/go/problems/F14Problem.java b/src/javaeva/server/go/problems/F14Problem.java index e3130c17..03c7ed57 100644 --- a/src/javaeva/server/go/problems/F14Problem.java +++ b/src/javaeva/server/go/problems/F14Problem.java @@ -1,6 +1,5 @@ package javaeva.server.go.problems; -import javaeva.server.go.individuals.AbstractEAIndividual; import javaeva.server.go.individuals.ESIndividualDoubleData; /** @@ -19,17 +18,8 @@ public class F14Problem extends F1Problem implements java.io.Serializable { } public F14Problem(F14Problem b) { - //AbstractOptimizationProblem - if (b.m_Template != null) - this.m_Template = (AbstractEAIndividual)((AbstractEAIndividual)b.m_Template).clone(); - //F1Problem - if (b.m_OverallBest != null) - this.m_OverallBest = (AbstractEAIndividual)((AbstractEAIndividual)b.m_OverallBest).clone(); - this.m_ProblemDimension = b.m_ProblemDimension; - this.m_Noise = b.m_Noise; - this.m_XOffSet = b.m_XOffSet; - this.m_YOffSet = b.m_YOffSet; - this.m_UseTestConstraint = b.m_UseTestConstraint; + super(b); + rotation = b.rotation; } /** This method returns a deep clone of the problem. diff --git a/src/javaeva/server/go/problems/F1Problem.java b/src/javaeva/server/go/problems/F1Problem.java index 0e790569..5b516d41 100644 --- a/src/javaeva/server/go/problems/F1Problem.java +++ b/src/javaeva/server/go/problems/F1Problem.java @@ -18,7 +18,7 @@ public class F1Problem extends AbstractProblemDouble implements Interface2DBorde * */ private static final long serialVersionUID = 4870484001737601464L; - protected AbstractEAIndividual m_OverallBest = null; +// protected AbstractEAIndividual m_OverallBest = null; protected int m_ProblemDimension = 10; protected double m_XOffSet = 0.0; protected double m_YOffSet = 0.0; @@ -33,8 +33,8 @@ public class F1Problem extends AbstractProblemDouble implements Interface2DBorde if (b.m_Template != null) this.m_Template = (AbstractEAIndividual)((AbstractEAIndividual)b.m_Template).clone(); //F1Problem - if (b.m_OverallBest != null) - this.m_OverallBest = (AbstractEAIndividual)((AbstractEAIndividual)b.m_OverallBest).clone(); +// if (b.m_OverallBest != null) +// this.m_OverallBest = (AbstractEAIndividual)((AbstractEAIndividual)b.m_OverallBest).clone(); this.m_ProblemDimension = b.m_ProblemDimension; this.m_Noise = b.m_Noise; this.m_DefaultRange = b.m_DefaultRange; @@ -53,7 +53,7 @@ public class F1Problem extends AbstractProblemDouble implements Interface2DBorde /** This method inits the Problem to log multiruns */ public void initProblem() { - this.m_OverallBest = null; +// this.m_OverallBest = null; } /** This method inits a given population @@ -76,9 +76,9 @@ public class F1Problem extends AbstractProblemDouble implements Interface2DBorde if (this.m_UseTestConstraint) { if (x[0] < 1) individual.addConstraintViolation(1-x[0]); } - if ((this.m_OverallBest == null) || (this.m_OverallBest.getFitness(0) > individual.getFitness(0))) { - this.m_OverallBest = (AbstractEAIndividual)individual.clone(); - } +// if ((this.m_OverallBest == null) || (this.m_OverallBest.getFitness(0) > individual.getFitness(0))) { +// this.m_OverallBest = (AbstractEAIndividual)individual.clone(); +// } } /** Ths method allows you to evaluate a simple bit string to determine the fitness diff --git a/src/javaeva/server/go/problems/F2Problem.java b/src/javaeva/server/go/problems/F2Problem.java index 122c31ac..b540b844 100644 --- a/src/javaeva/server/go/problems/F2Problem.java +++ b/src/javaeva/server/go/problems/F2Problem.java @@ -11,23 +11,13 @@ import javaeva.server.go.strategies.InterfaceOptimizer; * Time: 19:03:09 * To change this template use File | Settings | File Templates. */ -public class F2Problem extends F1Problem implements java.io.Serializable { +public class F2Problem extends F1Problem implements InterfaceMultimodalProblem, java.io.Serializable { public F2Problem() { this.m_Template = new ESIndividualDoubleData(); } public F2Problem(F2Problem b) { - //AbstractOptimizationProblem - if (b.m_Template != null) - this.m_Template = (AbstractEAIndividual)((AbstractEAIndividual)b.m_Template).clone(); - //F1Problem - if (b.m_OverallBest != null) - this.m_OverallBest = (AbstractEAIndividual)((AbstractEAIndividual)b.m_OverallBest).clone(); - this.m_ProblemDimension = b.m_ProblemDimension; - this.m_Noise = b.m_Noise; - this.m_XOffSet = b.m_XOffSet; - this.m_YOffSet = b.m_YOffSet; - this.m_UseTestConstraint = b.m_UseTestConstraint; + super(b); } /** This method returns a deep clone of the problem. diff --git a/src/javaeva/server/go/problems/F3Problem.java b/src/javaeva/server/go/problems/F3Problem.java index ae3c4735..611d75f7 100644 --- a/src/javaeva/server/go/problems/F3Problem.java +++ b/src/javaeva/server/go/problems/F3Problem.java @@ -16,17 +16,7 @@ public class F3Problem extends F1Problem implements java.io.Serializable { this.m_Template = new ESIndividualDoubleData(); } public F3Problem(F3Problem b) { - //AbstractOptimizationProblem - if (b.m_Template != null) - this.m_Template = (AbstractEAIndividual)((AbstractEAIndividual)b.m_Template).clone(); - //F1Problem - if (b.m_OverallBest != null) - this.m_OverallBest = (AbstractEAIndividual)((AbstractEAIndividual)b.m_OverallBest).clone(); - this.m_ProblemDimension = b.m_ProblemDimension; - this.m_Noise = b.m_Noise; - this.m_XOffSet = b.m_XOffSet; - this.m_YOffSet = b.m_YOffSet; - this.m_UseTestConstraint = b.m_UseTestConstraint; + super(b); } /** This method returns a deep clone of the problem. diff --git a/src/javaeva/server/go/problems/F4Problem.java b/src/javaeva/server/go/problems/F4Problem.java index dcf71e53..175bfdb5 100644 --- a/src/javaeva/server/go/problems/F4Problem.java +++ b/src/javaeva/server/go/problems/F4Problem.java @@ -19,17 +19,7 @@ public class F4Problem extends F1Problem implements java.io.Serializable { this.m_Template = new ESIndividualDoubleData(); } public F4Problem(F4Problem b) { - //AbstractOptimizationProblem - if (b.m_Template != null) - this.m_Template = (AbstractEAIndividual)((AbstractEAIndividual)b.m_Template).clone(); - //F1Problem - if (b.m_OverallBest != null) - this.m_OverallBest = (AbstractEAIndividual)((AbstractEAIndividual)b.m_OverallBest).clone(); - this.m_ProblemDimension = b.m_ProblemDimension; - this.m_Noise = b.m_Noise; - this.m_XOffSet = b.m_XOffSet; - this.m_YOffSet = b.m_YOffSet; - this.m_UseTestConstraint = b.m_UseTestConstraint; + super(b); } /** This method inits a given population @@ -38,7 +28,7 @@ public class F4Problem extends F1Problem implements java.io.Serializable { public void initPopulation(Population population) { AbstractEAIndividual tmpIndy; - this.m_OverallBest = null; +// this.m_OverallBest = null; population.clear(); diff --git a/src/javaeva/server/go/problems/F5Problem.java b/src/javaeva/server/go/problems/F5Problem.java index 7b2db714..784a2ace 100644 --- a/src/javaeva/server/go/problems/F5Problem.java +++ b/src/javaeva/server/go/problems/F5Problem.java @@ -19,17 +19,7 @@ public class F5Problem extends F1Problem implements java.io.Serializable { this.m_Template = new ESIndividualDoubleData(); } public F5Problem(F5Problem b) { - //AbstractOptimizationProblem - if (b.m_Template != null) - this.m_Template = (AbstractEAIndividual)((AbstractEAIndividual)b.m_Template).clone(); - //F1Problem - if (b.m_OverallBest != null) - this.m_OverallBest = (AbstractEAIndividual)((AbstractEAIndividual)b.m_OverallBest).clone(); - this.m_ProblemDimension = b.m_ProblemDimension; - this.m_Noise = b.m_Noise; - this.m_XOffSet = b.m_XOffSet; - this.m_YOffSet = b.m_YOffSet; - this.m_UseTestConstraint = b.m_UseTestConstraint; + super(b); } /** This method inits a given population @@ -38,7 +28,7 @@ public class F5Problem extends F1Problem implements java.io.Serializable { public void initPopulation(Population population) { AbstractEAIndividual tmpIndy; - this.m_OverallBest = null; +// this.m_OverallBest = null; population.clear(); diff --git a/src/javaeva/server/go/problems/F6Problem.java b/src/javaeva/server/go/problems/F6Problem.java index f9122af0..3684767f 100644 --- a/src/javaeva/server/go/problems/F6Problem.java +++ b/src/javaeva/server/go/problems/F6Problem.java @@ -1,6 +1,5 @@ package javaeva.server.go.problems; -import javaeva.server.go.individuals.AbstractEAIndividual; import javaeva.server.go.individuals.ESIndividualDoubleData; import javaeva.server.go.strategies.ParticleSwarmOptimization; import wsi.ra.math.Jama.Matrix; @@ -12,7 +11,7 @@ import wsi.ra.math.Jama.Matrix; * Time: 13:09:36 * To change this template use File | Settings | File Templates. */ -public class F6Problem extends F1Problem implements java.io.Serializable { +public class F6Problem extends F1Problem implements InterfaceMultimodalProblem, java.io.Serializable { private boolean doRotation = false; private double m_A = 10; @@ -23,17 +22,8 @@ public class F6Problem extends F1Problem implements java.io.Serializable { this.m_Template = new ESIndividualDoubleData(); } public F6Problem(F6Problem b) { - //AbstractOptimizationProblem - if (b.m_Template != null) - this.m_Template = (AbstractEAIndividual)((AbstractEAIndividual)b.m_Template).clone(); - //F1Problem - if (b.m_OverallBest != null) - this.m_OverallBest = (AbstractEAIndividual)((AbstractEAIndividual)b.m_OverallBest).clone(); - this.m_ProblemDimension = b.m_ProblemDimension; - this.m_Noise = b.m_Noise; - this.m_XOffSet = b.m_XOffSet; - this.m_YOffSet = b.m_YOffSet; - this.m_UseTestConstraint = b.m_UseTestConstraint; + super(b); + doRotation = b.doRotation; this.m_A = b.m_A; this.m_Omega = b.m_Omega; } diff --git a/src/javaeva/server/go/problems/F7Problem.java b/src/javaeva/server/go/problems/F7Problem.java index b4001d35..4e008cc3 100644 --- a/src/javaeva/server/go/problems/F7Problem.java +++ b/src/javaeva/server/go/problems/F7Problem.java @@ -30,19 +30,10 @@ public class F7Problem extends F1Problem implements java.io.Serializable { this.m_Template = new ESIndividualDoubleData(); } public F7Problem(F7Problem b) { - //AbstractOptimizationProblem - if (b.m_Template != null) - this.m_Template = (AbstractEAIndividual)((AbstractEAIndividual)b.m_Template).clone(); - //F1Problem - if (b.m_OverallBest != null) - this.m_OverallBest = (AbstractEAIndividual)((AbstractEAIndividual)b.m_OverallBest).clone(); - this.m_ProblemDimension = b.m_ProblemDimension; - this.m_Noise = b.m_Noise; - this.m_XOffSet = b.m_XOffSet; - this.m_YOffSet = b.m_YOffSet; - this.m_UseTestConstraint = b.m_UseTestConstraint; + super(b); + this.m_Change = b.m_Change; this.m_t = b.m_t; - this.m_TimeIntervalType = (SelectedTag)b.m_TimeIntervalType; + this.m_TimeIntervalType = (SelectedTag)b.m_TimeIntervalType.clone(); } /** This method returns a deep clone of the problem. @@ -58,7 +49,8 @@ public class F7Problem extends F1Problem implements java.io.Serializable { */ public void evaluate(Population population) { AbstractEAIndividual tmpIndy; - + + evaluatePopulationStart(population); for (int i = 0; i < population.size(); i++) { tmpIndy = (AbstractEAIndividual) population.get(i); tmpIndy.resetConstraintViolation(); @@ -70,6 +62,7 @@ public class F7Problem extends F1Problem implements java.io.Serializable { this.evaluate(tmpIndy); population.incrFunctionCalls(); } + evaluatePopulationEnd(population); } /** This method evaluate a single individual and sets the fitness values @@ -94,9 +87,9 @@ public class F7Problem extends F1Problem implements java.io.Serializable { if (this.m_UseTestConstraint) { if (x[0] < 1) individual.addConstraintViolation(1-x[0]); } - if ((this.m_OverallBest == null) || (this.m_OverallBest.getFitness(0) > individual.getFitness(0))) { - this.m_OverallBest = (AbstractEAIndividual)individual.clone(); - } +// if ((this.m_OverallBest == null) || (this.m_OverallBest.getFitness(0) > individual.getFitness(0))) { +// this.m_OverallBest = (AbstractEAIndividual)individual.clone(); +// } } /** Ths method allows you to evaluate a double[] to determine the fitness diff --git a/src/javaeva/server/go/problems/F8Problem.java b/src/javaeva/server/go/problems/F8Problem.java index 94afe3c4..d3ef8e29 100644 --- a/src/javaeva/server/go/problems/F8Problem.java +++ b/src/javaeva/server/go/problems/F8Problem.java @@ -4,7 +4,6 @@ import javaeva.server.go.individuals.AbstractEAIndividual; import javaeva.server.go.individuals.ESIndividualDoubleData; import javaeva.server.go.individuals.InterfaceDataTypeDouble; import javaeva.server.go.populations.Population; -import javaeva.server.go.tools.RandomNumberGenerator; /** * Created by IntelliJ IDEA. @@ -13,7 +12,7 @@ import javaeva.server.go.tools.RandomNumberGenerator; * Time: 19:40:28 * To change this template use File | Settings | File Templates. */ -public class F8Problem extends F1Problem implements java.io.Serializable { +public class F8Problem extends F1Problem implements InterfaceMultimodalProblem, java.io.Serializable { private double a = 20; private double b = 0.2; @@ -23,17 +22,10 @@ public class F8Problem extends F1Problem implements java.io.Serializable { this.m_Template = new ESIndividualDoubleData(); } public F8Problem(F8Problem b) { - //AbstractOptimizationProblem - if (b.m_Template != null) - this.m_Template = (AbstractEAIndividual)((AbstractEAIndividual)b.m_Template).clone(); - //F1Problem - if (b.m_OverallBest != null) - this.m_OverallBest = (AbstractEAIndividual)((AbstractEAIndividual)b.m_OverallBest).clone(); - this.m_ProblemDimension = b.m_ProblemDimension; - this.m_Noise = b.m_Noise; - this.m_XOffSet = b.m_XOffSet; - this.m_YOffSet = b.m_YOffSet; - this.m_UseTestConstraint = b.m_UseTestConstraint; + super(b); + this.a = b.a; + this.b = b.b; + this.c = b.c; } /** This method returns a deep clone of the problem. @@ -49,7 +41,7 @@ public class F8Problem extends F1Problem implements java.io.Serializable { public void initPopulation(Population population) { AbstractEAIndividual tmpIndy; - this.m_OverallBest = null; +// this.m_OverallBest = null; population.clear(); diff --git a/src/javaeva/server/go/problems/F9Problem.java b/src/javaeva/server/go/problems/F9Problem.java index 6c5c75be..bedab7fb 100644 --- a/src/javaeva/server/go/problems/F9Problem.java +++ b/src/javaeva/server/go/problems/F9Problem.java @@ -16,17 +16,7 @@ public class F9Problem extends F1Problem implements java.io.Serializable { this.m_Template = new ESIndividualDoubleData(); } public F9Problem(F9Problem b) { - //AbstractOptimizationProblem - if (b.m_Template != null) - this.m_Template = (AbstractEAIndividual)((AbstractEAIndividual)b.m_Template).clone(); - //F1Problem - if (b.m_OverallBest != null) - this.m_OverallBest = (AbstractEAIndividual)((AbstractEAIndividual)b.m_OverallBest).clone(); - this.m_ProblemDimension = b.m_ProblemDimension; - this.m_Noise = b.m_Noise; - this.m_XOffSet = b.m_XOffSet; - this.m_YOffSet = b.m_YOffSet; - this.m_UseTestConstraint = b.m_UseTestConstraint; + super(b); } /** This method returns a deep clone of the problem. diff --git a/src/javaeva/server/go/problems/FM0Problem.java b/src/javaeva/server/go/problems/FM0Problem.java index 617f4fac..6afb4037 100644 --- a/src/javaeva/server/go/problems/FM0Problem.java +++ b/src/javaeva/server/go/problems/FM0Problem.java @@ -1,13 +1,15 @@ package javaeva.server.go.problems; +import java.io.Serializable; +import java.util.List; + import javaeva.server.go.individuals.AbstractEAIndividual; import javaeva.server.go.individuals.ESIndividualDoubleData; import javaeva.server.go.individuals.InterfaceDataTypeDouble; import javaeva.server.go.operators.distancemetric.InterfaceDistanceMetric; -import javaeva.server.go.operators.distancemetric.PhenotypeMetricDoubleData; +import javaeva.server.go.operators.distancemetric.PhenotypeMetric; +import javaeva.server.go.operators.postprocess.PostProcess; import javaeva.server.go.populations.Population; -import javaeva.server.go.strategies.InterfaceOptimizer; -import javaeva.server.go.tools.RandomNumberGenerator; /** * Created by IntelliJ IDEA. @@ -16,16 +18,17 @@ import javaeva.server.go.tools.RandomNumberGenerator; * Time: 11:10:43 * To change this template use Options | File Templates. */ -public class FM0Problem extends F1Problem implements Interface2DBorderProblem, InterfaceMultimodalProblem, java.io.Serializable { +public class FM0Problem extends AbstractProblemDouble implements Interface2DBorderProblem, InterfaceMultimodalProblemKnown, Serializable { - protected InterfaceDistanceMetric m_Metric = new PhenotypeMetricDoubleData(); + protected static InterfaceDistanceMetric m_Metric = new PhenotypeMetric(); protected double m_GlobalOpt = 0; protected Population m_Optima; protected double m_Epsilon = 0.05; - protected boolean m_UseXCrit = true; - protected boolean m_UseYCrit = true; +// protected boolean m_UseXCrit = true; +// protected boolean m_UseYCrit = true; protected double[][] m_Range; protected double[] m_Extrema; + protected int m_ProblemDimension = 2; public FM0Problem() { this.m_Template = new ESIndividualDoubleData(); @@ -54,21 +57,21 @@ public class FM0Problem extends F1Problem implements Interface2DBorderProblem, I if (b.m_Template != null) this.m_Template = (AbstractEAIndividual)((AbstractEAIndividual)b.m_Template).clone(); //F1Problem - if (b.m_OverallBest != null) - this.m_OverallBest = (AbstractEAIndividual)((AbstractEAIndividual)b.m_OverallBest).clone(); +// if (b.m_OverallBest != null) +// this.m_OverallBest = (AbstractEAIndividual)((AbstractEAIndividual)b.m_OverallBest).clone(); this.m_ProblemDimension = b.m_ProblemDimension; this.m_Noise = b.m_Noise; - this.m_XOffSet = b.m_XOffSet; - this.m_YOffSet = b.m_YOffSet; - this.m_UseTestConstraint = b.m_UseTestConstraint; +// this.m_XOffSet = b.m_XOffSet; +// this.m_YOffSet = b.m_YOffSet; +// this.m_UseTestConstraint = b.m_UseTestConstraint; //FM0Problem this.m_GlobalOpt = b.m_GlobalOpt; this.m_Epsilon = b.m_Epsilon; - this.m_UseXCrit = b.m_UseXCrit; - this.m_UseYCrit = b.m_UseYCrit; - this.m_UseXCrit = b.m_UseXCrit; - if (b.m_Metric != null) - this.m_Metric = (InterfaceDistanceMetric)((InterfaceDistanceMetric)b.m_Metric).clone(); +// this.m_UseXCrit = b.m_UseXCrit; +// this.m_UseYCrit = b.m_UseYCrit; +// this.m_UseXCrit = b.m_UseXCrit; +// if (m_Metric != null) +// this.m_Metric = (InterfaceDistanceMetric)((InterfaceDistanceMetric)b.m_Metric).clone(); if (b.m_Optima != null) this.m_Optima = (Population)((Population)b.m_Optima).clone(); if (b.m_Extrema != null) { @@ -100,7 +103,7 @@ public class FM0Problem extends F1Problem implements Interface2DBorderProblem, I public void initPopulation(Population population) { AbstractEAIndividual tmpIndy; - this.m_OverallBest = null; +// this.m_OverallBest = null; population.clear(); @@ -128,7 +131,7 @@ public class FM0Problem extends F1Problem implements Interface2DBorderProblem, I return result; } - /** This method returns the unnormalized function value for an maximisation problem + /** This method returns the unnormalized function value for an maximization problem * @param x The n-dimensional input vector * @return The m-dimensional output vector. */ @@ -197,8 +200,19 @@ public class FM0Problem extends F1Problem implements Interface2DBorderProblem, I InterfaceDataTypeDouble tmpIndy; tmpIndy = (InterfaceDataTypeDouble)((AbstractEAIndividual)this.m_Template).clone(); tmpIndy.SetDoubleDataLamarkian(point); - ((AbstractEAIndividual)tmpIndy).SetFitness(this.evalUnnormalized(point)); - this.m_GlobalOpt = Math.max(this.m_GlobalOpt, ((AbstractEAIndividual)tmpIndy).getFitness(0)); + ((AbstractEAIndividual)tmpIndy).SetFitness(evalUnnormalized(point)); + if (((AbstractEAIndividual)tmpIndy).getFitness(0)>=m_GlobalOpt) { + m_GlobalOpt = ((AbstractEAIndividual)tmpIndy).getFitness(0); + double tmp=m_GlobalOpt; + double dx = 1e-30; + while (tmp==m_GlobalOpt) { + // this increases the optimum until there is a real difference. + // tries to avoid zero y-values which break the logarithmic plot + tmp+=dx; + dx *= 10; + } + m_GlobalOpt = tmp; + } this.m_Optima.add(tmpIndy); } @@ -220,70 +234,68 @@ public class FM0Problem extends F1Problem implements Interface2DBorderProblem, I /** This method returns a list of all optima as population * @return population */ - public Population getAllOptima() { + public Population getRealOptima() { return this.m_Optima; } - /** This method returns the overall number of optima - * @return int - */ - public int getNumberOfOptima() { - return this.m_Optima.size(); - } - /** This method returns the Number of Identified optima * @param pop A population of possible solutions. * @return int */ public int getNumberOfFoundOptima(Population pop) { - int result = 0; - AbstractEAIndividual posOpt, opt; - boolean[] found = new boolean[this.m_Optima.size()]; - for (int i = 0; i < found.length; i++) found[i] = false; - - for (int i = 0; i < pop.size(); i++) { - posOpt = (AbstractEAIndividual) pop.get(i); - for (int j = 0; j < this.m_Optima.size(); j++) { - opt = (AbstractEAIndividual) this.m_Optima.get(j); - if (!found[j]) { - if (this.m_Metric.distance(posOpt, opt) < this.m_Epsilon) found[j] = true; - } - } - } - for (int i = 0; i < found.length; i++) if (found[i]) result++; - return result; + List sols = PostProcess.getFoundOptima(pop, m_Optima, m_Epsilon, true); + return sols.size(); } - - /** This method returns the Maximum Peak Ratio. + + /** + * This method returns the maximum peak ratio, which is the ratio of found fitness values corresponding to + * known optima with the internal epsilon criterion and the sum of all fitness values seen as maximization. + * Thus, if all optima are perfectly found, 1 is returned. If no optimum is found, zero is returned. + * A return value of 0.5 may mean, e.g., that half of n similar optima have been found perfectly, or that 1 major + * optimum of equal weight than all the others has been found perfectly, or that all optima have been found + * with about 50% accuracy, etc. + * * @param pop A population of possible solutions. * @return double */ public double getMaximumPeakRatio(Population pop) { - double result = 0, sum = 0; - AbstractEAIndividual posOpt, opt; - boolean[] found = new boolean[this.m_Optima.size()]; - for (int i = 0; i < found.length; i++) { - found[i] = false; - sum += ((AbstractEAIndividual)this.m_Optima.get(i)).getFitness(0) ; - //System.out.println("Optimum " + i + ".: " + (((AbstractEAIndividual)this.m_Optima.get(i)).getFitness(0))); - } - - for (int i = 0; i < pop.size(); i++) { - posOpt = (AbstractEAIndividual) pop.get(i); - for (int j = 0; j < this.m_Optima.size(); j++) { - if (!found[j]) { - opt = (AbstractEAIndividual) this.m_Optima.get(j); - if (this.m_Metric.distance(posOpt, opt) < this.m_Epsilon) { - found[j] = true; - result += this.m_GlobalOpt - posOpt.getFitness(0); - //System.out.println("Found Optimum " + j + ".: " + (this.m_GlobalOpt - posOpt.getFitness(0))); - } - } - } - } - return result/sum; + double optimaInvertedSum = 0, foundInvertedSum = 0; + AbstractEAIndividual[] optsFound = PostProcess.getFoundOptimaArray(pop, m_Optima, m_Epsilon, true); + + for (int i=0; i m_Species = new ArrayList(); public Population m_Undifferentiated = new Population(); private InterfaceOptimizationProblem m_Problem = new B1Problem(); @@ -52,13 +58,15 @@ public class ClusterBasedNichingEA implements InterfacePopulationChangedEventLis private int m_actSpecSize = 2; private int m_minGroupSize = 3; private boolean m_UseClearing = false; + private boolean m_UseArchive = true; private boolean m_UseSpeciesDifferentation = true; private boolean m_UseSpeciesConvergence = true; private boolean m_UseHaltingWindow = true; private int m_PopulationSize = 50; + private int convergedCnt = 0; - private boolean m_Debug = true; - private int m_ShowCycle = 10; + private static boolean TRACE = false; + private int m_ShowCycle = 100; transient private TopoPlot m_Topology; private int haltingWindow = 15; private double muLambdaRatio = 0.5; @@ -98,8 +106,12 @@ public class ClusterBasedNichingEA implements InterfacePopulationChangedEventLis this.m_Undifferentiated.setPopulationSize(this.m_PopulationSize); this.m_Species = new ArrayList(); this.m_Problem.initPopulation(this.m_Undifferentiated); - this.getPopulation().setUseHistory(true); this.evaluatePopulation(this.m_Undifferentiated); + this.m_Optimizer.initByPopulation(m_Undifferentiated, false); + m_Archive = new Population(); + convergedCnt = 0; + this.m_Undifferentiated = m_Optimizer.getPopulation(); // required for changes to the population by the optimizer +// this.getPopulation().setUseHistory(true); // TODO this makes no sense if getPopulation clones the pop. this.firePropertyChangedEvent("FirstGenerationPerformed"); } @@ -114,7 +126,11 @@ public class ClusterBasedNichingEA implements InterfacePopulationChangedEventLis if (reset) this.m_Undifferentiated.init(); this.m_Undifferentiated.setPopulationSize(this.m_PopulationSize); this.m_Species = new ArrayList(); + m_Archive = new Population(); + convergedCnt = 0; this.evaluatePopulation(this.m_Undifferentiated); + this.m_Optimizer.initByPopulation(m_Undifferentiated, false); + this.m_Undifferentiated = m_Optimizer.getPopulation(); // required for changes to the population by the optimizer this.firePropertyChangedEvent("FirstGenerationPerformed"); } @@ -195,29 +211,28 @@ public class ClusterBasedNichingEA implements InterfacePopulationChangedEventLis popRep.addDPoint(new DPoint(best.getDoubleData()[0], best.getDoubleData()[1])); this.m_Topology.getFunctionArea().addDElement(popRep); } -// popRep = new DPointSet(); -// tmpIndy1 = (InterfaceDataTypeDouble)pop.getBestEAIndividual(); -// popRep.addDPoint(new DPoint(tmpIndy1.getDoubleData()[0], tmpIndy1.getDoubleData()[1])); -// double d = Math.round(100*((AbstractEAIndividual)tmpIndy1).getFitness(0))/(double)100; -// DPointIcon icon = new Chart2DDPointIconText(""+d); -// ((Chart2DDPointIconText)icon).setIcon(new Chart2DDPointIconCircle()); -// popRep.setIcon(icon); -// this.m_Topology.m_PlotArea.addDElement(popRep); } else { // this is an inactive species - popRep = new DPointSet(); - tmpIndy1 = (InterfaceDataTypeDouble)pop.get(0); - popRep.addDPoint(new DPoint(tmpIndy1.getDoubleData()[0], tmpIndy1.getDoubleData()[1])); - double d = Math.round(100*((AbstractEAIndividual)tmpIndy1).getFitness(0))/(double)100; - DPointIcon icon = new Chart2DDPointIconText(""+d); - ((Chart2DDPointIconText)icon).setIcon(new Chart2DDPointIconCircle()); - popRep.setIcon(icon); - this.m_Topology.getFunctionArea().addDElement(popRep); + plotInactive((InterfaceDataTypeDouble)pop.get(0)); } } + for (int i = 0; i < this.m_Archive.size(); i++) { + plotInactive((InterfaceDataTypeDouble)m_Archive.get(i)); + } } } + private void plotInactive(InterfaceDataTypeDouble tmpIndy) { + DPointSet popRep; + popRep = new DPointSet(); + popRep.addDPoint(new DPoint(tmpIndy.getDoubleData()[0], tmpIndy.getDoubleData()[1])); + double d = Math.round(100*((AbstractEAIndividual)tmpIndy).getFitness(0))/(double)100; + DPointIcon icon = new Chart2DDPointIconText(""+d); + ((Chart2DDPointIconText)icon).setIcon(new Chart2DDPointIconCircle()); + popRep.setIcon(icon); + this.m_Topology.getFunctionArea().addDElement(popRep); + } + /** * This method is used to cap the mutation rate. * For the global ES mutation, set the mutation rate to not more than cap. @@ -263,17 +278,19 @@ public class ClusterBasedNichingEA implements InterfacePopulationChangedEventLis ArrayList tmpA = pop.m_History; int length = pop.m_History.size(); - if (length <= haltingWindow) return false; - else { + if (length <= haltingWindow) { +// System.out.println("not long enough... gen " + pop.getGeneration()); + return false; + } else { AbstractEAIndividual historic = ((AbstractEAIndividual)pop.m_History.get(length-haltingWindow)); - for (int i = 1; i < haltingWindow; i++) { + for (int i = 1; i < haltingWindow; i++) { // TODO if (historic.getFitness(0) > ((AbstractEAIndividual)pop.m_History.get(length-haltingWindow+i)).getFitness(0)) { - //System.out.println("( " + historic.getFitness(0) + "/" + ((AbstractEAIndividual)pop.m_History.get(length-hw+i)).getFitness(0)); +// System.out.println("( " + historic.getFitness(0) + "/" + ((AbstractEAIndividual)pop.m_History.get(length-haltingWindow+i)).getFitness(0)); return false; } } } - if (this.m_Debug) { + if (TRACE) { double[] a = new double[2]; a[0] = 0; a[1] = 0; Plot plot = new Plot("HaltingWindow", "History", "Fitness", a, a); @@ -287,18 +304,24 @@ public class ClusterBasedNichingEA implements InterfacePopulationChangedEventLis private Population optimizeSpecies(Population species) { m_Optimizer.setPopulation(species); +// m_Optimizer.initByPopulation(species, false); if (m_Optimizer instanceof EvolutionStrategies) { EvolutionStrategies es = (EvolutionStrategies)m_Optimizer; int mu = (int)(muLambdaRatio*species.size()); if (mu < 1) mu = 1; else if (mu >= species.size()) { - if (m_Debug) System.err.println("warning, muLambdaRatio produced mu >= lambda.. reducing to mu=lambda-1"); + if (TRACE) System.err.println("warning, muLambdaRatio produced mu >= lambda.. reducing to mu=lambda-1"); mu = species.size() - 1; } es.setMyu(mu); es.setLambda(species.size()); } + if (TRACE) { + System.out.println("spec size: " + species.size() + ", says its " + species.getPopulationSize()); + System.out.println("Best bef: " + BeanInspector.toString(m_Optimizer.getPopulation().getBestFitness())); + } this.m_Optimizer.optimize(); + if (TRACE) System.out.println("Best aft: " + BeanInspector.toString(m_Optimizer.getPopulation().getBestFitness())); return m_Optimizer.getPopulation(); } @@ -313,7 +336,7 @@ public class ClusterBasedNichingEA implements InterfacePopulationChangedEventLis } // species evolution phase - if (this.m_Debug) { + if (TRACE) { System.out.println(""); System.out.println("Optimizing Generation " + this.m_Undifferentiated.getGeneration()); } @@ -325,40 +348,53 @@ public class ClusterBasedNichingEA implements InterfacePopulationChangedEventLis m_Undifferentiated = optimizeSpecies(m_Undifferentiated); } else { this.m_Undifferentiated.incrGeneration(); + //m_Undifferentiated.incrFunctionCallsby(m_Undifferentiated.size()); // TODO this is not optimal, an evaluation is wasted to keep N steps per gen. } // now the population is of max size - if (this.m_Debug) { + if (TRACE) { System.out.println("-Undiff. size: " + this.m_Undifferentiated.size()); System.out.println("-Number of Demes: " + this.m_Species.size()); + System.out.println("-Funcalls: "+m_Undifferentiated.getFunctionCalls()); } - int reinitCount; Population curSpecies; // optimize the clustered species - for (int i = 0; i < this.m_Species.size(); i++) { - if (this.m_Debug) System.out.println("-Deme " + i + " size: " + ((Population)this.m_Species.get(i)).size()); + for (int i = this.m_Species.size() - 1; i >= 0; i--) { + if (TRACE) System.out.println("-Deme " + i + " size: " + ((Population)this.m_Species.get(i)).size()); curSpecies = ((Population)this.m_Species.get(i)); curSpecies.SetFunctionCalls(0); curSpecies.setPopulationSize(curSpecies.size()); - reinitCount = curSpecies.size()-1; if (isActive(curSpecies)) { if ((this.m_UseHaltingWindow) && (this.testSpeciesForConvergence(curSpecies))) { ///////////////////////////////////////////// Halting Window ///////////////////////////////////////////////// - if (this.m_Debug) System.out.println("--Converged"); // if (this.m_Debug) { // System.out.println("Undiff.Size: " + this.m_Undifferentiated.size() +"/"+this.m_Undifferentiated.getPopulationSize()); // System.out.println("Diff.Size : " + ((Population)this.m_Species.get(i)).size() +"/"+((Population)this.m_Species.get(i)).getPopulationSize()); // } + convergedCnt++; + if (TRACE) System.out.println("--Converged: "+convergedCnt); // memorize the best one.... AbstractEAIndividual best = (AbstractEAIndividual)curSpecies.getBestEAIndividual().getClone(); - // now reset the converged species to inactivity size = 1 - curSpecies.setPopulationSize(1); - curSpecies.clear(); - curSpecies.add(best); + + int reinitCount = -1; + + if (m_UseArchive) { + m_Archive.add(best); + m_Species.remove(i); //REMOVES the converged Species + reinitCount = curSpecies.size(); // add all as new + } else { + // now reset the converged species to inactivity size = 1 + curSpecies.setPopulationSize(1); +// m_Undifferentiated.incrFunctionCallsby(1); // TODO not so good + curSpecies.clear(); + curSpecies.add(best); + reinitCount = curSpecies.size()-1; // add all but one as new + } // reinit the surplus individuals and add these new individuals to undifferentiated - this.m_Undifferentiated.addPopulation(this.initializeIndividuals(reinitCount)); - this.m_Undifferentiated.setPopulationSize(this.m_Undifferentiated.getPopulationSize()+reinitCount); + m_Undifferentiated.addPopulation(this.initializeIndividuals(reinitCount)); + m_Undifferentiated.incrFunctionCallsby(reinitCount); + m_Undifferentiated.setPopulationSize(this.m_Undifferentiated.getPopulationSize()+reinitCount); // if (this.m_Debug) { // System.out.println("Undiff.Size: " + this.m_Undifferentiated.size() +"/"+this.m_Undifferentiated.getPopulationSize()); // System.out.println("Diff.Size : " + ((Population)this.m_Species.get(i)).size() +"/"+((Population)this.m_Species.get(i)).getPopulationSize()); @@ -376,20 +412,33 @@ public class ClusterBasedNichingEA implements InterfacePopulationChangedEventLis } } else { // a single individual species, this element is inactive - if (m_Debug) System.out.println("inactive species not optimized"); + if (TRACE) System.out.println("inactive species not optimized"); +// curSpecies.incrFunctionCallsby(curSpecies.size()); // was todo: not so good } - // This is necessary to keep track to the function calls needed + // This is necessary to keep track of the function calls needed this.m_Undifferentiated.SetFunctionCalls(this.m_Undifferentiated.getFunctionCalls() + curSpecies.getFunctionCalls()); + if (TRACE) System.out.println("### funcalls: "+m_Undifferentiated.getFunctionCalls()); } - if (this.m_Debug) System.out.println("-Number of Demes: " + this.m_Species.size()); + if (TRACE) System.out.println("-Number of Demes: " + this.m_Species.size()); + ////////////////////// + if (!isActive(m_Undifferentiated)) { + if (TRACE) System.out.println("Inactive Undiff-pop, adding " + m_Undifferentiated.size() + " fun calls..."); + m_Undifferentiated.incrFunctionCallsby(m_Undifferentiated.size()); + } + if (this.m_Undifferentiated.getFunctionCalls() % this.m_PopulationSize != 0) { + if (true) System.out.println("### mismatching number of funcalls, inactive species? Correcting by " + (m_PopulationSize - (m_Undifferentiated.getFunctionCalls() % m_PopulationSize))); + if (true) System.out.println("### undiff " + ((isActive(m_Undifferentiated)) ? "active!" : "inactive!")); + m_Undifferentiated.incrFunctionCallsby(m_PopulationSize - (m_Undifferentiated.getFunctionCalls() % m_PopulationSize)); + } else if (TRACE) System.out.println("### undiff active: " + isActive(m_Undifferentiated)); + // possible species differentation and convergence if (this.m_Undifferentiated.getGeneration()%this.m_SpeciesCycle == 0) { - if (this.m_Debug) System.out.println("Species cycle:"); + if (TRACE) System.out.println("Species cycle:"); if (this.m_UseSpeciesDifferentation) { // species differentation phase - if (this.m_Debug) System.out.println("-Sepecies Differentation:"); + if (TRACE) System.out.println("-Sepecies Differentation:"); Population[] ClusterResult; ArrayList newSpecies = new ArrayList(); //cluster the undifferentiated population @@ -397,20 +446,23 @@ public class ClusterBasedNichingEA implements InterfacePopulationChangedEventLis this.m_Undifferentiated = ClusterResult[0]; for (int j = 1; j < ClusterResult.length; j++) { ClusterResult[j].setUseHistory(true); + ClusterResult[j].setGenerationTo(0); ClusterResult[j].m_History = new ArrayList(); newSpecies.add(ClusterResult[j]); } for (int i = 0; i < this.m_Species.size(); i++) { - if (isActive(this.m_Species.get(i))) { + curSpecies = this.m_Species.get(i); + if (isActive(curSpecies)) { // only active populations are clustered - ClusterResult = this.m_CAForSpeciesDifferentation.cluster((Population)this.m_Species.get(i)); + ClusterResult = this.m_CAForSpeciesDifferentation.cluster(curSpecies); this.m_Undifferentiated.addPopulation(ClusterResult[0]); - ClusterResult[0].setUseHistory(true); +// ClusterResult[0].setUseHistory(true); this.m_Undifferentiated.setPopulationSize(this.m_Undifferentiated.getPopulationSize() + ClusterResult[0].size()); for (int j = 1; j < ClusterResult.length; j++) { ClusterResult[j].setPopulationSize(ClusterResult[j].size()); ClusterResult[j].setUseHistory(true); - if (ClusterResult.length > 2) ClusterResult[j].m_History = new ArrayList(); +// if (ClusterResult.length > 2) ClusterResult[j].m_History = new ArrayList(); // mk: why min 3? Ill copy the history from the original pop for any j... + ClusterResult[j].m_History = (ArrayList) curSpecies.m_History.clone(); newSpecies.add(ClusterResult[j]); } } else { @@ -419,7 +471,7 @@ public class ClusterBasedNichingEA implements InterfacePopulationChangedEventLis } } this.m_Species = newSpecies; - if (this.m_Debug) { + if (TRACE) { System.out.println("--Number of species: " + this.m_Species.size()); System.out.println("---Undiff size: " + this.m_Undifferentiated.size()); for (int i = 0; i < this.m_Species.size(); i++) { @@ -431,7 +483,10 @@ public class ClusterBasedNichingEA implements InterfacePopulationChangedEventLis if (this.m_UseSpeciesConvergence) { //species convergence phase - if (this.m_Debug) System.out.println("-Species convergence:"); + if (TRACE) { + System.out.println("-Species convergence:"); + System.out.println("-Funcalls: " + m_Undifferentiated.getFunctionCalls()); + } // first test if loners belong to any species boolean found = false; @@ -442,7 +497,7 @@ public class ClusterBasedNichingEA implements InterfacePopulationChangedEventLis curSpecies = (Population)this.m_Species.get(j); AbstractEAIndividual tmpIndy = (AbstractEAIndividual)this.m_Undifferentiated.get(i); if (this.m_CAForSpeciesConvergence.belongsToSpecies(tmpIndy, curSpecies)) { - if (this.m_Debug) System.out.println("--Adding loner to species "+j); + if (TRACE) System.out.println("--Adding loner to species "+j); found = true; this.m_Undifferentiated.remove(i); if (isActive(curSpecies)) { @@ -452,6 +507,7 @@ public class ClusterBasedNichingEA implements InterfacePopulationChangedEventLis } else { // the species is inactive, reinitialize the individual (MK: why?) this.m_Undifferentiated.add(i, this.initializeIndividuals(1).get(0)); +// m_Undifferentiated.incrFunctionCallsby(1); } } j++; @@ -464,34 +520,36 @@ public class ClusterBasedNichingEA implements InterfacePopulationChangedEventLis for (int j = i+1; j < this.m_Species.size(); j++) { spec2 = (Population)this.m_Species.get(j); if (this.m_CAForSpeciesConvergence.convergingSpecies(spec1, spec2)) { - if (this.m_Debug) System.out.println("--------------------Merging species (" + i +", " +j +") ["+spec1.size()+"/"+spec2.size()+"]"); + if (TRACE) System.out.println("--------------------Merging species (" + i +", " +j +") ["+spec1.size()+"/"+spec2.size()+"]"); +// this.m_CAForSpeciesConvergence.convergingSpecies(spec1, spec2); if (isActive(spec1) && isActive(spec2)) { - if (this.m_Debug) System.out.println("---Active merge"); + if (TRACE) System.out.println("---Active merge"); spec1.addPopulation(spec2); if (spec2.m_History.size() > spec1.m_History.size()) spec1.m_History = spec2.m_History; this.m_Species.remove(j); j--; } else { - if (this.m_Debug) System.out.println("---Inactive merge"); + if (TRACE) System.out.println("---Inactive merge"); // save best in singular species and reinit the rest of the individuals spec1.addPopulation(spec2); this.m_Species.remove(j); j--; AbstractEAIndividual best = (AbstractEAIndividual)spec1.getBestEAIndividual().getClone(); - reinitCount = spec1.size()-1; + int reinitCount = spec1.size()-1; // now reset the converged species to inactivity size = 0 spec1.setPopulationSize(1); spec1.clear(); spec1.add(best); // reinitialized individuals and add them to undifferentiated this.m_Undifferentiated.addPopulation(this.initializeIndividuals(reinitCount)); +// m_Undifferentiated.incrFunctionCallsby(reinitCount); this.m_Undifferentiated.setPopulationSize(this.m_Undifferentiated.getPopulationSize()+reinitCount); } } } } - if (this.m_Debug) System.out.println("--Number of species: " + this.m_Species.size()); + if (TRACE) System.out.println("--Number of species: " + this.m_Species.size()); } // if (this.m_UseClearing) { @@ -509,15 +567,17 @@ public class ClusterBasedNichingEA implements InterfacePopulationChangedEventLis // } } // output the result - if (this.m_Debug) System.out.println("-Number of species: " + this.m_Species.size()); + if (TRACE) System.out.println("-Number of species: " + this.m_Species.size()); + if (TRACE) System.out.println("-Funcalls: " + this.m_Undifferentiated.getFunctionCalls()); + this.m_Population = (Population)this.m_Undifferentiated.clone(); m_Population.setUseHistory(true); - if (this.m_Debug) System.out.println("initing with " + this.m_Undifferentiated.size()); + if (TRACE) System.out.println("initing with " + this.m_Undifferentiated.size()); for (int i = 0; i < this.m_Species.size(); i++) { - if (this.m_Debug) System.out.println("Adding deme " + i + " with size " + ((Population)this.m_Species.get(i)).size()); + if (TRACE) System.out.println("Adding deme " + i + " with size " + ((Population)this.m_Species.get(i)).size()); this.m_Population.addPopulation((Population)this.m_Species.get(i)); } - if (this.m_Debug) System.out.println("Population size: " + this.m_Population.size()); + if (TRACE) System.out.println("Population size: " + this.m_Population.size()); this.firePropertyChangedEvent("NextGenerationPerformed"); } @@ -607,26 +667,32 @@ public class ClusterBasedNichingEA implements InterfacePopulationChangedEventLis return "CBN-EA"; } - /** Assuming that all optimizer will store thier data in a population - * we will allow acess to this population to query to current state - * of the optimizer. - * @return The population of current solutions to a given problem. - */ public Population getPopulation() { this.m_Population = (Population)m_Undifferentiated.clone(); // m_Population.addPopulation(this.m_Undifferentiated); for (int i = 0; i < this.m_Species.size(); i++) this.m_Population.addPopulation((Population)this.m_Species.get(i)); + m_Population.setPopulationSize(m_Population.size()); // set it to true value return this.m_Population; } + public void setPopulation(Population pop){ this.m_Undifferentiated = pop; + pop.setUseHistory(true); } public String populationTipText() { return "Edit the properties of the population used."; } - - /** This method allows you to set/get the switch that toggels the use - * of species differentation. + + public Population getAllSolutions() { + // return inactive species + Population pop = (Population)m_Archive.clone(); + pop.addPopulation(getPopulation()); + pop.setPopulationSize(pop.size()); + return pop; + } + + /** This method allows you to set/get the switch that toggles the use + * of species differentiation. * @return The current status of this flag */ public boolean getApplyDifferentation() { @@ -662,7 +728,7 @@ public class ClusterBasedNichingEA implements InterfacePopulationChangedEventLis this.m_UseHaltingWindow = b; } public String useHaltingWindowTipText() { - return "With a halting window converged species are freezed."; + return "With a halting window converged species are frozen."; } /** This method allows you to set/get the switch that toggels the use @@ -722,6 +788,16 @@ public class ClusterBasedNichingEA implements InterfacePopulationChangedEventLis return "The cluster algorithm on which the species convergence is based."; } + public void setUseArchive(boolean v) { + m_UseArchive = v; + } + public boolean isUseArchive() { + return m_UseArchive; + } + public String useArchiveTipText() { + return "Toggle usage of an archive where converged species are savend and the individuals reinitialized."; + } + /** Determines how often species differentation/convergence is performed. * @return This number gives the generations when specification is performed. */ diff --git a/src/javaeva/server/go/strategies/ClusteringHillClimbing.java b/src/javaeva/server/go/strategies/ClusteringHillClimbing.java new file mode 100644 index 00000000..ceb92f77 --- /dev/null +++ b/src/javaeva/server/go/strategies/ClusteringHillClimbing.java @@ -0,0 +1,324 @@ +package javaeva.server.go.strategies; + +import java.io.Serializable; + +import javaeva.gui.GenericObjectEditor; +import javaeva.server.go.InterfacePopulationChangedEventListener; +import javaeva.server.go.operators.mutation.MutateESFixedStepSize; +import javaeva.server.go.operators.postprocess.PostProcess; +import javaeva.server.go.populations.Population; +import javaeva.server.go.problems.AbstractOptimizationProblem; +import javaeva.server.go.problems.F1Problem; +import javaeva.server.go.problems.InterfaceOptimizationProblem; +import javaeva.tools.Pair; + +public class ClusteringHillClimbing implements InterfacePopulationChangedEventListener, InterfaceOptimizer, Serializable { + transient private InterfacePopulationChangedEventListener m_Listener; + transient private String m_Identifier = ""; + private Population m_Population = new Population(); + private transient Population archive = new Population(); + private InterfaceOptimizationProblem m_Problem = new F1Problem(); + private int hcEvalCycle = 1000; + private int initialPopSize = 200; + private int loopCnt = 0; +// private int baseEvalCnt = 0; + private int notifyGuiEvery = 50; + private double sigma = 0.01; + private double minImprovement = 0.000001; + private double reinitForStepSize = 0.000001; + private double initialStepSize = 0.1; + private MutateESFixedStepSize mutator = new MutateESFixedStepSize(0.1); + + public ClusteringHillClimbing() { + hideHideable(); + } + + public ClusteringHillClimbing(ClusteringHillClimbing other) { + hideHideable(); + m_Population = (Population)other.m_Population.clone(); + m_Problem = (InterfaceOptimizationProblem)other.m_Problem.clone(); + hcEvalCycle = other.hcEvalCycle; + initialPopSize = other.initialPopSize; + loopCnt = 0; + } + + public Object clone() { + return (Object) new ClusteringHillClimbing(this); + } + + /** + * Hide the population. + */ + public void hideHideable() { + GenericObjectEditor.setHideProperty(getClass(), "population", true); + } + + public void SetIdentifier(String name) { + this.m_Identifier = name; + } + public String getIdentifier() { + return this.m_Identifier; + } + + /** This method will set the problem that is to be optimized + * @param problem + */ + public void SetProblem (InterfaceOptimizationProblem problem) { + this.m_Problem = problem; + } + public InterfaceOptimizationProblem getProblem () { + return this.m_Problem; + } + + public void addPopulationChangedEventListener(InterfacePopulationChangedEventListener ea) { + this.m_Listener = ea; + } + + public void init() { + loopCnt = 0; + mutator = new MutateESFixedStepSize(initialStepSize); + archive = new Population(); + hideHideable(); + m_Population.setPopulationSize(initialPopSize); + this.m_Problem.initPopulation(this.m_Population); + m_Population.addPopulationChangedEventListener(null); + this.m_Problem.evaluate(this.m_Population); + this.firePropertyChangedEvent("NextGenerationPerformed"); + } + + /** This method will init the optimizer with a given population + * @param pop The initial population + * @param reset If true the population is reset. + */ + public void initByPopulation(Population pop, boolean reset) { + loopCnt = 0; + this.m_Population = (Population)pop.clone(); + m_Population.addPopulationChangedEventListener(null); + if (reset) this.m_Population.init(); + this.m_Problem.evaluate(this.m_Population); + this.firePropertyChangedEvent("NextGenerationPerformed"); + } + + /** Something has changed + */ + protected void firePropertyChangedEvent (String name) { + if (this.m_Listener != null) this.m_Listener.registerPopulationStateChanged(this, name); + } + + public void optimize() { + double improvement; + + loopCnt++; + m_Population.addPopulationChangedEventListener(this); + m_Population.setNotifyEvalInterval(notifyGuiEvery); + Pair popD = PostProcess.clusterHC(m_Population, (AbstractOptimizationProblem)m_Problem, sigma, hcEvalCycle - (m_Population.getFunctionCalls() % hcEvalCycle), 0.5, mutator); + improvement = popD.tail(); + + popD.head().setGenerationTo(m_Population.getGeneration()+1); + m_Population = popD.head(); + + if (improvement < minImprovement) { + System.out.println("improvement below " + minImprovement); + if (mutator.getSigma() < reinitForStepSize) { // reinit! + System.out.println("REINIT!!"); + // store results + mutator.setSigma(initialStepSize); + archive.SetFunctionCalls(m_Population.getFunctionCalls()); + archive.addPopulation(m_Population); + + Population tmpPop = new Population(); + tmpPop.setSameParams(m_Population); + tmpPop.addPopulationChangedEventListener(null); + tmpPop.setPopulationSize(initialPopSize); + this.m_Problem.initPopulation(tmpPop); + this.m_Problem.evaluate(tmpPop); + + // reset population while keeping function calls etc. + m_Population.clear(); + m_Population.addPopulation(tmpPop); + m_Population.incrFunctionCallsby(tmpPop.size()); + + } else { // decrease step size + mutator.setSigma(mutator.getSigma()/2); + System.out.println("halfed sigma to " + mutator.getSigma()); + } + } +// System.out.println("funcalls: " + evalCnt); +// this.firePropertyChangedEvent("NextGenerationPerformed"); + + } + + public void registerPopulationStateChanged(Object source, String name) { + // The events of the interim hill climbing population will be caught here + if (name.compareTo(Population.funCallIntervalReached) == 0) { +// if ((((Population)source).size() % 50) > 0) { +// System.out.println("bla"); +// } + // set funcalls to real value + m_Population.SetFunctionCalls(((Population)source).getFunctionCalls()); +// System.out.println("FunCallIntervalReached at " + (((Population)source).getFunctionCalls())); + this.firePropertyChangedEvent("NextGenerationPerformed"); + } + // do not react to NextGenerationPerformed + //else System.err.println("ERROR, event was " + name); + + } + + /** Assuming that all optimizer will store thier data in a population + * we will allow acess to this population to query to current state + * of the optimizer. + * @return The population of current solutions to a given problem. + */ + public Population getPopulation() { + return this.m_Population; + } + public void setPopulation(Population pop){ + this.m_Population = pop; + } + public String populationTipText() { + return "Change the number of starting individuals stored (Cluster-HC)."; + } + + public Population getAllSolutions() { + Population tmp = new Population(); + tmp.addPopulation(archive); + tmp.addPopulation(m_Population); +// tmp = PostProcessInterim.clusterBest(tmp, sigma, 0, PostProcessInterim.KEEP_LONERS, PostProcessInterim.BEST_ONLY); + return tmp; + } + /** This method will return a string describing all properties of the optimizer + * and the applied methods. + * @return A descriptive string + */ + public String getStringRepresentation() { + StringBuffer sbuf = new StringBuffer("Clustering Hill Climbing"); + sbuf.append(", initial pop size: "); + sbuf.append(getPopulation().getPopulationSize()); + sbuf.append("Optimization Problem: "); + sbuf.append(this.m_Problem.getStringRepresentationForProblem(this)); + sbuf.append(this.m_Population.getStringRepresentation()); + return sbuf.toString(); + } + + public void freeWilly() {} + + public String getName() { + return "Cluster-HC"; + } + + /** + * @return the hcEvalCycle + */ + public int getHcEvalCycle() { + return hcEvalCycle; + } + + /** + * @param hcEvalCycle the hcEvalCycle to set + */ + public void setHcEvalCycle(int hcEvalCycle) { + this.hcEvalCycle = hcEvalCycle; + } + + /** + * @return the initialPopSize + */ + public int getInitialPopSize() { + return initialPopSize; + } + + /** + * @param initialPopSize the initialPopSize to set + */ + public void setInitialPopSize(int initialPopSize) { + this.initialPopSize = initialPopSize; + } + + /** + * @return the sigma + */ + public double getSigma() { + return sigma; + } + + /** + * @param sigma the sigma to set + */ + public void setSigma(double sigma) { + this.sigma = sigma; + } + + public String sigmaTipText() { + return "Defines the sigma distance parameter for density based clustering."; + } + + /** + * @return the notifyGuiEvery + */ + public int getNotifyGuiEvery() { + return notifyGuiEvery; + } + + /** + * @param notifyGuiEvery the notifyGuiEvery to set + */ + public void setNotifyGuiEvery(int notifyGuiEvery) { + this.notifyGuiEvery = notifyGuiEvery; + } + + /** + * @return the minImprovement + */ + public double getMinImprovement() { + return minImprovement; + } + + /** + * @param minImprovement the minImprovement to set + */ + public void setMinImprovement(double minImprovement) { + this.minImprovement = minImprovement; + } + + /** + * @return the reinitForStepSize + */ + public double getReinitForStepSize() { + return reinitForStepSize; + } + + /** + * @param reinitForStepSize the reinitForStepSize to set + */ + public void setReinitForStepSize(double reinitForStepSize) { + this.reinitForStepSize = reinitForStepSize; + } + + /** + * @return the initialStepSize + */ + public double getInitialStepSize() { + return initialStepSize; + } + + /** + * @param initialStepSize the initialStepSize to set + */ + public void setInitialStepSize(double initialStepSize) { + this.initialStepSize = initialStepSize; + } + +// /** +// * @return the mutator +// */ +// public InterfaceMutation getMutator() { +// return mutator; +// } +// +// /** +// * @param mutator the mutator to set +// */ +// public void setMutator(InterfaceMutation mutator) { +// this.mutator = mutator; +// } +} diff --git a/src/javaeva/server/go/strategies/DifferentialEvolution.java b/src/javaeva/server/go/strategies/DifferentialEvolution.java index f01de85c..c3597c72 100644 --- a/src/javaeva/server/go/strategies/DifferentialEvolution.java +++ b/src/javaeva/server/go/strategies/DifferentialEvolution.java @@ -476,6 +476,10 @@ public class DifferentialEvolution implements InterfaceOptimizer, java.io.Serial public String populationTipText() { return "Edit the properties of the population used."; } + + public Population getAllSolutions() { + return getPopulation(); + } /** F is a real and constant factor which controls the amplification of the differential variation * @param f diff --git a/src/javaeva/server/go/strategies/EvolutionStrategies.java b/src/javaeva/server/go/strategies/EvolutionStrategies.java index a4943193..0df662e2 100644 --- a/src/javaeva/server/go/strategies/EvolutionStrategies.java +++ b/src/javaeva/server/go/strategies/EvolutionStrategies.java @@ -358,7 +358,10 @@ public class EvolutionStrategies implements InterfaceOptimizer, java.io.Serializ public String populationTipText() { return "Edit the properties of the population used."; } - + + public Population getAllSolutions() { + return getPopulation(); + } // /** This method will set the normation method that is to be used. // * @param normation // */ diff --git a/src/javaeva/server/go/strategies/EvolutionaryProgramming.java b/src/javaeva/server/go/strategies/EvolutionaryProgramming.java index c1f27b47..235a0573 100644 --- a/src/javaeva/server/go/strategies/EvolutionaryProgramming.java +++ b/src/javaeva/server/go/strategies/EvolutionaryProgramming.java @@ -198,6 +198,10 @@ public class EvolutionaryProgramming implements InterfaceOptimizer, java.io.Seri public String populationTipText() { return "Edit the properties of the population used."; } + + public Population getAllSolutions() { + return getPopulation(); + } /** Choose a method for selecting the reduced population. * @param selection */ diff --git a/src/javaeva/server/go/strategies/FloodAlgorithm.java b/src/javaeva/server/go/strategies/FloodAlgorithm.java index 508582fd..ef5ff9e0 100644 --- a/src/javaeva/server/go/strategies/FloodAlgorithm.java +++ b/src/javaeva/server/go/strategies/FloodAlgorithm.java @@ -233,6 +233,10 @@ public class FloodAlgorithm implements InterfaceOptimizer, java.io.Serializable return "Change the number of best individuals stored (MS-FA)."; } + + public Population getAllSolutions() { + return getPopulation(); + } /** This methods allow you to set/get the temperatur of the flood * algorithm procedure * @return The initial flood level. diff --git a/src/javaeva/server/go/strategies/GeneticAlgorithm.java b/src/javaeva/server/go/strategies/GeneticAlgorithm.java index e5d36456..a32983ef 100644 --- a/src/javaeva/server/go/strategies/GeneticAlgorithm.java +++ b/src/javaeva/server/go/strategies/GeneticAlgorithm.java @@ -239,6 +239,9 @@ public class GeneticAlgorithm implements InterfaceOptimizer, java.io.Serializabl return "Edit the properties of the population used."; } + public Population getAllSolutions() { + return getPopulation(); + } // /** This method will set the normation method that is to be used. // * @param normation // */ diff --git a/src/javaeva/server/go/strategies/GradientDescentAlgorithm.java b/src/javaeva/server/go/strategies/GradientDescentAlgorithm.java index bf2d5896..6c1bf2ac 100644 --- a/src/javaeva/server/go/strategies/GradientDescentAlgorithm.java +++ b/src/javaeva/server/go/strategies/GradientDescentAlgorithm.java @@ -256,6 +256,10 @@ public class GradientDescentAlgorithm implements InterfaceOptimizer, java.io.Ser public Population getPopulation() { return this.m_Population; } + + public Population getAllSolutions() { + return getPopulation(); + } public void setPopulation(Population pop) { Hashtable newindyhash = new Hashtable(); diff --git a/src/javaeva/server/go/strategies/HillClimbing.java b/src/javaeva/server/go/strategies/HillClimbing.java index a346bbb6..021325e7 100644 --- a/src/javaeva/server/go/strategies/HillClimbing.java +++ b/src/javaeva/server/go/strategies/HillClimbing.java @@ -2,7 +2,7 @@ package javaeva.server.go.strategies; import javaeva.server.go.InterfacePopulationChangedEventListener; import javaeva.server.go.individuals.AbstractEAIndividual; -import javaeva.server.go.individuals.GAIndividualBinaryData; +import javaeva.server.go.operators.mutation.InterfaceMutation; import javaeva.server.go.populations.Population; import javaeva.server.go.problems.B1Problem; import javaeva.server.go.problems.InterfaceOptimizationProblem; @@ -22,10 +22,11 @@ import javaeva.server.go.problems.InterfaceOptimizationProblem; public class HillClimbing implements InterfaceOptimizer, java.io.Serializable { // These variables are necessary for the simple testcase private InterfaceOptimizationProblem m_Problem = new B1Problem(); + private InterfaceMutation mutator = null; // private int m_MultiRuns = 100; // private int m_FitnessCalls = 100; // private int m_FitnessCallsNeeded = 0; - GAIndividualBinaryData m_Best, m_Test; +// GAIndividualBinaryData m_Best, m_Test; // These variables are necessary for the more complex LectureGUI enviroment transient private String m_Identifier = ""; @@ -70,12 +71,15 @@ public class HillClimbing implements InterfaceOptimizer, java.io.Serializable { public void optimize() { AbstractEAIndividual indy; Population original = (Population)this.m_Population.clone(); - + double tmpD; + InterfaceMutation tmpMut; + for (int i = 0; i < this.m_Population.size(); i++) { indy = ((AbstractEAIndividual) this.m_Population.get(i)); - double tmpD = indy.getMutationProbability(); + tmpD = indy.getMutationProbability(); indy.setMutationProbability(1.0); - indy.mutate(); + if (mutator == null) indy.mutate(); + else mutator.mutate(indy); indy.setMutationProbability(tmpD); } this.m_Problem.evaluate(this.m_Population); @@ -103,7 +107,20 @@ public class HillClimbing implements InterfaceOptimizer, java.io.Serializable { this.firePropertyChangedEvent("NextGenerationPerformed"); } - + public InterfaceMutation getMutationOperator() { + return mutator; + } + + /** + * Allows to set a desired mutator by hand, which is used instead of the one in the individuals. + * Set it to null to use the one in the individuals, which is the default. + * + * @param mute + */ + public void SetMutationOperator(InterfaceMutation mute) { + mutator = mute; + } + /** This method will set the problem that is to be optimized * @param problem */ @@ -200,7 +217,7 @@ public class HillClimbing implements InterfaceOptimizer, java.io.Serializable { * @return description */ public String globalInfo() { - return "The Hill CLimber uses the default EA mutation and init operators. If the population size is bigger than one a multi-start Hill Climber is performed."; + return "The Hill Climber uses the default EA mutation and initializing operators. If the population size is bigger than one a multi-start Hill Climber is performed."; } /** This method will return a naming String * @return The name of the algorithm @@ -208,17 +225,16 @@ public class HillClimbing implements InterfaceOptimizer, java.io.Serializable { public String getName() { return "MS-HC"; } - /** Assuming that all optimizer will store thier data in a population - * we will allow acess to this population to query to current state - * of the optimizer. - * @return The population of current solutions to a given problem. - */ public Population getPopulation() { return this.m_Population; } public void setPopulation(Population pop){ this.m_Population = pop; } + + public Population getAllSolutions() { + return getPopulation(); + } public String populationTipText() { return "Change the number of best individuals stored (MS-HC)."; } diff --git a/src/javaeva/server/go/strategies/InterfaceOptimizer.java b/src/javaeva/server/go/strategies/InterfaceOptimizer.java index b4331f93..52c9c639 100644 --- a/src/javaeva/server/go/strategies/InterfaceOptimizer.java +++ b/src/javaeva/server/go/strategies/InterfaceOptimizer.java @@ -1,6 +1,9 @@ package javaeva.server.go.strategies; +import java.util.List; + import javaeva.server.go.InterfacePopulationChangedEventListener; +import javaeva.server.go.individuals.AbstractEAIndividual; import javaeva.server.go.populations.Population; import javaeva.server.go.problems.InterfaceOptimizationProblem; @@ -49,16 +52,24 @@ public interface InterfaceOptimizer { */ public void optimize(); - /** Assuming that all optimizer will store thier data in a population - * we will allow acess to this population to query to current state + /** Assuming that all optimizer will store their data in a population + * we will allow access to this population to query to current state * of the optimizer. * @return The population of current solutions to a given problem. */ public Population getPopulation(); public void setPopulation(Population pop); - - /** This method allows you to set an identifier for the algorithm - * @param name The indenifier + + /** + * Return all found solutions (local optima) if they are not contained in the last population. + * + * @return A population of found solutions or null if they are contained in the population. + */ + public Population getAllSolutions(); + + /** + * This method allows you to set an identifier for the algorithm + * @param name The identifier */ public void SetIdentifier(String name); public String getIdentifier(); diff --git a/src/javaeva/server/go/strategies/IslandModelEA.java b/src/javaeva/server/go/strategies/IslandModelEA.java index 717e50f3..7a53e30c 100644 --- a/src/javaeva/server/go/strategies/IslandModelEA.java +++ b/src/javaeva/server/go/strategies/IslandModelEA.java @@ -517,6 +517,10 @@ public class IslandModelEA implements InterfacePopulationChangedEventListener, I public String populationTipText() { return "(Defunct)"; } + + public Population getAllSolutions() { + return getPopulation(); + } /** This method allows you to set the number of processors in local mode * @param n Number of processors. diff --git a/src/javaeva/server/go/strategies/MemeticAlgorithm.java b/src/javaeva/server/go/strategies/MemeticAlgorithm.java index 233546b8..ed79088e 100644 --- a/src/javaeva/server/go/strategies/MemeticAlgorithm.java +++ b/src/javaeva/server/go/strategies/MemeticAlgorithm.java @@ -235,7 +235,10 @@ public class MemeticAlgorithm implements InterfaceOptimizer, java.io.Serializabl public String populationTipText() { return "Edit the properties of the population used."; } - + + public Population getAllSolutions() { + return getPopulation(); + } /** Choose the global optimization strategy to use * @param m_GlobalOptimizer */ diff --git a/src/javaeva/server/go/strategies/MonteCarloSearch.java b/src/javaeva/server/go/strategies/MonteCarloSearch.java index 88f775f4..0f25e09f 100644 --- a/src/javaeva/server/go/strategies/MonteCarloSearch.java +++ b/src/javaeva/server/go/strategies/MonteCarloSearch.java @@ -199,4 +199,8 @@ public class MonteCarloSearch implements InterfaceOptimizer, java.io.Serializabl public String populationTipText() { return "Change the number of best individuals stored."; } + + public Population getAllSolutions() { + return getPopulation(); + } } \ No newline at end of file diff --git a/src/javaeva/server/go/strategies/MultiObjectiveEA.java b/src/javaeva/server/go/strategies/MultiObjectiveEA.java index 243d084d..20598f39 100644 --- a/src/javaeva/server/go/strategies/MultiObjectiveEA.java +++ b/src/javaeva/server/go/strategies/MultiObjectiveEA.java @@ -226,6 +226,10 @@ public class MultiObjectiveEA implements InterfaceOptimizer, java.io.Serializabl public String populationTipText() { return "Edit the properties of the Population used."; } + + public Population getAllSolutions() { + return getPopulation(); + } /** This method allows you to set/get the optimizing technique to use. * @return The current optimizing method diff --git a/src/javaeva/server/go/strategies/MultiObjectiveMemeticAlgorithmII.java b/src/javaeva/server/go/strategies/MultiObjectiveMemeticAlgorithmII.java index 943663fe..018071a6 100644 --- a/src/javaeva/server/go/strategies/MultiObjectiveMemeticAlgorithmII.java +++ b/src/javaeva/server/go/strategies/MultiObjectiveMemeticAlgorithmII.java @@ -162,7 +162,10 @@ public class MultiObjectiveMemeticAlgorithmII implements InterfaceOptimizer, jav public String populationTipText() { return "Edit the properties of the Population used."; } - + + public Population getAllSolutions() { + return getPopulation(); + } /** This method allows you to set/get the optimizing technique to use. * @return The current optimizing method */ diff --git a/src/javaeva/server/go/strategies/ParticleFilterOptimization.java b/src/javaeva/server/go/strategies/ParticleFilterOptimization.java index cbe494df..06681cd4 100644 --- a/src/javaeva/server/go/strategies/ParticleFilterOptimization.java +++ b/src/javaeva/server/go/strategies/ParticleFilterOptimization.java @@ -257,7 +257,10 @@ public class ParticleFilterOptimization implements InterfaceOptimizer, java.io.S public String populationTipText() { return "Edit the properties of the population used."; } - + + public Population getAllSolutions() { + return getPopulation(); + } /** This method will set the selection method that is to be used * @param selection */ diff --git a/src/javaeva/server/go/strategies/ParticleSwarmOptimization.java b/src/javaeva/server/go/strategies/ParticleSwarmOptimization.java index 9aa2d9d2..68e7dfc7 100644 --- a/src/javaeva/server/go/strategies/ParticleSwarmOptimization.java +++ b/src/javaeva/server/go/strategies/ParticleSwarmOptimization.java @@ -7,6 +7,7 @@ import wsi.ra.chart2d.DPoint; import wsi.ra.chart2d.DPointSet; import wsi.ra.math.Jama.Matrix; +import javaeva.gui.BeanInspector; import javaeva.gui.GenericObjectEditor; import javaeva.gui.TopoPlot; import javaeva.server.go.InterfacePopulationChangedEventListener; @@ -97,6 +98,7 @@ public class ParticleSwarmOptimization implements InterfaceOptimizer, java.io.Se private int emaPeriods = 0; // for debugging only + transient private static boolean TRACE = false; transient protected boolean m_Show = false; transient protected javaeva.gui.Plot m_Plot; @@ -124,7 +126,7 @@ public class ParticleSwarmOptimization implements InterfaceOptimizer, java.io.Se this.m_SpeedLimit = a.m_SpeedLimit; this.m_Phi1 = a.m_Phi1; this.m_Phi2 = a.m_Phi2; - this.m_InertnessOrChi = a.m_InertnessOrChi; + this.m_InertnessOrChi = a.m_InertnessOrChi; this.m_TopologyRange = a.m_TopologyRange; //this.setCheckSpeedLimit(a.isCheckSpeedLimit()); } @@ -430,6 +432,9 @@ public class ParticleSwarmOptimization implements InterfaceOptimizer, java.io.Se neighbourPos = ((InterfaceESIndividual)neighbourIndy).getDGenotype(); } + if (neighbourFit == null || attractorFit == null) { + System.err.println("error!"); + } // if (fit[0] >= tmpFit[0]) { // now multi-obj. if (AbstractEAIndividual.isDominatingFitness(neighbourFit, attractorFit)) { // if the remembered fitness dominates the given one, overwrite the given one // replace best fitness and position with current best @@ -1250,6 +1255,15 @@ public class ParticleSwarmOptimization implements InterfaceOptimizer, java.io.Se * */ protected void startOptimize() { + if (TRACE) { + for (int i=0; i mems = swarm.collectMem(); + for (Iterator iterator = mems.iterator(); iterator.hasNext();) { + TribesPosition tp = iterator.next(); + all.add(positionToExplorer(tp)); + } + //all.addPopulation(pop); + return all; + } + + protected TribesExplorer positionToExplorer(TribesPosition pos) { + TribesExplorer tmp = (TribesExplorer)population.get(0); + if (tmp == null) System.err.println("Error in Tribes::positionToExplorer!"); + TribesExplorer indy = tmp.clone(); + indy.clearPosVel(); + indy.SetDoubleDataLamarkian(pos.getPos()); + indy.SetFitness(pos.getFitness()); + return indy; + } + + /** This method allows you to add the LectureGUI as listener to the Optimizer * @param ea */ public void addPopulationChangedEventListener(InterfacePopulationChangedEventListener ea) { diff --git a/src/javaeva/server/go/strategies/WingedMultiObjectiveEA.java b/src/javaeva/server/go/strategies/WingedMultiObjectiveEA.java index 7def2588..abdf37e7 100644 --- a/src/javaeva/server/go/strategies/WingedMultiObjectiveEA.java +++ b/src/javaeva/server/go/strategies/WingedMultiObjectiveEA.java @@ -14,12 +14,12 @@ import javaeva.server.go.problems.FM0Problem; import javaeva.server.go.problems.InterfaceOptimizationProblem; import javaeva.gui.PropertyDoubleArray; -/** The winged MOEA was a nice idea, which didn't really worked out. +/** The winged MOEA was a nice idea, which didn't really work out. * Here a standard MOEA is assisted by n additional local searchers, each * optimizing just one objective. The idea was that these local optimizers * would span the search space and would allow the MOEA to converge faster. * But in the end the performance of this algorithm strongly depends on the - * optimizaiton problem. + * optimization problem. * Created by IntelliJ IDEA. * User: streiche * Date: 16.02.2005 @@ -271,8 +271,8 @@ public class WingedMultiObjectiveEA implements InterfaceOptimizer, java.io.Seria return "EMO-LS"; } - /** Assuming that all optimizer will store thier data in a population - * we will allow acess to this population to query to current state + /** Assuming that all optimizer will store their data in a population + * we will allow access to this population to query to current state * of the optimizer. * @return The population of current solutions to a given problem. */ @@ -285,7 +285,10 @@ public class WingedMultiObjectiveEA implements InterfaceOptimizer, java.io.Seria public String populationTipText() { return "(Defunct)"; } - + + public Population getAllSolutions() { + return getPopulation(); + } /** This method allows you to set/get the optimizing technique to use. * @return The current optimizing method */ diff --git a/src/javaeva/server/go/strategies/tribes/TribesExplorer.java b/src/javaeva/server/go/strategies/tribes/TribesExplorer.java index 3a85faed..f311d5e4 100644 --- a/src/javaeva/server/go/strategies/tribes/TribesExplorer.java +++ b/src/javaeva/server/go/strategies/tribes/TribesExplorer.java @@ -121,6 +121,13 @@ public class TribesExplorer extends AbstractEAIndividual implements InterfaceDat return new TribesExplorer(this); } + /** + * Resets all positions and velocity. + */ + public void clearPosVel() { + initPositions(position.getMaxDimension()); + } + // // public int generateExplorer(TribesParam pb, // TribesSwarm swarm, TribesPosition center, double radius, diff --git a/src/javaeva/server/go/strategies/tribes/TribesSwarm.java b/src/javaeva/server/go/strategies/tribes/TribesSwarm.java index 3341195a..daeda1f5 100644 --- a/src/javaeva/server/go/strategies/tribes/TribesSwarm.java +++ b/src/javaeva/server/go/strategies/tribes/TribesSwarm.java @@ -1,5 +1,8 @@ package javaeva.server.go.strategies.tribes; +import java.util.ArrayList; +import java.util.List; + import javaeva.server.go.populations.Population; import javaeva.server.go.problems.InterfaceOptimizationProblem; import javaeva.server.go.strategies.Tribes; @@ -195,6 +198,21 @@ public class TribesSwarm implements java.io.Serializable{ return found; } + /** + * Returns al memory particles as double vectors. + * @return + */ + public List collectMem() { + ArrayList bestList = new ArrayList(); + + for (int n = 0; n < tribeNb; n++) { + for (int m = 0; m < tribes[n].memoryNb; m++) { + bestList.add(tribes[n].memory[m].getPos()); + } + } + return bestList; + } + /** * This searches for the best memory, and also sets the bestMem member of the swarm. * diff --git a/src/javaeva/server/modules/AbstractGOParameters.java b/src/javaeva/server/modules/AbstractGOParameters.java new file mode 100644 index 00000000..170bb7dc --- /dev/null +++ b/src/javaeva/server/modules/AbstractGOParameters.java @@ -0,0 +1,187 @@ +package javaeva.server.modules; + +import java.io.Serializable; + +import javaeva.gui.BeanInspector; +import javaeva.server.go.InterfaceGOParameters; +import javaeva.server.go.InterfacePopulationChangedEventListener; +import javaeva.server.go.InterfaceTerminator; +import javaeva.server.go.operators.postprocess.InterfacePostProcessParams; +import javaeva.server.go.operators.postprocess.PostProcessParams; +import javaeva.server.go.problems.InterfaceOptimizationProblem; +import javaeva.server.go.strategies.InterfaceOptimizer; + +public abstract class AbstractGOParameters implements InterfaceGOParameters, Serializable { + public static boolean TRACE = false; + protected long m_Seed = (long)100.0; + + // Opt. Algorithms and Parameters + protected InterfaceOptimizer m_Optimizer; + protected InterfaceOptimizationProblem m_Problem ; + protected InterfaceTerminator m_Terminator; + protected InterfacePostProcessParams m_PostProc = new PostProcessParams(false); +// protected int hcPostProcessSteps = 5000; + transient protected InterfacePopulationChangedEventListener m_Listener; +// private boolean postProcess = false; +// protected double postProcessClusterSigma = 0.05; + + protected AbstractGOParameters() { + } + + protected AbstractGOParameters(AbstractGOParameters Source) { + this.m_Optimizer = Source.m_Optimizer; + this.m_Problem = Source.m_Problem; + this.m_Terminator = Source.m_Terminator; + this.m_Optimizer.SetProblem(this.m_Problem); + this.m_Seed = Source.m_Seed; + this.m_PostProc = Source.m_PostProc; +// this.hcPostProcessSteps = Source.hcPostProcessSteps; + } + + protected AbstractGOParameters(InterfaceOptimizer opt, InterfaceOptimizationProblem prob, InterfaceTerminator term) { + m_Optimizer = opt; + m_Problem = prob; + m_Terminator = term; + m_PostProc = new PostProcessParams(false); + opt.SetProblem(prob); + } + + /** This method allows you to add the LectureGUI as listener to the Optimizer + * @param ea + */ + public void addPopulationChangedEventListener(InterfacePopulationChangedEventListener ea) { + this.m_Listener = ea; + if (this.m_Optimizer != null) this.m_Optimizer.addPopulationChangedEventListener(this.m_Listener); + } + public String toString() { +// String ret = "\r\nParameters:"+this.m_Problem.getStringRepresentationForProblem(this.m_Optimizer)+"\n"+this.m_Optimizer.getStringRepresentation(); +// return ret; + StringBuffer sb = new StringBuffer(getName()); + sb.append("\n"); + sb.append("seed="); + sb.append(m_Seed); + sb.append("\nProblem: "); + sb.append(BeanInspector.toString(m_Problem)); + sb.append("\nOptimizer: "); + sb.append(BeanInspector.toString(m_Optimizer)); + sb.append("\nTerminator: "); + sb.append(BeanInspector.toString(m_Terminator)); + sb.append("\n"); +// sb.append(m_N) + return sb.toString(); + } + + public void setOptimizer(InterfaceOptimizer optimizer) { + this.m_Optimizer = optimizer; + this.m_Optimizer.SetProblem(this.m_Problem); + if (this.m_Listener != null) this.m_Optimizer.addPopulationChangedEventListener(this.m_Listener); + } + public InterfaceOptimizer getOptimizer() { + return this.m_Optimizer; + } + public String optimizerTipText() { + return "Choose an optimizing strategy."; + } + + public String getName() { + return "Optimization parameters"; + } + +// public String postProcessStepsTipText() { +// return "The number of HC post processing steps in fitness evaluations."; +// } +// public int getPostProcessSteps() { +// return hcPostProcessSteps; +// } +// public void setPostProcessSteps(int ppSteps) { +// hcPostProcessSteps = ppSteps; +// } + + /** + * This method will set the problem that is to be optimized. + * @param problem + */ + public void setProblem (InterfaceOptimizationProblem problem) { + this.m_Problem = problem; + this.m_Optimizer.SetProblem(this.m_Problem); + } + public InterfaceOptimizationProblem getProblem() { + return this.m_Problem; + } + public String problemTipText() { + return "Choose the problem that is to optimize and the EA individual parameters."; + } + + /** This methods allow you to set and get the Seed for the Random Number Generator. + * @param x Long seed. + */ + public void setSeed(long x) { + m_Seed = x; + } + public long getSeed() { + return m_Seed; + } + public String seedTipText() { + return "Random number seed, set to zero to use current system time."; + } + + /** This method allows you to choose a termination criteria for the + * evolutionary algorithm. + * @param term The new terminator + */ + public void setTerminator(InterfaceTerminator term) { + this.m_Terminator = term; + } + public InterfaceTerminator getTerminator() { + return this.m_Terminator; + } + public String terminatorTipText() { + return "Choose a termination criterion."; + } + +// /** +// * @return the postProcess +// */ +// public boolean isPostProcess() { +// return postProcess; +// } +// /** +// * @param postProcess the postProcess to set +// */ +// public void setPostProcess(boolean postProcess) { +// this.postProcess = postProcess; +// GenericObjectEditor.setShowProperty(this.getClass(), "postProcessSteps", postProcess); +// GenericObjectEditor.setShowProperty(this.getClass(), "postProcessClusterSigma", postProcess); +// } +// public String postProcessTipText() { +// return "Toggle post processing of the solutions."; +// } +// /** +// * @return the postProcessClusterSigma +// */ +// public double getPostProcessClusterSigma() { +// return postProcessClusterSigma; +// } +// /** +// * @param postProcessClusterSigma the postProcessClusterSigma to set +// */ +// public void setPostProcessClusterSigma(double postProcessClusterSigma) { +// this.postProcessClusterSigma = postProcessClusterSigma; +// } +// public String postProcessClusterSigmaTipText() { +// return "Set the sigma parameter for clustering during post processing. Set to zero for no clustering."; +// } + + public InterfacePostProcessParams getPostProcessParams() { + return m_PostProc; + } + public void setPostProcessParams(InterfacePostProcessParams ppp) { + m_PostProc = ppp; + } + public String postProcessParamsTipText() { + return "Parameters for the post processing step"; + } + public void setDoPostProcessing(boolean doPP){ + m_PostProc.setDoPostProcessing(doPP); + } +} diff --git a/src/javaeva/server/modules/DEParameters.java b/src/javaeva/server/modules/DEParameters.java index cc73fba3..47a0c62c 100644 --- a/src/javaeva/server/modules/DEParameters.java +++ b/src/javaeva/server/modules/DEParameters.java @@ -24,19 +24,9 @@ import java.io.Serializable; * Time: 13:49:09 * To change this template use File | Settings | File Templates. */ -public class DEParameters implements InterfaceGOParameters, Serializable { +public class DEParameters extends AbstractGOParameters implements InterfaceGOParameters, Serializable { public static boolean TRACE = false; - private String m_Name ="not defined"; - private long m_Seed = (long)100.0; - - // Opt. Algorithms and Parameters - private InterfaceOptimizer m_Optimizer = new DifferentialEvolution(); - private InterfaceOptimizationProblem m_Problem = new F1Problem(); - //private int m_FunctionCalls = 1000; - private InterfaceTerminator m_Terminator = new EvaluationTerminator(); -// private String m_OutputFileName = "none"; - transient private InterfacePopulationChangedEventListener m_Listener; /** * @@ -59,57 +49,17 @@ public class DEParameters implements InterfaceGOParameters, Serializable { * */ public DEParameters() { - if (TRACE) System.out.println("DEParameters Constructor start"); - this.m_Name="Optimization parameters"; - this.m_Optimizer = new DifferentialEvolution(); - this.m_Problem = new F1Problem(); - //this.m_FunctionCalls = 1000; - ((EvaluationTerminator)this.m_Terminator).setFitnessCalls(1000); - this.m_Optimizer.SetProblem(this.m_Problem); - if (TRACE) System.out.println("DEParameters Constructor end"); + super(new DifferentialEvolution(), new F1Problem(), new EvaluationTerminator(1000)); } - /** - * - */ private DEParameters(DEParameters Source) { - this.m_Name = Source.m_Name; - this.m_Optimizer = Source.m_Optimizer; - this.m_Problem = Source.m_Problem; - this.m_Terminator = Source.m_Terminator; - //this.m_FunctionCalls = Source.m_FunctionCalls; - this.m_Optimizer.SetProblem(this.m_Problem); - this.m_Seed = Source.m_Seed; + super(Source); } - /** - * - */ - public String getName() { - return m_Name; - } - /** - * - */ + public Object clone() { return new DEParameters(this); } - /** This method allows you to add the LectureGUI as listener to the Optimizer - * @param ea - */ - public void addPopulationChangedEventListener(InterfacePopulationChangedEventListener ea) { - this.m_Listener = ea; - if (this.m_Optimizer != null) this.m_Optimizer.addPopulationChangedEventListener(this.m_Listener); - } - - /** - * - */ - public String toString() { - String ret = "\r\nDE-Parameter:"+this.m_Problem.getStringRepresentationForProblem(this.m_Optimizer)+"\n"+this.m_Optimizer.getStringRepresentation(); - return ret; - } - /** This method returns a global info string * @return description */ @@ -117,70 +67,12 @@ public class DEParameters implements InterfaceGOParameters, Serializable { return "This is a Differential Evolution optimization method, please limit DE to real-valued genotypes."; } - /** This methods allow you to set and get the Seed for the Random Number Generator. - * @param x Long seed. - */ - public void setSeed(long x) { - m_Seed = x; - } - public long getSeed() { - return m_Seed; - } - public String seedTipText() { - return "Random number seed."; - } - /** This method allows you to set the current optimizing algorithm * @param optimizer The new optimizing algorithm */ public void setOptimizer(InterfaceOptimizer optimizer) { - // i'm a Monte Carlo Search Algorithm // *pff* i'll ignore that! } - public InterfaceOptimizer getOptimizer() { - return this.m_Optimizer; - } - - /** This method allows you to choose a termination criteria for the - * evolutionary algorithm. - * @param term The new terminator - */ - public void setTerminator(InterfaceTerminator term) { - this.m_Terminator = term; - } - public InterfaceTerminator getTerminator() { - return this.m_Terminator; - } - public String terminatorTipText() { - return "Choose a termination criterion."; - } - - /** This method will set the problem that is to be optimized - * @param problem - */ - public void setProblem (InterfaceOptimizationProblem problem) { - this.m_Problem = problem; - this.m_Optimizer.SetProblem(this.m_Problem); - } - public InterfaceOptimizationProblem getProblem() { - return this.m_Problem; - } - public String problemTipText() { - return "Choose the problem that is to optimize and the EA individual parameters."; - } - - /** This method will set the output filename - * @param name - */ -// public void setOutputFileName (String name) { -// this.m_OutputFileName = name; -// } -// public String getOutputFileName () { -// return this.m_OutputFileName; -// } -// public String outputFileNameTipText() { -// return "Set the name for the output file, if 'none' no output file will be created."; -// } /** Assuming that all optimizer will store thier data in a population * we will allow acess to this population to query to current state diff --git a/src/javaeva/server/modules/EPParameters.java b/src/javaeva/server/modules/EPParameters.java index b2c2c789..4be1a1a7 100644 --- a/src/javaeva/server/modules/EPParameters.java +++ b/src/javaeva/server/modules/EPParameters.java @@ -22,19 +22,9 @@ import java.io.Serializable; * Time: 13:49:09 * To change this template use File | Settings | File Templates. */ -public class EPParameters implements InterfaceGOParameters, Serializable { +public class EPParameters extends AbstractGOParameters implements InterfaceGOParameters, Serializable { public static boolean TRACE = false; - private String m_Name ="not defined"; - private long m_Seed = (long)100.0; - - // Opt. Algorithms and Parameters - private InterfaceOptimizer m_Optimizer = new EvolutionaryProgramming(); - private InterfaceOptimizationProblem m_Problem = new F1Problem(); - //private int m_FunctionCalls = 1000; - private InterfaceTerminator m_Terminator = new EvaluationTerminator(); -// private String m_OutputFileName = "none"; - transient private InterfacePopulationChangedEventListener m_Listener; /** * @@ -57,34 +47,17 @@ public class EPParameters implements InterfaceGOParameters, Serializable { * */ public EPParameters() { + super(new EvolutionaryProgramming(), new F1Problem(), new EvaluationTerminator()); if (TRACE) System.out.println("EPParameters Constructor start"); - this.m_Name="Optimization parameters"; - this.m_Optimizer = new EvolutionaryProgramming(); - this.m_Problem = new F1Problem(); - //this.m_FunctionCalls = 1000; - ((EvaluationTerminator)this.m_Terminator).setFitnessCalls(1000); - this.m_Optimizer.SetProblem(this.m_Problem); - if (TRACE) System.out.println("EPParameters Constructor end"); } /** * */ private EPParameters(EPParameters Source) { - this.m_Name = Source.m_Name; - this.m_Optimizer = Source.m_Optimizer; - this.m_Problem = Source.m_Problem; - this.m_Terminator = Source.m_Terminator; - //this.m_FunctionCalls = Source.m_FunctionCalls; - this.m_Optimizer.SetProblem(this.m_Problem); - this.m_Seed = Source.m_Seed; - } - /** - * - */ - public String getName() { - return m_Name; + super(Source); } + /** * */ @@ -92,22 +65,6 @@ public class EPParameters implements InterfaceGOParameters, Serializable { return new EPParameters(this); } - /** This method allows you to add the LectureGUI as listener to the Optimizer - * @param ea - */ - public void addPopulationChangedEventListener(InterfacePopulationChangedEventListener ea) { - this.m_Listener = ea; - if (this.m_Optimizer != null) this.m_Optimizer.addPopulationChangedEventListener(this.m_Listener); - } - - /** - * - */ - public String toString() { - String ret = "\r\nEP-Parameter:"+this.m_Problem.getStringRepresentationForProblem(this.m_Optimizer)+"\n"+this.m_Optimizer.getStringRepresentation(); - return ret; - } - /** This method returns a global info string * @return description */ @@ -115,70 +72,10 @@ public class EPParameters implements InterfaceGOParameters, Serializable { return "This is a Evolutionary Programming optimization method, please limit EP to mutation operators only."; } - /** This methods allow you to set and get the Seed for the Random Number Generator. - * @param x Long seed. - */ - public void setSeed(long x) { - m_Seed = x; - } - public long getSeed() { - return m_Seed; - } - public String seedTipText() { - return "Random number seed."; - } - - /** This method allows you to set the current optimizing algorithm - * @param optimizer The new optimizing algorithm - */ public void setOptimizer(InterfaceOptimizer optimizer) { // i'm a Monte Carlo Search Algorithm // *pff* i'll ignore that! } - public InterfaceOptimizer getOptimizer() { - return this.m_Optimizer; - } - - /** This method allows you to choose a termination criteria for the - * evolutionary algorithm. - * @param term The new terminator - */ - public void setTerminator(InterfaceTerminator term) { - this.m_Terminator = term; - } - public InterfaceTerminator getTerminator() { - return this.m_Terminator; - } - public String terminatorTipText() { - return "Choose a termination criterion."; - } - - /** This method will set the problem that is to be optimized - * @param problem - */ - public void setProblem (InterfaceOptimizationProblem problem) { - this.m_Problem = problem; - this.m_Optimizer.SetProblem(this.m_Problem); - } - public InterfaceOptimizationProblem getProblem() { - return this.m_Problem; - } - public String problemTipText() { - return "Choose the problem that is to optimize and the EA individual parameters."; - } - -// /** This method will set the output filename -// * @param name -// */ -// public void setOutputFileName (String name) { -// this.m_OutputFileName = name; -// } -// public String getOutputFileName () { -// return this.m_OutputFileName; -// } -// public String outputFileNameTipText() { -// return "Set the name for the output file, if 'none' no output file will be created."; -// } /** Assuming that all optimizer will store thier data in a population * we will allow acess to this population to query to current state diff --git a/src/javaeva/server/modules/GAParameters.java b/src/javaeva/server/modules/GAParameters.java index 9545d880..8c690bd8 100644 --- a/src/javaeva/server/modules/GAParameters.java +++ b/src/javaeva/server/modules/GAParameters.java @@ -23,23 +23,10 @@ import java.io.Serializable; * Time: 21:29:34 * To change this template use File | Settings | File Templates. */ -public class GAParameters implements InterfaceGOParameters, Serializable { +public class GAParameters extends AbstractGOParameters implements InterfaceGOParameters, Serializable { public static boolean TRACE = false; - private String m_Name ="not defined"; - private long m_Seed = (long)100.0; - // Opt. Algorithms and Parameters - private InterfaceOptimizer m_Optimizer = new GeneticAlgorithm(); - private InterfaceOptimizationProblem m_Problem = new B1Problem(); - //private int m_FunctionCalls = 1000; - private InterfaceTerminator m_Terminator = new EvaluationTerminator(); -// private String m_OutputFileName = "none"; - transient private InterfacePopulationChangedEventListener m_Listener; - - /** - * - */ public static GAParameters getInstance() { if (TRACE) System.out.println("GAParameters getInstance 1"); GAParameters Instance = (GAParameters) Serializer.loadObject("GAParameters.ser"); @@ -58,57 +45,22 @@ public class GAParameters implements InterfaceGOParameters, Serializable { * */ public GAParameters() { - if (TRACE) System.out.println("GAParameters Constructor start"); - this.m_Name="Optimization parameters"; - this.m_Optimizer = new GeneticAlgorithm(); - this.m_Problem = new B1Problem(); - //this.m_FunctionCalls = 1000; - ((EvaluationTerminator)this.m_Terminator).setFitnessCalls(1000); - this.m_Optimizer.SetProblem(this.m_Problem); - if (TRACE) System.out.println("GAParameters Constructor end"); + super(new GeneticAlgorithm(), new B1Problem(), new EvaluationTerminator()); } /** * */ private GAParameters(GAParameters Source) { - this.m_Name = Source.m_Name; - this.m_Optimizer = Source.m_Optimizer; - this.m_Problem = Source.m_Problem; - this.m_Terminator = Source.m_Terminator; - //this.m_FunctionCalls = Source.m_FunctionCalls; - this.m_Optimizer.SetProblem(this.m_Problem); - this.m_Seed = Source.m_Seed; - } - /** - * - */ - public String getName() { - return m_Name; + super(Source); } + /** * */ public Object clone() { return new GAParameters(this); } - - /** This method allows you to add the LectureGUI as listener to the Optimizer - * @param ea - */ - public void addPopulationChangedEventListener(InterfacePopulationChangedEventListener ea) { - this.m_Listener = ea; - if (this.m_Optimizer != null) this.m_Optimizer.addPopulationChangedEventListener(this.m_Listener); - } - - /** - * - */ - public String toString() { - String ret = "\r\nGO-Parameter:"+this.m_Problem.getStringRepresentationForProblem(this.m_Optimizer)+"\n"+this.m_Optimizer.getStringRepresentation(); - return ret; - } - /** This method returns a global info string * @return description */ @@ -116,70 +68,10 @@ public class GAParameters implements InterfaceGOParameters, Serializable { return "This is a Genetic Algorithm, which transforms into a GP or GE if the appropriate problem and genotype is used."; } - /** This methods allow you to set and get the Seed for the Random Number Generator. - * @param x Long seed. - */ - public void setSeed(long x) { - m_Seed = x; - } - public long getSeed() { - return m_Seed; - } - public String seedTipText() { - return "Random number seed."; - } - - /** This method allows you to set the current optimizing algorithm - * @param optimizer The new optimizing algorithm - */ public void setOptimizer(InterfaceOptimizer optimizer) { // i'm a Monte Carlo Search Algorithm // *pff* i'll ignore that! } - public InterfaceOptimizer getOptimizer() { - return this.m_Optimizer; - } - - /** This method allows you to choose a termination criteria for the - * evolutionary algorithm. - * @param term The new terminator - */ - public void setTerminator(InterfaceTerminator term) { - this.m_Terminator = term; - } - public InterfaceTerminator getTerminator() { - return this.m_Terminator; - } - public String terminatorTipText() { - return "Choose a termination criterion."; - } - - /** This method will set the problem that is to be optimized - * @param problem - */ - public void setProblem (InterfaceOptimizationProblem problem) { - this.m_Problem = problem; - this.m_Optimizer.SetProblem(this.m_Problem); - } - public InterfaceOptimizationProblem getProblem() { - return this.m_Problem; - } - public String problemTipText() { - return "Choose the problem that is to optimize and the EA individual parameters."; - } - -// /** This method will set the output filename -// * @param name -// */ -// public void setOutputFileName (String name) { -// this.m_OutputFileName = name; -// } -// public String getOutputFileName () { -// return this.m_OutputFileName; -// } -// public String outputFileNameTipText() { -// return "Set the name for the output file, if 'none' no output file will be created."; -// } /** Assuming that all optimizer will store thier data in a population * we will allow acess to this population to query to current state diff --git a/src/javaeva/server/modules/GOParameters.java b/src/javaeva/server/modules/GOParameters.java index 3e44dc7d..eef55398 100644 --- a/src/javaeva/server/modules/GOParameters.java +++ b/src/javaeva/server/modules/GOParameters.java @@ -1,21 +1,15 @@ package javaeva.server.modules; +import java.io.Serializable; + import javaeva.gui.BeanInspector; import javaeva.server.go.InterfaceGOParameters; import javaeva.server.go.InterfacePopulationChangedEventListener; -import javaeva.server.go.InterfaceTerminator; import javaeva.server.go.operators.terminators.EvaluationTerminator; import javaeva.server.go.problems.B1Problem; -import javaeva.server.go.problems.InterfaceOptimizationProblem; import javaeva.server.go.strategies.GeneticAlgorithm; -import javaeva.server.go.strategies.HillClimbing; -import javaeva.server.go.strategies.InterfaceOptimizer; import javaeva.tools.Serializer; -import java.io.Serializable; -import java.io.BufferedWriter; -import java.util.ArrayList; - /** * Created by IntelliJ IDEA. * Copyright: Copyright (c) 2003 @@ -25,19 +19,9 @@ import java.util.ArrayList; * $Date: 2007-12-04 14:22:52 +0100 (Tue, 04 Dec 2007) $ * $Author: mkron $ */ -public class GOParameters implements InterfaceGOParameters, Serializable { +public class GOParameters extends AbstractGOParameters implements InterfaceGOParameters, Serializable { public static boolean TRACE = false; - private String m_Name ="not defined"; - private long m_Seed = (long)100.0; - - // Opt. Algorithms and Parameters - private InterfaceOptimizer m_Optimizer = new GeneticAlgorithm(); - private InterfaceOptimizationProblem m_Problem = new B1Problem(); - //private int m_FunctionCalls = 1000; - private InterfaceTerminator m_Terminator = new EvaluationTerminator(); -// private String m_OutputFileName = "none"; - transient private InterfacePopulationChangedEventListener m_Listener; /** * @@ -50,22 +34,6 @@ public class GOParameters implements InterfaceGOParameters, Serializable { return Instance; } - public String toString() { - StringBuffer sb = new StringBuffer(m_Name); - sb.append("\n"); - sb.append("seed="); - sb.append(m_Seed); - sb.append("\nProblem: "); - sb.append(BeanInspector.toString(m_Problem)); - sb.append("\nOptimizer: "); - sb.append(BeanInspector.toString(m_Optimizer)); - sb.append("\nTerminator: "); - sb.append(BeanInspector.toString(m_Terminator)); - sb.append("\n"); -// sb.append(m_N) - return sb.toString(); - } - /** * */ @@ -76,33 +44,20 @@ public class GOParameters implements InterfaceGOParameters, Serializable { * */ public GOParameters() { - if (TRACE) System.out.println("GOParameters Constructor start"); - this.m_Name="Optimization parameters"; - this.m_Optimizer = new GeneticAlgorithm(); - this.m_Problem = new B1Problem(); - //this.m_FunctionCalls = 1000; - ((EvaluationTerminator)this.m_Terminator).setFitnessCalls(1000); - this.m_Optimizer.SetProblem(this.m_Problem); - if (TRACE) System.out.println("GOParameters Constructor end"); + super(new GeneticAlgorithm(), new B1Problem(), new EvaluationTerminator(1000)); } /** * */ private GOParameters(GOParameters Source) { - this.m_Name = Source.m_Name; - this.m_Optimizer = Source.m_Optimizer; - this.m_Problem = Source.m_Problem; - this.m_Terminator = Source.m_Terminator; - //this.m_FunctionCalls = Source.m_FunctionCalls; - this.m_Optimizer.SetProblem(this.m_Problem); - this.m_Seed = Source.m_Seed; + super(Source); } /** * */ public String getName() { - return m_Name; + return "Optimization parameters"; } /** * @@ -110,102 +65,10 @@ public class GOParameters implements InterfaceGOParameters, Serializable { public Object clone() { return new GOParameters(this); } - - /** This method allows you to add the LectureGUI as listener to the Optimizer - * @param ea - */ - public void addPopulationChangedEventListener(InterfacePopulationChangedEventListener ea) { - this.m_Listener = ea; - if (this.m_Optimizer != null) this.m_Optimizer.addPopulationChangedEventListener(this.m_Listener); - } - -// /** -// * -// */ -// public String toString() { -// String ret = "";//"\r\nGO-Parameter:"+this.m_Problem.getStringRepresentationForProblem()+"\n"+this.m_Optimizer.getStringRepresentation(); -// return ret; -// } - /** This method returns a global info string * @return description */ public String globalInfo() { return "Select the optimization parameters."; } - - /** This methods allow you to set and get the Seed for the Random Number Generator. - * @param x Long seed. - */ - public void setSeed(long x) { - m_Seed = x; - } - public long getSeed() { - return m_Seed; - } - public String seedTipText() { - return "Random number seed, set to zero to use current system time."; - } - - /** This method allows you to choose a termination criteria for the - * evolutionary algorithm. - * @param term The new terminator - */ - public void setTerminator(InterfaceTerminator term) { - this.m_Terminator = term; - } - public InterfaceTerminator getTerminator() { - return this.m_Terminator; - } - public String terminatorTipText() { - return "Choose a termination criterion."; - } - -// /** This method allows you to set the current optimizing algorithm -// * @param optimizer The new optimizing algorithm -// */ -// public void SetOptimizer(InterfaceOptimizer optimizer) { -// this.m_Optimizer = optimizer; -// this.m_Optimizer.SetProblem(this.m_Problem); -// if (this.m_Listener != null) this.m_Optimizer.addPopulationChangedEventListener(this.m_Listener); -// } - - public void setOptimizer(InterfaceOptimizer optimizer) { - this.m_Optimizer = optimizer; - this.m_Optimizer.SetProblem(this.m_Problem); - if (this.m_Listener != null) this.m_Optimizer.addPopulationChangedEventListener(this.m_Listener); - } - public InterfaceOptimizer getOptimizer() { - return this.m_Optimizer; - } - public String optimizerTipText() { - return "Choose an optimizing strategy."; - } - - /** This method will set the problem that is to be optimized - * @param problem - */ - public void setProblem (InterfaceOptimizationProblem problem) { - this.m_Problem = problem; - this.m_Optimizer.SetProblem(this.m_Problem); - } - public InterfaceOptimizationProblem getProblem() { - return this.m_Problem; - } - public String problemTipText() { - return "Choose the problem that is to optimize and the EA individual parameters."; - } - -// /** This method will set the output filename -// * @param name -// */ -// public void setOutputFileName (String name) { -// this.m_OutputFileName = name; -// } -// public String getOutputFileName () { -// return this.m_OutputFileName; -// } -// public String outputFileNameTipText() { -// return "Set the name for the output file, if 'none' no output file will be created."; -// } } diff --git a/src/javaeva/server/modules/HCParameters.java b/src/javaeva/server/modules/HCParameters.java index 99ebc671..093752a2 100644 --- a/src/javaeva/server/modules/HCParameters.java +++ b/src/javaeva/server/modules/HCParameters.java @@ -1,5 +1,7 @@ package javaeva.server.modules; +import java.io.Serializable; + import javaeva.server.go.InterfaceGOParameters; import javaeva.server.go.InterfacePopulationChangedEventListener; import javaeva.server.go.InterfaceTerminator; @@ -7,14 +9,10 @@ import javaeva.server.go.operators.terminators.EvaluationTerminator; import javaeva.server.go.populations.Population; import javaeva.server.go.problems.B1Problem; import javaeva.server.go.problems.InterfaceOptimizationProblem; -import javaeva.server.go.strategies.GeneticAlgorithm; import javaeva.server.go.strategies.HillClimbing; import javaeva.server.go.strategies.InterfaceOptimizer; -import javaeva.server.go.strategies.MonteCarloSearch; import javaeva.tools.Serializer; -import java.io.Serializable; - /** The class gives access to all HC parameters for the JavaEvA * top level GUI. * Created by IntelliJ IDEA. @@ -23,20 +21,7 @@ import java.io.Serializable; * Time: 21:19:20 * To change this template use File | Settings | File Templates. */ -public class HCParameters implements InterfaceGOParameters, Serializable { - - public static boolean TRACE = false; - private String m_Name ="not defined"; - private long m_Seed = (long)100.0; - - // Opt. Algorithms and Parameters - private InterfaceOptimizer m_Optimizer = new HillClimbing(); - private InterfaceOptimizationProblem m_Problem = new B1Problem(); - //private int m_FunctionCalls = 1000; - private InterfaceTerminator m_Terminator = new EvaluationTerminator(); -// private String m_OutputFileName = "none"; - transient private InterfacePopulationChangedEventListener m_Listener; - +public class HCParameters extends AbstractGOParameters implements InterfaceGOParameters, Serializable { /** * */ @@ -58,33 +43,14 @@ public class HCParameters implements InterfaceGOParameters, Serializable { * */ public HCParameters() { - if (TRACE) System.out.println("HCParameters Constructor start"); - this.m_Name="Optimization parameters"; - this.m_Optimizer = new HillClimbing(); - this.m_Problem = new B1Problem(); - //this.m_FunctionCalls = 1000; - ((EvaluationTerminator)this.m_Terminator).setFitnessCalls(1000); - this.m_Optimizer.SetProblem(this.m_Problem); - if (TRACE) System.out.println("HCParameters Constructor end"); + super(new HillClimbing(), new B1Problem(), new EvaluationTerminator()); } /** * */ private HCParameters(HCParameters Source) { - this.m_Name = Source.m_Name; - this.m_Optimizer = Source.m_Optimizer; - this.m_Problem = Source.m_Problem; - this.m_Terminator = Source.m_Terminator; - //this.m_FunctionCalls = Source.m_FunctionCalls; - this.m_Optimizer.SetProblem(this.m_Problem); - this.m_Seed = Source.m_Seed; - } - /** - * - */ - public String getName() { - return m_Name; + super(Source); } /** * @@ -92,23 +58,6 @@ public class HCParameters implements InterfaceGOParameters, Serializable { public Object clone() { return new HCParameters(this); } - - /** This method allows you to add the LectureGUI as listener to the Optimizer - * @param ea - */ - public void addPopulationChangedEventListener(InterfacePopulationChangedEventListener ea) { - this.m_Listener = ea; - if (this.m_Optimizer != null) this.m_Optimizer.addPopulationChangedEventListener(this.m_Listener); - } - - /** - * - */ - public String toString() { - String ret = "\r\nGO-Parameter:"+this.m_Problem.getStringRepresentationForProblem(this.m_Optimizer)+"\n"+this.m_Optimizer.getStringRepresentation(); - return ret; - } - /** This method returns a global info string * @return description */ @@ -116,70 +65,10 @@ public class HCParameters implements InterfaceGOParameters, Serializable { return "This is a Hill-Climber, use a population size > 1 for a Multi-Start Hill-Climber."; } - /** This methods allow you to set and get the Seed for the Random Number Generator. - * @param x Long seed. - */ - public void setSeed(long x) { - m_Seed = x; - } - public long getSeed() { - return m_Seed; - } - public String seedTipText() { - return "Random number seed."; - } - - /** This method allows you to set the current optimizing algorithm - * @param optimizer The new optimizing algorithm - */ public void setOptimizer(InterfaceOptimizer optimizer) { // i'm a Monte Carlo Search Algorithm // *pff* i'll ignore that! } - public InterfaceOptimizer getOptimizer() { - return this.m_Optimizer; - } - - /** This method allows you to choose a termination criteria for the - * evolutionary algorithm. - * @param term The new terminator - */ - public void setTerminator(InterfaceTerminator term) { - this.m_Terminator = term; - } - public InterfaceTerminator getTerminator() { - return this.m_Terminator; - } - public String terminatorTipText() { - return "Choose a termination criterion."; - } - - /** This method will set the problem that is to be optimized - * @param problem - */ - public void setProblem (InterfaceOptimizationProblem problem) { - this.m_Problem = problem; - this.m_Optimizer.SetProblem(this.m_Problem); - } - public InterfaceOptimizationProblem getProblem() { - return this.m_Problem; - } - public String problemTipText() { - return "Choose the problem that is to optimize and the EA individual parameters."; - } - -// /** This method will set the output filename -// * @param name -// */ -// public void setOutputFileName (String name) { -// this.m_OutputFileName = name; -// } -// public String getOutputFileName () { -// return this.m_OutputFileName; -// } -// public String outputFileNameTipText() { -// return "Set the name for the output file, if 'none' no output file will be created."; -// } /** Assuming that all optimizer will store thier data in a population * we will allow acess to this population to query to current state diff --git a/src/javaeva/server/modules/MCParameters.java b/src/javaeva/server/modules/MCParameters.java index e1184552..bb464773 100644 --- a/src/javaeva/server/modules/MCParameters.java +++ b/src/javaeva/server/modules/MCParameters.java @@ -22,19 +22,8 @@ import java.io.Serializable; * Time: 21:07:40 * To change this template use File | Settings | File Templates. */ -public class MCParameters implements InterfaceGOParameters, Serializable { - +public class MCParameters extends AbstractGOParameters implements InterfaceGOParameters, Serializable { public static boolean TRACE = false; - private String m_Name ="not defined"; - private long m_Seed = (long)100.0; - - // Opt. Algorithms and Parameters - private InterfaceOptimizer m_Optimizer = new MonteCarloSearch(); - private InterfaceOptimizationProblem m_Problem = new B1Problem(); - //private int m_FunctionCalls = 1000; - private InterfaceTerminator m_Terminator = new EvaluationTerminator(); -// private String m_OutputFileName = "none"; - transient private InterfacePopulationChangedEventListener m_Listener; /** * @@ -56,35 +45,14 @@ public class MCParameters implements InterfaceGOParameters, Serializable { /** * */ - public MCParameters() { - if (TRACE) System.out.println("MCParameters Constructor start"); - this.m_Name="Optimization parameters"; - this.m_Optimizer = new MonteCarloSearch(); - this.m_Problem = new B1Problem(); - //this.m_FunctionCalls = 1000; - ((EvaluationTerminator)this.m_Terminator).setFitnessCalls(1000); - this.m_Optimizer.SetProblem(this.m_Problem); - if (TRACE) System.out.println("GOParameters Constructor end"); + public MCParameters() { + super(new MonteCarloSearch(), new B1Problem(), new EvaluationTerminator()); } - /** - * - */ private MCParameters(MCParameters Source) { - this.m_Name = Source.m_Name; - this.m_Optimizer = Source.m_Optimizer; - this.m_Problem = Source.m_Problem; - this.m_Terminator = Source.m_Terminator; - //this.m_FunctionCalls = Source.m_FunctionCalls; - this.m_Optimizer.SetProblem(this.m_Problem); - this.m_Seed = Source.m_Seed; - } - /** - * - */ - public String getName() { - return m_Name; + super(Source); } + /** * */ @@ -92,22 +60,6 @@ public class MCParameters implements InterfaceGOParameters, Serializable { return new MCParameters(this); } - /** This method allows you to add the LectureGUI as listener to the Optimizer - * @param ea - */ - public void addPopulationChangedEventListener(InterfacePopulationChangedEventListener ea) { - this.m_Listener = ea; - if (this.m_Optimizer != null) this.m_Optimizer.addPopulationChangedEventListener(this.m_Listener); - } - - /** - * - */ - public String toString() { - String ret = "\r\nGO-Parameter:"+this.m_Problem.getStringRepresentationForProblem(this.m_Optimizer)+"\n"+this.m_Optimizer.getStringRepresentation(); - return ret; - } - /** This method returns a global info string * @return description */ @@ -115,70 +67,10 @@ public class MCParameters implements InterfaceGOParameters, Serializable { return "This is a simple Monte-Carlo Search, please use big populations sizes for faster drawing."; } - /** This methods allow you to set and get the Seed for the Random Number Generator. - * @param x Long seed. - */ - public void setSeed(long x) { - m_Seed = x; - } - public long getSeed() { - return m_Seed; - } - public String seedTipText() { - return "Random number seed."; - } - - /** This method allows you to set the current optimizing algorithm - * @param optimizer The new optimizing algorithm - */ public void setOptimizer(InterfaceOptimizer optimizer) { - // i'm a Monte Carlo Search Algorithm // *pff* i'll ignore that! } - public InterfaceOptimizer getOptimizer() { - return this.m_Optimizer; - } - /** This method allows you to choose a termination criteria for the - * evolutionary algorithm. - * @param term The new terminator - */ - public void setTerminator(InterfaceTerminator term) { - this.m_Terminator = term; - } - public InterfaceTerminator getTerminator() { - return this.m_Terminator; - } - public String terminatorTipText() { - return "Choose a termination criterion."; - } - - /** This method will set the problem that is to be optimized - * @param problem - */ - public void setProblem (InterfaceOptimizationProblem problem) { - this.m_Problem = problem; - this.m_Optimizer.SetProblem(this.m_Problem); - } - public InterfaceOptimizationProblem getProblem() { - return this.m_Problem; - } - public String problemTipText() { - return "Choose the problem that is to optimize and the EA individual parameters."; - } - -// /** This method will set the output filename -// * @param name -// */ -// public void setOutputFileName (String name) { -// this.m_OutputFileName = name; -// } -// public String getOutputFileName () { -// return this.m_OutputFileName; -// } -// public String outputFileNameTipText() { -// return "Set the name for the output file, if 'none' no output file will be created."; -// } /** Assuming that all optimizer will store thier data in a population * we will allow acess to this population to query to current state diff --git a/src/javaeva/server/modules/MOEAParameters.java b/src/javaeva/server/modules/MOEAParameters.java index 02fd70e2..8d349e06 100644 --- a/src/javaeva/server/modules/MOEAParameters.java +++ b/src/javaeva/server/modules/MOEAParameters.java @@ -26,23 +26,10 @@ import java.io.Serializable; * Time: 13:49:09 * To change this template use File | Settings | File Templates. */ -public class MOEAParameters implements InterfaceGOParameters, Serializable { +public class MOEAParameters extends AbstractGOParameters implements InterfaceGOParameters, Serializable { public static boolean TRACE = false; - private String m_Name ="not defined"; - private long m_Seed = (long)100.0; - // Opt. Algorithms and Parameters - private InterfaceOptimizer m_Optimizer = new MultiObjectiveEA(); - private InterfaceOptimizationProblem m_Problem = new TF1Problem(); - //private int m_FunctionCalls = 1000; - private InterfaceTerminator m_Terminator = new EvaluationTerminator(); -// private String m_OutputFileName = "none"; - transient private InterfacePopulationChangedEventListener m_Listener; - - /** - * - */ public static MOEAParameters getInstance() { if (TRACE) System.out.println("MOEAParameters getInstance 1"); MOEAParameters Instance = (MOEAParameters) Serializer.loadObject("MOEAParameters.ser"); @@ -51,67 +38,22 @@ public class MOEAParameters implements InterfaceGOParameters, Serializable { return Instance; } - /** - * - */ public void saveInstance() { Serializer.storeObject("MOEAParameters.ser",this); } - /** - * - */ + public MOEAParameters() { - if (TRACE) System.out.println("MOEAParameters Constructor start"); - this.m_Name="Optimization parameters"; - this.m_Optimizer = new MultiObjectiveEA(); - this.m_Problem = new TF1Problem(); - //this.m_FunctionCalls = 1000; - ((EvaluationTerminator)this.m_Terminator).setFitnessCalls(1000); - this.m_Optimizer.SetProblem(this.m_Problem); - if (TRACE) System.out.println("MOEAParameters Constructor end"); + super(new MultiObjectiveEA(), new TF1Problem(), new EvaluationTerminator(1000)); } - /** - * - */ private MOEAParameters(MOEAParameters Source) { - this.m_Name = Source.m_Name; - this.m_Optimizer = Source.m_Optimizer; - this.m_Problem = Source.m_Problem; - this.m_Terminator = Source.m_Terminator; - //this.m_FunctionCalls = Source.m_FunctionCalls; - this.m_Optimizer.SetProblem(this.m_Problem); - this.m_Seed = Source.m_Seed; + super(Source); } - /** - * - */ - public String getName() { - return m_Name; - } - /** - * - */ + public Object clone() { return new MOEAParameters(this); } - /** This method allows you to add the LectureGUI as listener to the Optimizer - * @param ea - */ - public void addPopulationChangedEventListener(InterfacePopulationChangedEventListener ea) { - this.m_Listener = ea; - if (this.m_Optimizer != null) this.m_Optimizer.addPopulationChangedEventListener(this.m_Listener); - } - - /** - * - */ - public String toString() { - String ret = "\r\nMOEA-Parameter:"+this.m_Problem.getStringRepresentationForProblem(this.m_Optimizer)+"\n"+this.m_Optimizer.getStringRepresentation(); - return ret; - } - /** This method returns a global info string * @return description */ @@ -119,60 +61,6 @@ public class MOEAParameters implements InterfaceGOParameters, Serializable { return "This is a multi-objective evoluationary algorithm, please limit MOEA to multi-objective problems (due to the given framework only the fitness of objective one will be plotted)."; } - /** This methods allow you to set and get the Seed for the Random Number Generator. - * @param x Long seed. - */ - public void setSeed(long x) { - m_Seed = x; - } - public long getSeed() { - return m_Seed; - } - public String seedTipText() { - return "Random number seed."; - } - - /** This method allows you to choose a termination criteria for the - * evolutionary algorithm. - * @param term The new terminator - */ - public void setTerminator(InterfaceTerminator term) { - this.m_Terminator = term; - } - public InterfaceTerminator getTerminator() { - return this.m_Terminator; - } - public String terminatorTipText() { - return "Choose a termination criterion."; - } - - /** This method will set the problem that is to be optimized - * @param problem - */ - public void setProblem (InterfaceOptimizationProblem problem) { - this.m_Problem = problem; - ((MultiObjectiveEA)this.m_Optimizer).SetProblem(this.m_Problem); - } - public InterfaceOptimizationProblem getProblem() { - return this.m_Problem; - } - public String problemTipText() { - return "Choose the problem that is to optimize and the EA individual parameters."; - } - -// /** This method will set the output filename -// * @param name -// */ -// public void setOutputFileName (String name) { -// this.m_OutputFileName = name; -// } -// public String getOutputFileName () { -// return this.m_OutputFileName; -// } -// public String outputFileNameTipText() { -// return "Set the name for the output file, if 'none' no output file will be created."; -// } - /** Assuming that all optimizer will store thier data in a population * we will allow acess to this population to query to current state * of the optimizer. @@ -194,9 +82,6 @@ public class MOEAParameters implements InterfaceGOParameters, Serializable { public InterfaceOptimizer getOptimizer() { return ((MultiObjectiveEA)this.m_Optimizer).getOptimizer(); } -// public void SetOptimizer(InterfaceOptimizer b){ -// // i'm a MOEA i'll ignore that -// } public void setOptimizer(InterfaceOptimizer b){ ((MultiObjectiveEA)this.m_Optimizer).setOptimizer(b); } diff --git a/src/javaeva/server/modules/PBILParameters.java b/src/javaeva/server/modules/PBILParameters.java index 6c679609..e04a6795 100644 --- a/src/javaeva/server/modules/PBILParameters.java +++ b/src/javaeva/server/modules/PBILParameters.java @@ -1,20 +1,17 @@ package javaeva.server.modules; +import java.io.Serializable; + import javaeva.server.go.InterfaceGOParameters; import javaeva.server.go.InterfacePopulationChangedEventListener; -import javaeva.server.go.InterfaceTerminator; import javaeva.server.go.operators.selection.InterfaceSelection; import javaeva.server.go.operators.terminators.EvaluationTerminator; import javaeva.server.go.populations.Population; import javaeva.server.go.problems.B1Problem; -import javaeva.server.go.problems.InterfaceOptimizationProblem; import javaeva.server.go.strategies.InterfaceOptimizer; -import javaeva.server.go.strategies.MonteCarloSearch; import javaeva.server.go.strategies.PopulationBasedIncrementalLearning; import javaeva.tools.Serializer; -import java.io.Serializable; - /** The class gives access to all PBIL parameters for the JavaEvA * top level GUI. * Created by IntelliJ IDEA. @@ -23,23 +20,10 @@ import java.io.Serializable; * Time: 21:53:29 * To change this template use File | Settings | File Templates. */ -public class PBILParameters implements InterfaceGOParameters, Serializable { +public class PBILParameters extends AbstractGOParameters implements InterfaceGOParameters, Serializable { public static boolean TRACE = false; - private String m_Name ="not defined"; - private long m_Seed = (long)100.0; - // Opt. Algorithms and Parameters - private InterfaceOptimizer m_Optimizer = new PopulationBasedIncrementalLearning(); - private InterfaceOptimizationProblem m_Problem = new B1Problem(); - //private int m_FunctionCalls = 1000; - private InterfaceTerminator m_Terminator = new EvaluationTerminator(); -// private String m_OutputFileName = "none"; - transient private InterfacePopulationChangedEventListener m_Listener; - - /** - * - */ public static PBILParameters getInstance() { if (TRACE) System.out.println("PBILParameters getInstance 1"); PBILParameters Instance = (PBILParameters) Serializer.loadObject("PBILParameters.ser"); @@ -48,67 +32,21 @@ public class PBILParameters implements InterfaceGOParameters, Serializable { return Instance; } - /** - * - */ public void saveInstance() { Serializer.storeObject("PBILParameters.ser",this); } - /** - * - */ + public PBILParameters() { - if (TRACE) System.out.println("PBILParameters Constructor start"); - this.m_Name="Optimization parameters"; - this.m_Optimizer = new PopulationBasedIncrementalLearning(); - this.m_Problem = new B1Problem(); - //this.m_FunctionCalls = 1000; - ((EvaluationTerminator)this.m_Terminator).setFitnessCalls(1000); - this.m_Optimizer.SetProblem(this.m_Problem); - if (TRACE) System.out.println("PBILParameters Constructor end"); + super(new PopulationBasedIncrementalLearning(), new B1Problem(), new EvaluationTerminator(1000)); } - /** - * - */ private PBILParameters(PBILParameters Source) { - this.m_Name = Source.m_Name; - this.m_Optimizer = Source.m_Optimizer; - this.m_Problem = Source.m_Problem; - this.m_Terminator = Source.m_Terminator; - //this.m_FunctionCalls = Source.m_FunctionCalls; - this.m_Optimizer.SetProblem(this.m_Problem); - this.m_Seed = Source.m_Seed; + super(Source); } - /** - * - */ - public String getName() { - return m_Name; - } - /** - * - */ public Object clone() { return new PBILParameters(this); } - /** This method allows you to add the LectureGUI as listener to the Optimizer - * @param ea - */ - public void addPopulationChangedEventListener(InterfacePopulationChangedEventListener ea) { - this.m_Listener = ea; - if (this.m_Optimizer != null) this.m_Optimizer.addPopulationChangedEventListener(this.m_Listener); - } - - /** - * - */ - public String toString() { - String ret = "\r\nGO-Parameter:"+this.m_Problem.getStringRepresentationForProblem(this.m_Optimizer)+"\n"+this.m_Optimizer.getStringRepresentation(); - return ret; - } - /** This method returns a global info string * @return description */ @@ -116,70 +54,10 @@ public class PBILParameters implements InterfaceGOParameters, Serializable { return ((PopulationBasedIncrementalLearning)this.m_Optimizer).globalInfo(); } - /** This methods allow you to set and get the Seed for the Random Number Generator. - * @param x Long seed. - */ - public void setSeed(long x) { - m_Seed = x; - } - public long getSeed() { - return m_Seed; - } - public String seedTipText() { - return "Random number seed."; - } - - /** This method allows you to set the current optimizing algorithm - * @param optimizer The new optimizing algorithm - */ public void setOptimizer(InterfaceOptimizer optimizer) { // i'm a Monte Carlo Search Algorithm // *pff* i'll ignore that! } - public InterfaceOptimizer getOptimizer() { - return this.m_Optimizer; - } - - /** This method allows you to choose a termination criteria for the - * evolutionary algorithm. - * @param term The new terminator - */ - public void setTerminator(InterfaceTerminator term) { - this.m_Terminator = term; - } - public InterfaceTerminator getTerminator() { - return this.m_Terminator; - } - public String terminatorTipText() { - return "Choose a termination criterion."; - } - - /** This method will set the problem that is to be optimized - * @param problem - */ - public void setProblem (InterfaceOptimizationProblem problem) { - this.m_Problem = problem; - this.m_Optimizer.SetProblem(this.m_Problem); - } - public InterfaceOptimizationProblem getProblem() { - return this.m_Problem; - } - public String problemTipText() { - return "Choose the problem that is to optimize and the EA individual parameters."; - } - -// /** This method will set the output filename -// * @param name -// */ -// public void setOutputFileName (String name) { -// this.m_OutputFileName = name; -// } -// public String getOutputFileName () { -// return this.m_OutputFileName; -// } -// public String outputFileNameTipText() { -// return "Set the name for the output file, if 'none' no output file will be created."; -// } /** Assuming that all optimizer will store thier data in a population * we will allow acess to this population to query to current state diff --git a/src/javaeva/server/modules/PSOParameters.java b/src/javaeva/server/modules/PSOParameters.java index 484eee22..c022d2e4 100644 --- a/src/javaeva/server/modules/PSOParameters.java +++ b/src/javaeva/server/modules/PSOParameters.java @@ -26,19 +26,9 @@ import java.io.Serializable; * Time: 17:58:37 * To change this template use File | Settings | File Templates. */ -public class PSOParameters implements InterfaceGOParameters, Serializable { +public class PSOParameters extends AbstractGOParameters implements InterfaceGOParameters, Serializable { public static boolean TRACE = false; - private String m_Name ="not defined"; - private long m_Seed = (long)100.0; - - // Opt. Algorithms and Parameters - private InterfaceOptimizer m_Optimizer = new ParticleSwarmOptimization(); - private InterfaceOptimizationProblem m_Problem = new F1Problem(); - //private int m_FunctionCalls = 1000; - private InterfaceTerminator m_Terminator = new EvaluationTerminator(); -// private String m_OutputFileName = "none"; - transient private InterfacePopulationChangedEventListener m_Listener; /** * @@ -61,57 +51,17 @@ public class PSOParameters implements InterfaceGOParameters, Serializable { * */ public PSOParameters() { - if (TRACE) System.out.println("PSOParameters Constructor start"); - this.m_Name="Optimization parameters"; - this.m_Optimizer = new ParticleSwarmOptimization(); - this.m_Problem = new F1Problem(); - //this.m_FunctionCalls = 1000; - ((EvaluationTerminator)this.m_Terminator).setFitnessCalls(1000); - this.m_Optimizer.SetProblem(this.m_Problem); - if (TRACE) System.out.println("PSOParameters Constructor end"); + super(new ParticleSwarmOptimization(), new F1Problem(), new EvaluationTerminator()); } - /** - * - */ private PSOParameters(PSOParameters Source) { - this.m_Name = Source.m_Name; - this.m_Optimizer = Source.m_Optimizer; - this.m_Problem = Source.m_Problem; - this.m_Terminator = Source.m_Terminator; - //this.m_FunctionCalls = Source.m_FunctionCalls; - this.m_Optimizer.SetProblem(this.m_Problem); - this.m_Seed = Source.m_Seed; + super(Source); } - /** - * - */ - public String getName() { - return m_Name; - } - /** - * - */ + public Object clone() { return new PSOParameters(this); } - /** This method allows you to add the LectureGUI as listener to the Optimizer - * @param ea - */ - public void addPopulationChangedEventListener(InterfacePopulationChangedEventListener ea) { - this.m_Listener = ea; - if (this.m_Optimizer != null) this.m_Optimizer.addPopulationChangedEventListener(this.m_Listener); - } - - /** - * - */ - public String toString() { - String ret = "\r\nGO-Parameter:"+this.m_Problem.getStringRepresentationForProblem(this.m_Optimizer)+"\n"+this.m_Optimizer.getStringRepresentation(); - return ret; - } - /** This method returns a global info string * @return description */ @@ -127,71 +77,10 @@ public class PSOParameters implements InterfaceGOParameters, Serializable { setCheckSpeedLimit(isCheckSpeedLimit()); setTopology(getTopology()); } - - /** This methods allow you to set and get the Seed for the Random Number Generator. - * @param x Long seed. - */ - public void setSeed(long x) { - m_Seed = x; - } - public long getSeed() { - return m_Seed; - } - public String seedTipText() { - return "Random number seed, set to zero to use current time"; - } - /** This method allows you to set the current optimizing algorithm - * @param optimizer The new optimizing algorithm - */ public void setOptimizer(InterfaceOptimizer optimizer) { - // i'm a Monte Carlo Search Algorithm // *pff* i'll ignore that! } - public InterfaceOptimizer getOptimizer() { - return this.m_Optimizer; - } - - /** This method allows you to choose a termination criteria for the - * evolutionary algorithm. - * @param term The new terminator - */ - public void setTerminator(InterfaceTerminator term) { - this.m_Terminator = term; - } - public InterfaceTerminator getTerminator() { - return this.m_Terminator; - } - public String terminatorTipText() { - return "Choose a termination criterion."; - } - - /** This method will set the problem that is to be optimized - * @param problem - */ - public void setProblem (InterfaceOptimizationProblem problem) { - this.m_Problem = problem; - this.m_Optimizer.SetProblem(this.m_Problem); - } - public InterfaceOptimizationProblem getProblem() { - return this.m_Problem; - } - public String problemTipText() { - return "Choose the problem that is to optimize and the EA individual parameters."; - } - -// /** This method will set the output filename -// * @param name -// */ -// public void setOutputFileName (String name) { -// this.m_OutputFileName = name; -// } -// public String getOutputFileName () { -// return this.m_OutputFileName; -// } -// public String outputFileNameTipText() { -// return "Set the name for the output file, if 'none' no output file will be created."; -// } /** Assuming that all optimizer will store thier data in a population * we will allow acess to this population to query to current state diff --git a/src/javaeva/server/modules/Processor.java b/src/javaeva/server/modules/Processor.java index cfb02f2e..4ee5e7c2 100644 --- a/src/javaeva/server/modules/Processor.java +++ b/src/javaeva/server/modules/Processor.java @@ -5,23 +5,27 @@ import javaeva.server.go.InterfaceGOParameters; import javaeva.server.go.InterfacePopulationChangedEventListener; import javaeva.server.go.InterfaceProcessor; import javaeva.server.go.PopulationInterface; +import javaeva.server.go.operators.postprocess.PostProcess; import javaeva.server.go.operators.terminators.EvaluationTerminator; import javaeva.server.go.populations.Population; -import javaeva.server.go.problems.InterfaceMultimodalProblem; +import javaeva.server.go.problems.AbstractOptimizationProblem; import javaeva.server.go.tools.RandomNumberGenerator; import javaeva.server.stat.InterfaceStatistics; +import javaeva.server.stat.InterfaceTextListener; import wsi.ra.jproxy.RemoteStateListener; public class Processor extends Thread implements InterfaceProcessor, InterfacePopulationChangedEventListener { - public static final boolean TRACE=false; + private static final boolean TRACE=false; private volatile boolean m_optRunning; - public volatile boolean m_doRunScript; - public InterfaceStatistics m_Statistics; - public InterfaceGOParameters goParams; - public boolean m_createInitialPopulations=true; +// private volatile boolean m_doRunScript; + private InterfaceStatistics m_Statistics; + private InterfaceGOParameters goParams; + private boolean m_createInitialPopulations=true; + private boolean saveParams = true; private RemoteStateListener m_ListenerModule; private boolean wasRestarted = false; +// private int postProcessSteps = 0; private int runCounter = 0; // transient private String m_OutputPath = ""; @@ -54,6 +58,15 @@ public class Processor extends Thread implements InterfaceProcessor, InterfacePo protected void setOptRunning(boolean bRun) { m_optRunning = bRun; } + + /** + * If set to true, before every run the parameters will be stored to a file. + * + * @param doSave + */ + public void setSaveParams(boolean doSave) { + saveParams = doSave; + } // public void addPopulationChangedEventListener(InterfacePopulationChangedEventListener ea) { // listener = ea; @@ -94,16 +107,16 @@ public class Processor extends Thread implements InterfaceProcessor, InterfacePo public void stopOpt() { // this means user break if (TRACE) System.out.println("called StopOpt"); setOptRunning(false); - m_doRunScript = false; +// m_doRunScript = false; if (TRACE) System.out.println("m_doRunScript = false "); } - /** - * - */ - public void runScript() { - m_doRunScript = true; - } +// /** +// * +// */ +// public void runScript() { +// m_doRunScript = true; +// } /** * @@ -124,12 +137,11 @@ public class Processor extends Thread implements InterfaceProcessor, InterfacePo try { while (isOptRunning()) { setPriority(3); - goParams.saveInstance(); + if (saveParams) goParams.saveInstance(); optimize("Run"); setPriority(1); } } catch (Exception e) { - // TODO Das hier so machen, daß trotz Exception eine neue optimierung ohne Neustart möglich ist! System.err.println("Caught exception in Processor: "+e.getMessage()); e.printStackTrace(); //m_Statistics.stopOptPerformed(false); @@ -202,12 +214,19 @@ public class Processor extends Thread implements InterfaceProcessor, InterfacePo } while (isOptRunning() && !this.goParams.getTerminator().isTerminated(this.goParams.getOptimizer().getPopulation())); runCounter++; - if (goParams.getProblem() instanceof InterfaceMultimodalProblem) { - // TODO improve this? - InterfaceMultimodalProblem mmProb = (InterfaceMultimodalProblem)goParams.getProblem(); - System.out.println("no optima found: " + mmProb.getNumberOfFoundOptima(goParams.getOptimizer().getPopulation())); - } + //////////////// Default stats m_Statistics.stopOptPerformed(isOptRunning()); // stop is "normal" if opt wasnt set false by the user + //////////////// PP + PostProcess.postProcess(goParams.getPostProcessParams(), goParams.getOptimizer().getAllSolutions(), (AbstractOptimizationProblem)goParams.getProblem(), (InterfaceTextListener)m_Statistics); + // moved to PostProcess +// if ((goParams.getProblem() instanceof InterfaceMultimodalProblem)) { +// InterfaceMultimodalProblem mmProb = (InterfaceMultimodalProblem)goParams.getProblem(); +// PostProcessInterim.outputResult((AbstractOptimizationProblem)mmProb, goParams.getOptimizer().getAllSolutions(), 0.01, System.out, 0, 2000, 20, goParams.getPostProcessSteps()); +//// PostProcessInterim.postProcess(mmProb, goParams.getOptimizer().getPopulation(), 0.01, System.out, 0, 2000, 20); +// if ((goParams.getProblem() instanceof InterfaceMultimodalProblemKnown)) { +// PostProcessInterim.outputResultKnown((InterfaceMultimodalProblemKnown)goParams.getProblem(), goParams.getOptimizer().getAllSolutions(), 0.01, System.out, 0., 2000., 20); +// } +// } } setOptRunning(false); // normal finish if (m_ListenerModule!=null) m_ListenerModule.performedStop(); // is only needed in client server mode diff --git a/src/javaeva/server/modules/SAParameters.java b/src/javaeva/server/modules/SAParameters.java index ae659c13..a966037f 100644 --- a/src/javaeva/server/modules/SAParameters.java +++ b/src/javaeva/server/modules/SAParameters.java @@ -23,11 +23,9 @@ import java.io.Serializable; * Time: 21:25:12 * To change this template use File | Settings | File Templates. */ -public class SAParameters implements InterfaceGOParameters, Serializable { +public class SAParameters extends AbstractGOParameters implements InterfaceGOParameters, Serializable { public static boolean TRACE = false; - private String m_Name ="not defined"; - private long m_Seed = (long)100.0; // Opt. Algorithms and Parameters private InterfaceOptimizer m_Optimizer = new SimulatedAnnealing(); @@ -58,57 +56,16 @@ public class SAParameters implements InterfaceGOParameters, Serializable { * */ public SAParameters() { - if (TRACE) System.out.println("SAParameters Constructor start"); - this.m_Name="Optimization parameters"; - this.m_Optimizer = new SimulatedAnnealing(); - this.m_Problem = new B1Problem(); - //this.m_FunctionCalls = 1000; - ((EvaluationTerminator)this.m_Terminator).setFitnessCalls(1000); - this.m_Optimizer.SetProblem(this.m_Problem); - if (TRACE) System.out.println("SAParameters Constructor end"); + super(new SimulatedAnnealing(),new B1Problem(),new EvaluationTerminator()); } - /** - * - */ private SAParameters(SAParameters Source) { - this.m_Name = Source.m_Name; - this.m_Optimizer = Source.m_Optimizer; - this.m_Problem = Source.m_Problem; - this.m_Terminator = Source.m_Terminator; - //this.m_FunctionCalls = Source.m_FunctionCalls; - this.m_Optimizer.SetProblem(this.m_Problem); - this.m_Seed = Source.m_Seed; + super(Source); } - /** - * - */ - public String getName() { - return m_Name; - } - /** - * - */ public Object clone() { return new SAParameters(this); } - /** This method allows you to add the LectureGUI as listener to the Optimizer - * @param ea - */ - public void addPopulationChangedEventListener(InterfacePopulationChangedEventListener ea) { - this.m_Listener = ea; - if (this.m_Optimizer != null) this.m_Optimizer.addPopulationChangedEventListener(this.m_Listener); - } - - /** - * - */ - public String toString() { - String ret = "\r\nGO-Parameter:"+this.m_Problem.getStringRepresentationForProblem(this.m_Optimizer)+"\n"+this.m_Optimizer.getStringRepresentation(); - return ret; - } - /** This method returns a global info string * @return description */ @@ -116,70 +73,9 @@ public class SAParameters implements InterfaceGOParameters, Serializable { return "This is a simple Simulated Annealing Algorithm."; } - /** This methods allow you to set and get the Seed for the Random Number Generator. - * @param x Long seed. - */ - public void setSeed(long x) { - m_Seed = x; - } - public long getSeed() { - return m_Seed; - } - public String seedTipText() { - return "Random number seed."; - } - - /** This method allows you to set the current optimizing algorithm - * @param optimizer The new optimizing algorithm - */ public void setOptimizer(InterfaceOptimizer optimizer) { - // i'm a Monte Carlo Search Algorithm // *pff* i'll ignore that! } - public InterfaceOptimizer getOptimizer() { - return this.m_Optimizer; - } - - /** This method allows you to choose a termination criteria for the - * evolutionary algorithm. - * @param term The new terminator - */ - public void setTerminator(InterfaceTerminator term) { - this.m_Terminator = term; - } - public InterfaceTerminator getTerminator() { - return this.m_Terminator; - } - public String terminatorTipText() { - return "Choose a termination criterion."; - } - - /** This method will set the problem that is to be optimized - * @param problem - */ - public void setProblem (InterfaceOptimizationProblem problem) { - this.m_Problem = problem; - this.m_Optimizer.SetProblem(this.m_Problem); - } - public InterfaceOptimizationProblem getProblem() { - return this.m_Problem; - } - public String problemTipText() { - return "Choose the problem that is to optimize and the EA individual parameters."; - } - -// /** This method will set the output filename -// * @param name -// */ -// public void setOutputFileName (String name) { -// this.m_OutputFileName = name; -// } -// public String getOutputFileName () { -// return this.m_OutputFileName; -// } -// public String outputFileNameTipText() { -// return "Set the name for the output file, if 'none' no output file will be created."; -// } /** Assuming that all optimizer will store thier data in a population * we will allow acess to this population to query to current state diff --git a/src/javaeva/server/modules/SSGAParameters.java b/src/javaeva/server/modules/SSGAParameters.java index 4b148be7..b2e509d9 100644 --- a/src/javaeva/server/modules/SSGAParameters.java +++ b/src/javaeva/server/modules/SSGAParameters.java @@ -23,19 +23,9 @@ import java.io.Serializable; * Time: 15:44:34 * To change this template use File | Settings | File Templates. */ -public class SSGAParameters implements InterfaceGOParameters, Serializable { +public class SSGAParameters extends AbstractGOParameters implements InterfaceGOParameters, Serializable { public static boolean TRACE = false; - private String m_Name ="not defined"; - private long m_Seed = (long)100.0; - - // Opt. Algorithms and Parameters - private InterfaceOptimizer m_Optimizer = new SteadyStateGA(); - private InterfaceOptimizationProblem m_Problem = new B1Problem(); - //private int m_FunctionCalls = 1000; - private InterfaceTerminator m_Terminator = new EvaluationTerminator(); -// private String m_OutputFileName = "none"; - transient private InterfacePopulationChangedEventListener m_Listener; /** * @@ -57,58 +47,17 @@ public class SSGAParameters implements InterfaceGOParameters, Serializable { /** * */ - public SSGAParameters() { - if (TRACE) System.out.println("SSGAParameters Constructor start"); - this.m_Name="Optimization parameters"; - this.m_Optimizer = new SteadyStateGA(); - this.m_Problem = new B1Problem(); - //this.m_FunctionCalls = 1000; - ((EvaluationTerminator)this.m_Terminator).setFitnessCalls(1000); - this.m_Optimizer.SetProblem(this.m_Problem); - if (TRACE) System.out.println("SSGAParameters Constructor end"); + public SSGAParameters() { + super(new SteadyStateGA(), new B1Problem(), new EvaluationTerminator()); + } + private SSGAParameters(SSGAParameters Source) { + super(Source); } - /** - * - */ - private SSGAParameters(SSGAParameters Source) { - this.m_Name = Source.m_Name; - this.m_Optimizer = Source.m_Optimizer; - this.m_Problem = Source.m_Problem; - this.m_Terminator = Source.m_Terminator; - //this.m_FunctionCalls = Source.m_FunctionCalls; - this.m_Optimizer.SetProblem(this.m_Problem); - this.m_Seed = Source.m_Seed; - } - /** - * - */ - public String getName() { - return m_Name; - } - /** - * - */ public Object clone() { return new SSGAParameters(this); } - /** This method allows you to add the LectureGUI as listener to the Optimizer - * @param ea - */ - public void addPopulationChangedEventListener(InterfacePopulationChangedEventListener ea) { - this.m_Listener = ea; - if (this.m_Optimizer != null) this.m_Optimizer.addPopulationChangedEventListener(this.m_Listener); - } - - /** - * - */ - public String toString() { - String ret = "\r\nGO-Parameter:"+this.m_Problem.getStringRepresentationForProblem(this.m_Optimizer)+"\n"+this.m_Optimizer.getStringRepresentation(); - return ret; - } - /** This method returns a global info string * @return description */ @@ -116,70 +65,9 @@ public class SSGAParameters implements InterfaceGOParameters, Serializable { return "This is a steady-state GA."; } - /** This methods allow you to set and get the Seed for the Random Number Generator. - * @param x Long seed. - */ - public void setSeed(long x) { - m_Seed = x; - } - public long getSeed() { - return m_Seed; - } - public String seedTipText() { - return "Random number seed."; - } - - /** This method allows you to set the current optimizing algorithm - * @param optimizer The new optimizing algorithm - */ public void setOptimizer(InterfaceOptimizer optimizer) { - // i'm a Monte Carlo Search Algorithm // *pff* i'll ignore that! } - public InterfaceOptimizer getOptimizer() { - return this.m_Optimizer; - } - - /** This method allows you to choose a termination criteria for the - * evolutionary algorithm. - * @param term The new terminator - */ - public void setTerminator(InterfaceTerminator term) { - this.m_Terminator = term; - } - public InterfaceTerminator getTerminator() { - return this.m_Terminator; - } - public String terminatorTipText() { - return "Choose a termination criterion."; - } - - /** This method will set the problem that is to be optimized - * @param problem - */ - public void setProblem (InterfaceOptimizationProblem problem) { - this.m_Problem = problem; - this.m_Optimizer.SetProblem(this.m_Problem); - } - public InterfaceOptimizationProblem getProblem() { - return this.m_Problem; - } - public String problemTipText() { - return "Choose the problem that is to optimize and the EA individual parameters."; - } - -// /** This method will set the output filename -// * @param name -// */ -// public void setOutputFileName (String name) { -// this.m_OutputFileName = name; -// } -// public String getOutputFileName () { -// return this.m_OutputFileName; -// } -// public String outputFileNameTipText() { -// return "Set the name for the output file, if 'none' no output file will be created."; -// } /** Assuming that all optimizer will store thier data in a population * we will allow acess to this population to query to current state diff --git a/src/javaeva/server/stat/AbstractStatistics.java b/src/javaeva/server/stat/AbstractStatistics.java index 9009b6c9..8b3251cf 100644 --- a/src/javaeva/server/stat/AbstractStatistics.java +++ b/src/javaeva/server/stat/AbstractStatistics.java @@ -14,7 +14,7 @@ import javaeva.server.go.individuals.AbstractEAIndividual; import javaeva.server.go.problems.InterfaceAdditionalPopulationInformer; import wsi.ra.tool.StatisticUtils; -public abstract class AbstractStatistics implements InterfaceStatistics { +public abstract class AbstractStatistics implements InterfaceTextListener, InterfaceStatistics { private PrintWriter resultOut; public final static boolean TRACE = false; protected StatisticsParameter m_StatisticsParameter; @@ -133,6 +133,16 @@ public abstract class AbstractStatistics implements InterfaceStatistics { } } + ////////////// InterfaceTextListener + public void print(String str) { + printToTextListener(str); + } + ////////////// InterfaceTextListener + public void println(String str) { + printToTextListener(str); + printToTextListener("\n"); + } + public StatisticsParameter getStatisticsParameter() { return m_StatisticsParameter; } @@ -218,6 +228,14 @@ public abstract class AbstractStatistics implements InterfaceStatistics { if (doTextOutput()) printToTextListener(getOutputHeader(informer, pop)+'\n'); firstPlot = false; } +// System.out.println("pop fcalls: " + pop.getFunctionCalls()); +// if ((pop.getFunctionCalls() % 100) != 0 ) { +// System.err.println("error: pop fcalls: " + pop.getFunctionCalls()); +// double [] bla= new double[1]; +// bla[10]=0; +// //TODO +// +// } if (pop.getSpecificData() != null) { plotSpecificData(pop, informer); return; diff --git a/src/javaeva/server/stat/InterfaceStatistics.java b/src/javaeva/server/stat/InterfaceStatistics.java index 9dfcddd5..22c9443d 100644 --- a/src/javaeva/server/stat/InterfaceStatistics.java +++ b/src/javaeva/server/stat/InterfaceStatistics.java @@ -16,20 +16,26 @@ import javaeva.server.go.IndividualInterface; import javaeva.server.go.PopulationInterface; import javaeva.server.go.problems.InterfaceAdditionalPopulationInformer; /*==========================================================================* -* INTERFACE DECLARATION -*==========================================================================*/ + * INTERFACE DECLARATION + *==========================================================================*/ /** * */ public interface InterfaceStatistics { - public void startOptPerformed(String InfoString,int runnumber); // called from processor - public void stopOptPerformed(boolean normal); // called from processor - public void addTextListener(InterfaceTextListener listener); - public boolean removeTextListener(InterfaceTextListener listener); - public void printToTextListener(String s); - public void createNextGenerationPerformed(PopulationInterface Pop, InterfaceAdditionalPopulationInformer informer); - public void createNextGenerationPerformed(double[] bestfit,double[] worstfit,int calls); - public StatisticsParameter getStatisticsParameter(); // called from moduleadapter - public IndividualInterface getBestSolution(); // returns the best overall solution - public double[] getBestFitness(); // returns the best overall fitness + /** + * Initialize statistics computations. + */ + public void startOptPerformed(String InfoString,int runnumber); // called from processor + /** + * Finalize statistics computations. + */ + public void stopOptPerformed(boolean normal); // called from processor + public void addTextListener(InterfaceTextListener listener); + public boolean removeTextListener(InterfaceTextListener listener); + public void printToTextListener(String s); + public void createNextGenerationPerformed(PopulationInterface Pop, InterfaceAdditionalPopulationInformer informer); + public void createNextGenerationPerformed(double[] bestfit,double[] worstfit,int calls); + public StatisticsParameter getStatisticsParameter(); // called from moduleadapter + public IndividualInterface getBestSolution(); // returns the best overall solution + public double[] getBestFitness(); // returns the best overall fitness } \ No newline at end of file diff --git a/src/javaeva/server/stat/InterfaceTextListener.java b/src/javaeva/server/stat/InterfaceTextListener.java index eaa8bba0..8c1c298c 100644 --- a/src/javaeva/server/stat/InterfaceTextListener.java +++ b/src/javaeva/server/stat/InterfaceTextListener.java @@ -2,4 +2,5 @@ package javaeva.server.stat; public interface InterfaceTextListener { public void print(String str); + public void println(String str); } diff --git a/src/javaeva/server/stat/StatisticsParameterImpl.java b/src/javaeva/server/stat/StatisticsParameterImpl.java index cbf80da8..438daa4b 100644 --- a/src/javaeva/server/stat/StatisticsParameterImpl.java +++ b/src/javaeva/server/stat/StatisticsParameterImpl.java @@ -186,7 +186,8 @@ public class StatisticsParameterImpl implements StatisticsParameter, Serializabl * */ public void setResultFileName(String x) { - m_ResultFileName = x; + if (x==null) m_ResultFileName = ""; + else m_ResultFileName = x; } /** diff --git a/src/javaeva/server/stat/StatisticsStandalone.java b/src/javaeva/server/stat/StatisticsStandalone.java index c86eb1aa..2df6f380 100644 --- a/src/javaeva/server/stat/StatisticsStandalone.java +++ b/src/javaeva/server/stat/StatisticsStandalone.java @@ -110,10 +110,6 @@ public class StatisticsStandalone extends AbstractStatistics implements Interfac ((ArrayList[]) m_Result.get(i))[optRunsPerformed] = new ArrayList(); } - - /** - * - */ public void startOptPerformed(String infoString, int runNumber) { super.startOptPerformed(infoString, runNumber); if (runNumber == 0) { @@ -127,9 +123,6 @@ public class StatisticsStandalone extends AbstractStatistics implements Interfac m_InfoString = infoString; } - /** - * - */ public void stopOptPerformed(boolean normal) { super.stopOptPerformed(normal); diff --git a/src/javaeva/tools/Pair.java b/src/javaeva/tools/Pair.java new file mode 100644 index 00000000..042747b9 --- /dev/null +++ b/src/javaeva/tools/Pair.java @@ -0,0 +1,33 @@ +package javaeva.tools; + +/** + * Simple pair structure of two types, Scheme style, but typed. + * + * @author mkron + * + */ +public class Pair { + public S head; + public T tail; + + public Pair(S head, T tail) { + this.head = head; + this.tail = tail; + } + + public S car() { + return head; + } + + public T cdr() { + return tail; + } + + public S head() { + return head; + } + + public T tail() { + return tail; + } +} \ No newline at end of file diff --git a/src/wsi/ra/chart2d/DArea.java b/src/wsi/ra/chart2d/DArea.java index 398f97e2..6e5176f8 100644 --- a/src/wsi/ra/chart2d/DArea.java +++ b/src/wsi/ra/chart2d/DArea.java @@ -12,19 +12,23 @@ package wsi.ra.chart2d; +import java.awt.Color; +import java.awt.Dimension; +import java.awt.FontMetrics; +import java.awt.Graphics; +import java.awt.Point; +import java.awt.print.PageFormat; +import java.awt.print.Printable; + +import javax.swing.JComponent; +import javax.swing.border.Border; + +import wsi.ra.print.PagePrinter; + /*==========================================================================* * IMPORTS *==========================================================================*/ -import java.awt.*; -import java.awt.image.BufferedImage; -import javax.swing.*; -import javax.swing.border.Border; -import java.util.Vector; - -// zum Drucken: -import java.awt.print.*; -import wsi.ra.print.PagePrinter; /*==========================================================================* * CLASS DECLARATION @@ -37,7 +41,7 @@ import wsi.ra.print.PagePrinter; */ public class DArea extends JComponent implements DParent, Printable { - private static final boolean under_construction = false; + private static final boolean TRACE = false; /** * the default minimal rectangle which is shown @@ -157,7 +161,7 @@ public class DArea extends JComponent implements DParent, Printable * @param rect the visible DRectangle in DArea coordinates */ public void setVisibleRectangle( DRectangle rect ){ - if( under_construction )System.out.println("DArea.setVisibleRectangle(DRectangle)"); + if( TRACE )System.out.println("DArea.setVisibleRectangle(DRectangle)"); if( rect.isEmpty() ) throw new IllegalArgumentException( "You shopuld never try to set an empty rectangle\n" @@ -380,7 +384,7 @@ public class DArea extends JComponent implements DParent, Printable * @param g the java.awt.Graphics object */ public void paint( Graphics g ){ - if( under_construction ) System.out.println("DArea.paint(Graphics)"); + if( TRACE ) System.out.println("DArea.paint(Graphics)"); if( auto_focus ) { container.restore(); visible_rect = (DRectangle)container.getRectangle().clone(); @@ -400,7 +404,7 @@ public class DArea extends JComponent implements DParent, Printable * @param r the rectangle to repaint */ public void repaint( DRectangle r ){ - if( under_construction ) System.out.println("DArea.repaint(DRectangle)"+r); + if( TRACE ) System.out.println("DArea.repaint(DRectangle)"+r); if( r == null ) throw new IllegalArgumentException("Cannot repaint a null DRectangle"); if( r.isAll() || auto_focus ) repaint(); @@ -471,7 +475,7 @@ public class DArea extends JComponent implements DParent, Printable * @param aFlag visible or not */ public void setGridVisible( boolean aFlag ){ - if( under_construction ) System.out.println("DArea.setGridVisisble: "+aFlag); + if( TRACE ) System.out.println("DArea.setGridVisisble: "+aFlag); grid.rectangle = getDRectangle(); grid.setVisible( aFlag ); } @@ -572,7 +576,7 @@ public class DArea extends JComponent implements DParent, Printable * @return int @see java.awt.print.Printable */ public int print( Graphics g, PageFormat pf, int pi ){ - if( under_construction ) System.out.println("DArea.print(...)"); + if( TRACE ) System.out.println("DArea.print(...)"); if( pi > 0 ) return Printable.NO_SUCH_PAGE; Border sb = getBorder(); @@ -644,7 +648,7 @@ public class DArea extends JComponent implements DParent, Printable public void restoreBorder(){ dborder = container.getDBorder(); - if( under_construction ) System.out.println("DArea.restoreBorder -> "+dborder); + if( TRACE ) System.out.println("DArea.restoreBorder -> "+dborder); } /** @@ -653,7 +657,7 @@ public class DArea extends JComponent implements DParent, Printable * ScaledBorder or not and on the auto_grid option */ private void paintGrid( DMeasures m ){ - if( under_construction ) System.out.println("DArea.paintGrid(DMeasures)"); + if( TRACE ) System.out.println("DArea.paintGrid(DMeasures)"); grid.rectangle = getDRectangle(); if( auto_grid ){ Border b = getBorder(); @@ -679,7 +683,7 @@ public class DArea extends JComponent implements DParent, Printable * @param m the measures of the area */ private void paintGrid(ScaledBorder sb, DMeasures m){ - if( under_construction ) System.out.println("DArea.paintGrid(ScaledBorder, DMeasures)"); + if( TRACE ) System.out.println("DArea.paintGrid(ScaledBorder, DMeasures)"); Dimension d = getSize(); FontMetrics fm = m.getGraphics().getFontMetrics(); grid.hor_dist = sb.getSrcdX(fm, d); diff --git a/src/wsi/ra/chart2d/DPointSet.java b/src/wsi/ra/chart2d/DPointSet.java index 2e9eb7db..1f457343 100644 --- a/src/wsi/ra/chart2d/DPointSet.java +++ b/src/wsi/ra/chart2d/DPointSet.java @@ -213,6 +213,15 @@ public class DPointSet extends DComponent public Stroke getStroke(){ return stroke; } + + /** + * Return the minimum y value in the point set. + * + * @return the minimum y value in the point set + */ + public double getMinYVal() { + return y.getMinImageValue(); + } public void setConnected( boolean aFlag ){ boolean changed = !( aFlag == connected ); @@ -274,7 +283,7 @@ public class DPointSet extends DComponent // if( size != y.getSize() ) throw // new ArrayStoreException( // "The number of x-values is not equal to the number of y-values.\n" -// +"The size of the DPointSet isn´t clear." +// +"The size of the DPointSet isn�t clear." // ); // return size; // }