diff --git a/.classpath b/.classpath index bdb2412f..8876802c 100644 --- a/.classpath +++ b/.classpath @@ -2,5 +2,6 @@ + diff --git a/resources/ConvergenceTerminator.html b/resources/ConvergenceTerminator.html deleted file mode 100644 index 0fd630c2..00000000 --- a/resources/ConvergenceTerminator.html +++ /dev/null @@ -1,13 +0,0 @@ - - -Convergence Terminator - - -

Convergence Terminator

-
-

-The convergence terminator stops the optimization, when there has been hardly -any change in the best population fitness (within percentual range) for a certain -time, given in generations or fitness calls. - - \ No newline at end of file diff --git a/resources/FitnessConvergenceTerminator.html b/resources/FitnessConvergenceTerminator.html new file mode 100644 index 00000000..7b82bfc5 --- /dev/null +++ b/resources/FitnessConvergenceTerminator.html @@ -0,0 +1,16 @@ + + +Fitness Convergence Terminator + + +

Fitness Convergence Terminator

+
+

+The fitness convergence terminator stops the optimization, when there has been hardly +any change in the best population fitness (within percentual or absolute distance) for a certain +time, given in generations or fitness calls.
+Be aware that, if the optimization is allowed to be non-monotonic, such as for (,)-ES strategies, +and if the optimum is close to zero, it may happen that the fitness fluctuates due to numeric +issues and does not easily converge in a relative measure. + + \ No newline at end of file diff --git a/resources/PhenotypeConvergenceTerminator.html b/resources/PhenotypeConvergenceTerminator.html new file mode 100644 index 00000000..e38dcf97 --- /dev/null +++ b/resources/PhenotypeConvergenceTerminator.html @@ -0,0 +1,15 @@ + + +Phenotype Convergence Terminator + + +

Phenotype Convergence Terminator

+
+

+The phenotype convergence terminator stops the optimization, when there has been hardly +any change in the best population individual (within percentual or absolute distance) for a certain +time span, given in generations or fitness calls.
+Be aware that, if the optimum individual is close to zero, it may happen that its phenotype values +fluctuate due to numeric issues and do not easily converge in a relative measure. + + \ No newline at end of file diff --git a/src/javaeva/OptimizerFactory.java b/src/javaeva/OptimizerFactory.java new file mode 100644 index 00000000..03a2f62d --- /dev/null +++ b/src/javaeva/OptimizerFactory.java @@ -0,0 +1,230 @@ +package javaeva; + +import javaeva.gui.BeanInspector; +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.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.DifferentialEvolution; +import javaeva.server.go.strategies.EvolutionStrategies; +import javaeva.server.go.strategies.GeneticAlgorithm; +import javaeva.server.go.strategies.InterfaceOptimizer; +import javaeva.server.go.strategies.ParticleSwarmOptimization; +import javaeva.server.go.strategies.Tribes; +import javaeva.server.modules.GOParameters; + +/** + * The OptimizerFactory allows quickly creating some optimizers without thinking much + * about parameters. You can access a runnable Optimization thread and directly start it, + * or access its fully prepared GOParameter instance, change some parameters, and start it then. + * + * @author mkron + * + */ +public class OptimizerFactory { + private static InterfaceTerminator term = null; + public final static int STD_ES = 1; + public final static int CMA_ES = 2; + public final static int STD_GA = 3; + public final static int PSO = 4; + public final static int DE = 5; + public final static int TRIBES = 6; + + public final static int defaultFitCalls = 10000; + public final static int randSeed = 0; + + /** + * Return a simple String showing the accessible optimizers. For external access." + * + * @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"; + } + + /** + * The default Terminator finishes after n fitness calls, the default n is returned here. + * @return the default number of fitness call done before termination + */ + public static int getDefaultFitCalls() { + return defaultFitCalls; + } + + /** + * Create a runnable optimization Runnable and directly start it in an own thread. The Runnable + * will notify waiting threads and set the isFinished flag when the optimization is complete. + * If the optType is invalid, null will be returned. + * + * @param optType + * @param problem + * @param outputFilePrefix + * @return + */ + public static OptimizerRunnable optimizeInThread(final int optType, AbstractOptimizationProblem problem, String outputFilePrefix) { + OptimizerRunnable runnable = getOptRunnable(optType, problem, outputFilePrefix); + if (runnable != null) new Thread(runnable).start(); + return runnable; + } + + // TODO hier weiter kommentieren + public static IndividualInterface optimize(final int optType, AbstractOptimizationProblem problem, String outputFilePrefix) { + OptimizerRunnable runnable = getOptRunnable(optType, problem, outputFilePrefix); + if (runnable != null) { + new Thread(runnable).run(); + return runnable.getSolution(); + } else return null; + } + + public static OptimizerRunnable getOptRunnable(final int optType, AbstractOptimizationProblem problem, String outputFilePrefix) { + switch (optType) { + case STD_ES: + return new OptimizerRunnable(standardES(problem), outputFilePrefix); + case CMA_ES: + return new OptimizerRunnable(cmaES(problem), outputFilePrefix); + case STD_GA: + return new OptimizerRunnable(standardGA(problem), outputFilePrefix); + case PSO: + return new OptimizerRunnable(standardPSO(problem), outputFilePrefix); + case DE: + return new OptimizerRunnable(standardDE(problem), outputFilePrefix); + case TRIBES: + return new OptimizerRunnable(tribes(problem), outputFilePrefix); + } + System.err.println("Error: optimizer type " + optType + " is unknown!"); + return null; + } + + public static InterfaceTerminator defaultTerminator() { + if (term == null) term = new EvaluationTerminator(defaultFitCalls); + return term; + } + + public static void setTerminator(InterfaceTerminator term) { + OptimizerFactory.term = term; + } + + public static InterfaceTerminator getTerminator() { + return OptimizerFactory.term; + } + + /** + * Add an InterfaceTerminator to any new optimizer in a boolean combination. The old and the given + * terminator will be combined as in (TOld && TNew) if bAnd is true, and as in (TOld || TNew) if bAnd + * is false. + * @param newTerm a new InterfaceTerminator instance + * @param bAnd indicate the boolean combination + */ + public static void addTerminator(InterfaceTerminator newTerm, boolean bAnd) { + if (OptimizerFactory.term == null) OptimizerFactory.term = term; + else setTerminator(new CombinedTerminator(OptimizerFactory.term, newTerm, bAnd)); + } + + public static GOParameters makeParams(InterfaceOptimizer opt, Population pop, AbstractOptimizationProblem problem, long seed, InterfaceTerminator term) { + GOParameters params = new GOParameters(); + params.setProblem(problem); + opt.SetProblem(problem); + opt.setPopulation(pop); + params.setOptimizer(opt); + params.setTerminator(term); + params.setSeed(seed); + return params; + } + + public static GOParameters standardES(AbstractOptimizationProblem problem) { + EvolutionStrategies es = new EvolutionStrategies(); + es.setMyu(15); + es.setLambda(50); + es.setPlusStrategy(false); + + Object maybeTemplate = BeanInspector.callIfAvailable(problem, "getEAIndividual", null); + if ((maybeTemplate != null) && (maybeTemplate instanceof InterfaceESIndividual)) { + // Set CMA operator for mutation + AbstractEAIndividual indy = (AbstractEAIndividual)maybeTemplate; + indy.setMutationOperator(new MutateESGlobal()); + indy.setCrossoverOperator(new CrossoverESDefault()); + } else { + System.err.println("Error, standard ES is implemented for ES individuals only (requires double data types)"); + return null; + } + + Population pop = new Population(); + pop.setPopulationSize(es.getLambda()); + + return makeParams(es, pop, problem, randSeed, defaultTerminator()); + } + + public static GOParameters cmaES(AbstractOptimizationProblem problem) { + EvolutionStrategies es = new EvolutionStrategies(); + es.setMyu(15); + es.setLambda(50); + es.setPlusStrategy(false); + + Object maybeTemplate = BeanInspector.callIfAvailable(problem, "getEAIndividual", null); + if ((maybeTemplate != null) && (maybeTemplate instanceof InterfaceESIndividual)) { + // Set CMA operator for mutation + AbstractEAIndividual indy = (AbstractEAIndividual)maybeTemplate; + MutateESCovarianceMartixAdaption cmaMut = new MutateESCovarianceMartixAdaption(); + cmaMut.setCheckConstraints(true); + indy.setMutationOperator(cmaMut); + indy.setCrossoverOperator(new CrossoverESDefault()); + } else { + System.err.println("Error, CMA-ES is implemented for ES individuals only (requires double data types)"); + return null; + } + + Population pop = new Population(); + pop.setPopulationSize(es.getLambda()); + + return makeParams(es, pop, problem, randSeed, defaultTerminator()); + } + + public static GOParameters standardPSO(AbstractOptimizationProblem problem) { + ParticleSwarmOptimization pso = new ParticleSwarmOptimization(); + Population pop = new Population(); + pop.setPopulationSize(30); + pso.setPopulation(pop); + pso.setPhiValues(2.05, 2.05); + pso.getTopology().setSelectedTag("Grid"); + return makeParams(pso, pop, problem, randSeed, defaultTerminator()); + } + + public static GOParameters standardDE(AbstractOptimizationProblem problem) { + DifferentialEvolution de = new DifferentialEvolution(); + Population pop = new Population(); + pop.setPopulationSize(50); + de.setPopulation(pop); + de.getDEType().setSelectedTag(1); // this sets current-to-best + de.setF(0.8); + de.setK(0.6); + de.setLambda(0.6); + de.setMt(0.05); + + return makeParams(de, pop, problem, randSeed, defaultTerminator()); + } + + public static GOParameters standardGA(AbstractOptimizationProblem problem) { + GeneticAlgorithm ga = new GeneticAlgorithm(); + Population pop = new Population(); + pop.setPopulationSize(100); + ga.setPopulation(pop); + ga.setElitism(true); + + return makeParams(ga, pop, problem, randSeed, defaultTerminator()); + } + + public static GOParameters tribes(AbstractOptimizationProblem problem) { + Tribes tr = new Tribes(); + Population pop = new Population(); + pop.setPopulationSize(1); // only for init + problem.initPopulation(pop); + return makeParams(tr, pop, problem, randSeed, defaultTerminator()); + } +} diff --git a/src/javaeva/OptimizerRunnable.java b/src/javaeva/OptimizerRunnable.java new file mode 100644 index 00000000..2d747469 --- /dev/null +++ b/src/javaeva/OptimizerRunnable.java @@ -0,0 +1,94 @@ +package javaeva; + +import java.io.PrintWriter; +import java.io.StringWriter; +import java.util.BitSet; + +import javaeva.gui.BeanInspector; +import javaeva.server.go.IndividualInterface; +import javaeva.server.go.InterfaceTerminator; +import javaeva.server.go.InterfaceGOParameters; +import javaeva.server.go.individuals.InterfaceDataTypeBinary; +import javaeva.server.go.individuals.InterfaceDataTypeDouble; +import javaeva.server.go.individuals.InterfaceDataTypeInteger; +import javaeva.server.go.operators.terminators.CombinedTerminator; +import javaeva.server.modules.GOParameters; +import javaeva.server.modules.Processor; +import javaeva.server.stat.StatisticsStandalone; + +/** + * This Runnable class just encapsulates the Processor class with some simple ways to access a solution. + * + * @author mkron + * + */ +public class OptimizerRunnable implements Runnable { + Processor proc; + boolean isFinished = false; + + public OptimizerRunnable(GOParameters params, String outputFilePrefix) { + proc = new Processor(new StatisticsStandalone(outputFilePrefix), null, params); + } + + public InterfaceGOParameters getGOParams() { + return proc.getGOParams(); + } + + public void run() { + isFinished = false; + try { + proc.startOpt(); + proc.runOptOnce(); + } catch(Exception e) { + proc.getStatistics().printToTextListener("Exception in OptimizeThread::run: " + e.getMessage() + "\n"); + StringWriter sw = new StringWriter(); + e.printStackTrace(new PrintWriter(sw)); + proc.getStatistics().printToTextListener(sw.toString()); + } + isFinished = true; + synchronized (this) { + this.notifyAll(); + } + } + + public boolean isFinished() { + return isFinished; + } + + public void stopOpt() { + proc.stopOpt(); + } + + public IndividualInterface getSolution() { + return proc.getStatistics().getBestSolution(); + } + + 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;"; + } else return "Not yet terminated"; + } + + public double[] getDoubleSolution() { + IndividualInterface indy = getSolution(); + if (indy instanceof InterfaceDataTypeDouble) { + return ((InterfaceDataTypeDouble)indy).getDoubleData(); + } else return null; + } + + public BitSet getBinarySolution() { + IndividualInterface indy = getSolution(); + if (indy instanceof InterfaceDataTypeBinary) { + return ((InterfaceDataTypeBinary)indy).getBinaryData(); + } else return null; + } + + public int[] getIntegerSolution() { + IndividualInterface indy = getSolution(); + if (indy instanceof InterfaceDataTypeInteger) { + return ((InterfaceDataTypeInteger)indy).getIntegerData(); + } else return null; + } +} \ No newline at end of file diff --git a/src/javaeva/client/EvAClient.java b/src/javaeva/client/EvAClient.java index d6e2a319..bc1d35a7 100644 --- a/src/javaeva/client/EvAClient.java +++ b/src/javaeva/client/EvAClient.java @@ -23,7 +23,11 @@ import java.awt.event.KeyEvent; import java.awt.event.WindowAdapter; import java.awt.event.WindowEvent; import java.io.Serializable; +import java.net.URL; +import java.util.Iterator; +import java.util.Map; import java.util.Properties; +import java.util.Set; import javaeva.gui.ExtAction; import javaeva.gui.JEFrame; @@ -35,6 +39,7 @@ import javaeva.server.EvAServer; import javaeva.server.modules.ModuleAdapter; import javaeva.tools.EVAERROR; import javaeva.tools.EVAHELP; +import javaeva.tools.ReflectPackage; import javaeva.tools.Serializer; import javax.swing.ButtonGroup; @@ -229,7 +234,11 @@ public class EvAClient implements RemoteStateListener, Serializable { m_Frame.addWindowListener(new WindowAdapter() { public void windowClosing(WindowEvent e) { System.out.println("Closing JavaEvA Client. Bye!"); - System.exit(1); + m_Frame.dispose(); + Set keys = System.getenv().keySet(); + if (keys.contains("MATLAB")) { + System.out.println("Seems like Ive been started from Matlab: not killing JVM"); + } else System.exit(1); } }); @@ -241,6 +250,7 @@ public class EvAClient implements RemoteStateListener, Serializable { // m_mnuModule.setText("Select module"); // m_mnuModule.repaint(); + m_LogPanel.logMessage("Working directory is: " + System.getProperty("user.dir")); m_LogPanel.logMessage("Class path is: " + System.getProperty("java.class.path",".")); if (!(m_Frame.isVisible())) { @@ -271,7 +281,7 @@ public class EvAClient implements RemoteStateListener, Serializable { } /** - * The one and only main of the client programm. + * The one and only main of the client program. * * @param args command line parameters */ @@ -280,6 +290,7 @@ public class EvAClient implements RemoteStateListener, Serializable { System.out.println(EVAHELP.getSystemPropertyString()); } EvAClient Client = new EvAClient((args.length == 1) ? args[0] : null); + } // /** @@ -563,11 +574,24 @@ public class EvAClient implements RemoteStateListener, Serializable { e.printStackTrace(); EVAERROR.EXIT("Error while m_ComAdapter.GetModuleAdapter Host: " + e.getMessage()); } - if (newModuleAdapter == null) showLoadModules = true; + if (newModuleAdapter == null) { + URL baseDir = this.getClass().getClassLoader().getResource(""); + String cp = System.getProperty("java.class.path","."); + if (!cp.contains(baseDir.getPath())) { + System.err.println("classpath does not contain base directory!"); + System.err.println("adding base dir and trying again..."); + System.setProperty("java.class.path", cp + System.getProperty("path.separator") + baseDir.getPath()); + ReflectPackage.resetDynCP(); + m_ComAdapter.updateLocalMainAdapter(); + loadSpecificModule(selectedModule); // warning! end recursive call! handle with care! + return; + } + showLoadModules = true; + } else { newModuleAdapter.setConnection(!localMode); if (m_ComAdapter.isRunLocally()) { - // TODO in rmi-mode this doesnt work yet! + // TODO in rmi-mode this doesnt work yet! meaning e.g. that theres no content in the info log newModuleAdapter.addRemoteStateListener((RemoteStateListener)this); } try { @@ -693,12 +717,12 @@ public class EvAClient implements RemoteStateListener, Serializable { } public void performedRestart(String infoString) { - logMessage("Restarted " + infoString); + logMessage("Restarted processing " + infoString); startTime = System.currentTimeMillis(); } public void performedStart(String infoString) { - logMessage("Started " + infoString); + logMessage("Started processing " + infoString); startTime = System.currentTimeMillis(); } @@ -713,7 +737,8 @@ public class EvAClient implements RemoteStateListener, Serializable { * SwingUtilities.invokeLater(). In this case we're just * changing the progress bars value. */ - public void updateProgress(final int percent) { + public void updateProgress(final int percent, String msg) { + if (msg != null) logMessage(msg); if (this.m_ProgressBar != null) { Runnable doSetProgressBarValue = new Runnable() { public void run() { @@ -723,4 +748,10 @@ public class EvAClient implements RemoteStateListener, Serializable { SwingUtilities.invokeLater(doSetProgressBarValue); } } + +// +// public void test(Object o) { +// System.out.println("hello from EvAClient.test!"); +// System.out.println("object gives " + o); +// } } diff --git a/src/javaeva/client/EvAComAdapter.java b/src/javaeva/client/EvAComAdapter.java index 28917b6b..6278f532 100644 --- a/src/javaeva/client/EvAComAdapter.java +++ b/src/javaeva/client/EvAComAdapter.java @@ -74,6 +74,10 @@ public class EvAComAdapter extends ComAdapter { return newModuleAdapter; } + public void updateLocalMainAdapter() { + localMainAdapter = new EvAMainAdapterImpl(); + } + private EvAMainAdapter getLocalMainAdapter() { if (localMainAdapter == null) localMainAdapter = new EvAMainAdapterImpl(); return localMainAdapter; diff --git a/src/javaeva/client/RMIConnectionEvA.java b/src/javaeva/client/RMIConnectionEvA.java index 98bb7dde..5a547e5b 100644 --- a/src/javaeva/client/RMIConnectionEvA.java +++ b/src/javaeva/client/RMIConnectionEvA.java @@ -1,6 +1,5 @@ package javaeva.client; -import java.lang.reflect.InvocationHandler; import java.net.InetAddress; import java.net.UnknownHostException; diff --git a/src/javaeva/gui/BeanInspector.java b/src/javaeva/gui/BeanInspector.java index 5d31b2b3..684cd25c 100644 --- a/src/javaeva/gui/BeanInspector.java +++ b/src/javaeva/gui/BeanInspector.java @@ -127,25 +127,25 @@ public class BeanInspector { */ public static String toString(Object Target) { String ret = ""; + if (Target == null) return "null"; // try the object itself if (Target instanceof String) return (String)Target; // directly return a string object - Class type = Target.getClass(); if (type.isArray()) { // handle the array case - StringBuffer sbuf = new StringBuffer("["); + StringBuffer sbuf = new StringBuffer("[ "); int len = Array.getLength(Target); for (int i=0; i m_PointSetContainer; + private ScaledBorder m_Border; + private boolean m_log = false; + private boolean notifyNegLog = true; + private int m_x; + private int m_y; - private DPointIcon m_CurrentPointIcon; - /** - * - */ - public FunctionArea() {} + private DPointIcon m_CurrentPointIcon; + /** + * + */ + public FunctionArea() {} - /** - * - */ - public FunctionArea(String xname, String yname) { - super(); - setPreferredSize(new Dimension(600, 500)); - setVisibleRectangle(1, 1, 100000, 1000); - setAutoFocus(true); - setMinRectangle(0, 0, 1, 1); - //setAutoFocus(true); - m_Border = new ScaledBorder(); - m_Border.x_label = xname; //"App. " + Name + " func. calls"; - m_Border.y_label = yname; //"fitness"; - setBorder(m_Border); - setAutoGrid(true); - setGridVisible(true); - m_PointSetContainer = new ArrayList(20); - //new DMouseZoom( this ); - addPopup(); - repaint(); - notifyNegLog = true; - } + /** + * + */ + public FunctionArea(String xname, String yname) { + super(); + setPreferredSize(new Dimension(600, 500)); + setVisibleRectangle(1, 1, 100000, 1000); + setAutoFocus(true); + setMinRectangle(0, 0, 1, 1); + //setAutoFocus(true); + m_Border = new ScaledBorder(); + m_Border.x_label = xname; //"App. " + Name + " func. calls"; + m_Border.y_label = yname; //"fitness"; + setBorder(m_Border); + setAutoGrid(true); + setGridVisible(true); + m_PointSetContainer = new ArrayList(20); + //new DMouseZoom( this ); + addPopup(); + repaint(); + notifyNegLog = true; + } - /** - * - */ - public String getGraphInfo(int x, int y) { - String ret = ""; - if ((m_PointSetContainer == null) || (m_PointSetContainer.size() == 0)) - return ret; - int minindex = getNearestGraphIndex(x, y); - ret = ((GraphPointSet) (m_PointSetContainer.get(minindex))).getInfoString(); - return ret; - } + /** + * + */ + public String getGraphInfo(int x, int y) { + String ret = ""; + if ((m_PointSetContainer == null) || (m_PointSetContainer.size() == 0)) + return ret; + int minindex = getNearestGraphIndex(x, y); + ret = ((GraphPointSet) (m_PointSetContainer.get(minindex))).getInfoString(); + return ret; + } - /** - * - */ - public boolean isStatisticsGraph(int x, int y) { - boolean ret = false; - if ((m_PointSetContainer == null) || (m_PointSetContainer.size() == 0)) - return ret; - int minindex = getNearestGraphIndex(x, y); - ret = ((GraphPointSet) (m_PointSetContainer.get(minindex))).isStatisticsGraph(); - return ret; - } + /** + * + */ + public boolean isStatisticsGraph(int x, int y) { + boolean ret = false; + if ((m_PointSetContainer == null) || (m_PointSetContainer.size() == 0)) + return ret; + int minindex = getNearestGraphIndex(x, y); + ret = ((GraphPointSet) (m_PointSetContainer.get(minindex))).isStatisticsGraph(); + return ret; + } - /** - * - */ - private int getNearestGraphIndex(int x, int y) { - // get index of nearest Graph - double distmin = 10000000; - int minindex = -1; - DPoint point1 = getDMeasures().getDPoint(x, y); - DPoint point2 = null; - double dist = 0; - for (int i = 0; i < m_PointSetContainer.size(); i++) { - if (m_PointSetContainer.get(i)instanceof GraphPointSet) { - GraphPointSet pointset = (GraphPointSet) (m_PointSetContainer.get(i)); - point2 = pointset.getNearestDPoint(point1); - if (point2 == null) - continue; - if (point1 == null) - System.err.println("point1 == null"); + /** + * + */ + private int getNearestGraphIndex(int x, int y) { + // get index of nearest Graph + double distmin = 10000000; + int minindex = -1; + DPoint point1 = getDMeasures().getDPoint(x, y); + DPoint point2 = null; + double dist = 0; + for (int i = 0; i < m_PointSetContainer.size(); i++) { + if (m_PointSetContainer.get(i)instanceof GraphPointSet) { + GraphPointSet pointset = (GraphPointSet) (m_PointSetContainer.get(i)); + point2 = pointset.getNearestDPoint(point1); + if (point2 == null) + continue; + if (point1 == null) + System.err.println("point1 == null"); - dist = (point1.x - point2.x) * (point1.x - point2.x) + (point1.y - point2.y) * (point1.y - point2.y); - //System.out.println("dist="+dist+"i="+i); - if (dist < distmin) { - distmin = dist; - minindex = i; - } - } - } - return minindex; - } + dist = (point1.x - point2.x) * (point1.x - point2.x) + (point1.y - point2.y) * (point1.y - point2.y); + //System.out.println("dist="+dist+"i="+i); + if (dist < distmin) { + distmin = dist; + minindex = i; + } + } + } + return minindex; + } - /** - * - */ - private DPoint getNearestDPoint(int x, int y) { - // get index of nearest Graph - double distmin = 10000000; - DPoint ret = null; - DPoint point1 = getDMeasures().getDPoint(x, y); - DPoint point2 = null; - double dist = 0; - for (int i = 0; i < m_PointSetContainer.size(); i++) { - if (m_PointSetContainer.get(i)instanceof GraphPointSet) { - GraphPointSet pointset = (GraphPointSet) (m_PointSetContainer.get(i)); - point2 = pointset.getNearestDPoint(point1); - if (point2 == null) - continue; - dist = (point1.x - point2.x) * (point1.x - point2.x) + (point1.y - point2.y) * (point1.y - point2.y); - //System.out.println("dist="+dist+"i="+i); - if (dist < distmin) { - distmin = dist; - ret = point2; - } - if ((dist == distmin) && !(ret.getIcon()instanceof Chart2DDPointIconContent) && !(ret.getIcon()instanceof InterfaceSelectablePointIcon)) { - distmin = dist; - ret = point2; - } - } - } - return ret; - } + /** + * + */ + private DPoint getNearestDPoint(int x, int y) { + // get index of nearest Graph + double distmin = 10000000; + DPoint ret = null; + DPoint point1 = getDMeasures().getDPoint(x, y); + DPoint point2 = null; + double dist = 0; + for (int i = 0; i < m_PointSetContainer.size(); i++) { + if (m_PointSetContainer.get(i)instanceof GraphPointSet) { + GraphPointSet pointset = (GraphPointSet) (m_PointSetContainer.get(i)); + point2 = pointset.getNearestDPoint(point1); + if (point2 == null) + continue; + dist = (point1.x - point2.x) * (point1.x - point2.x) + (point1.y - point2.y) * (point1.y - point2.y); + //System.out.println("dist="+dist+"i="+i); + if (dist < distmin) { + distmin = dist; + ret = point2; + } + if ((dist == distmin) && !(ret.getIcon()instanceof Chart2DDPointIconContent) && !(ret.getIcon()instanceof InterfaceSelectablePointIcon)) { + distmin = dist; + ret = point2; + } + } + } + return ret; + } - /** - * - */ - public void exportToAscii() { - String[] s = null; - for (int i = 0; i < m_PointSetContainer.size(); i++) { - if (m_PointSetContainer.get(i)instanceof GraphPointSet) { - GraphPointSet set = (GraphPointSet) m_PointSetContainer.get(i); - String info = set.getInfoString(); - DPointSet pset = set.getConnectedPointSet(); - if (s == null) { - s = new String[pset.getSize() + 1]; - s[0] = "calls"; - } - s[0] = s[0] + " " + info; - for (int j = 1; j < s.length; j++) { - if (i == 0) - s[j] = "" + pset.getDPoint(j - 1).x; - try { - s[j] = s[j] + " " + pset.getDPoint(j - 1).y; - } catch (Exception e) { - s[j] += " "; - } - } - } - } - for (int j = 0; j < s.length; j++) { - System.out.println("s=" + s[j]); - } - // todo: Steichert hat einfach einen default namen genommen - SimpleDateFormat formatter = new SimpleDateFormat("E'_'yyyy.MM.dd'_'HH.mm.ss"); - String fname = "PlotExport_"+formatter.format(new Date()); -// System.out.println("Filename ??"); -// String fname = null; -// BufferedReader in = new BufferedReader(new InputStreamReader(System.in)); -// try { -// fname = in.readLine(); -// } catch (Exception e) { -// System.out.println("" + e.getMessage()); -// } - try { - File f = new File(fname + ".txt"); - f.createNewFile(); - PrintWriter Out = new PrintWriter(new FileOutputStream(f)); - for (int j = 0; j < s.length; j++) - Out.println(s[j]); - Out.flush(); - Out.close(); - } catch (Exception e) { - System.err.println("Error:" + e.getMessage()); - } + /** + * Export contained data to standard output. + * + */ + public void exportToAscii() { + exportToAscii((File)null); + } + + private String cleanBlanks(String str, Character rpl) { + return str.replace(' ', rpl); + } + + /** + * Export contained data to a file or to standard out if null is given. + * The given File will be overwritten! + * + * @param file a File instance or null to export to standard out + * @return true if the export succeeded, else false + */ + public boolean exportToAscii(File file) { + String[] s = null; + int maxSize = 0; + DPointSet maxSet = null; + for (int i = 0; i < m_PointSetContainer.size(); i++) { + // find maximum length of all point sets + if (m_PointSetContainer.get(i).getConnectedPointSet().getSize() > maxSize) { + maxSet = m_PointSetContainer.get(i).getConnectedPointSet(); + maxSize = maxSet.getSize(); + } + } + if (maxSize > 0) { // if there is any data, init string array and set x value column + s = new String[maxSize + 1]; + s[0] = "calls"; + for (int j = 1; j <= maxSize; j++) s[j] = "" + maxSet.getDPoint(j-1).x; + } else { + System.err.println("Error: no data to export"); + return true; + } + for (int i = 0; i < m_PointSetContainer.size(); i++) { + if (m_PointSetContainer.get(i) instanceof GraphPointSet) { + GraphPointSet set = (GraphPointSet) m_PointSetContainer.get(i); + DPointSet pset = set.getConnectedPointSet(); + s[0] = s[0] + " " + cleanBlanks(set.getInfoString(), '_'); // add column name + for (int j = 1; j < s.length; j++) { // add column data of place holder if no value in this set + if ((j-1) < pset.getSize()) s[j] = s[j] + " " + pset.getDPoint(j - 1).y; + else s[j] += " #"; +// try { +// s[j] = s[j] + " " + pset.getDPoint(j - 1).y; +// } catch (Exception e) { +// s[j] += " "; +// } + } + } else System.err.println("error in FunctionArea::exportToAscii"); + } + if (file == null) { + for (int j = 0; j < s.length; j++) { + System.out.println(s[j]); + } + return true; + } else try { + PrintWriter out = new PrintWriter(new FileOutputStream(file)); + for (int j = 0; j < s.length; j++) out.println(s[j]); + out.flush(); + out.close(); + return true; + } catch (Exception e) { + System.err.println("Error on data export:" + e.getMessage()); + return false; + } + } + + /** + * Export contained data to a file with a given String as prefix + * + * @param prefix file name prefix + * @return true if the export succeeded, else false + */ + public boolean exportToAscii(String prefix) { + SimpleDateFormat formatter = new SimpleDateFormat("E'_'yyyy.MM.dd'_'HH.mm.ss"); + String fname = prefix+"PlotExport_"+formatter.format(new Date())+".txt"; + try { + File f = new File(fname); + f.createNewFile(); + return exportToAscii(f); + } catch (Exception e) { + System.err.println("Error:" + e.getMessage()); + return false; + } - } + } - /** - * - */ - 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; - } - } - getGraphPointSet(GraphLabel).addDPoint(x, y); + /** + * + */ + 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; + } + } + getGraphPointSet(GraphLabel).addDPoint(x, y); - } + } - public void addGraphPointSet(GraphPointSet d) { - this.m_PointSetContainer.add(d); - } + public void addGraphPointSet(GraphPointSet d) { + this.m_PointSetContainer.add(d); + } - /** - * - */ - public void addGraph(int GraphLabel_1, int GraphLabel_2, boolean forceAdd) { - getGraphPointSet(GraphLabel_1).addGraph(getGraphPointSet(GraphLabel_2), this.getDMeasures(), forceAdd); - notifyNegLog = true; - } + /** + * + */ + public void addGraph(int GraphLabel_1, int GraphLabel_2, boolean forceAdd) { + getGraphPointSet(GraphLabel_1).addGraph(getGraphPointSet(GraphLabel_2), this.getDMeasures(), forceAdd); + notifyNegLog = true; + } - /** - * - */ - public void clearGraph(int GraphLabel) { - getGraphPointSet(GraphLabel).removeAllPoints(); - m_PointSetContainer.remove(getGraphPointSet(GraphLabel)); - repaint(); - notifyNegLog = true; - } + /** + * + */ + public void clearGraph(int GraphLabel) { + getGraphPointSet(GraphLabel).removeAllPoints(); + m_PointSetContainer.remove(getGraphPointSet(GraphLabel)); + repaint(); + notifyNegLog = true; + } - /** - * - */ - public void changeColorGraph(int GraphLabel) { - Color col = getGraphPointSet(GraphLabel).getColor(); - if (col == Color.black) - col = Color.red; - else - if (col == Color.red) - col = Color.blue; - else - if (col == Color.blue) - col = Color.red; - else - if (col == Color.red) - col = Color.black; - getGraphPointSet(GraphLabel).setColor(col); - repaint(); - } + /** + * + */ + public void changeColorGraph(int GraphLabel) { + Color col = getGraphPointSet(GraphLabel).getColor(); + if (col == Color.black) + col = Color.red; + else + if (col == Color.red) + col = Color.blue; + else + if (col == Color.blue) + col = Color.red; + else + if (col == Color.red) + col = Color.black; + getGraphPointSet(GraphLabel).setColor(col); + repaint(); + } - /** - * - */ - public void clearGraph(int x, int y) { - int index = getNearestGraphIndex(x, y); - if (index == -1) - return; - int GraphLabel = ((GraphPointSet) (this.m_PointSetContainer.get(index))).getGraphLabel(); - clearGraph(GraphLabel); - } + /** + * + */ + public void clearGraph(int x, int y) { + int index = getNearestGraphIndex(x, y); + if (index == -1) + return; + int GraphLabel = ((GraphPointSet) (this.m_PointSetContainer.get(index))).getGraphLabel(); + clearGraph(GraphLabel); + } - /** - * - */ - public void changeColorGraph(int x, int y) { - int index = getNearestGraphIndex(x, y); - if (index == -1) - return; - int GraphLabel = ((GraphPointSet) (this.m_PointSetContainer.get(index))).getGraphLabel(); - changeColorGraph(GraphLabel); - } + /** + * + */ + public void changeColorGraph(int x, int y) { + int index = getNearestGraphIndex(x, y); + if (index == -1) + return; + int GraphLabel = ((GraphPointSet) (this.m_PointSetContainer.get(index))).getGraphLabel(); + changeColorGraph(GraphLabel); + } - /** - * - */ - public void removePoint(int x, int y) { - DPoint point = getNearestDPoint(x, y); - int index = getNearestGraphIndex(x, y); - if (index == -1 || point == null) - return; - GraphPointSet pointset = (GraphPointSet) (this.m_PointSetContainer.get(index)); - pointset.removePoint(point); - } + /** + * + */ + public void removePoint(int x, int y) { + DPoint point = getNearestDPoint(x, y); + int index = getNearestGraphIndex(x, y); + if (index == -1 || point == null) + return; + GraphPointSet pointset = (GraphPointSet) (this.m_PointSetContainer.get(index)); + pointset.removePoint(point); + } - /** - * - */ - public void setInfoString(int GraphLabel, String Info, float stroke) { - getGraphPointSet(GraphLabel).setInfoString(Info, stroke); - } + /** + * + */ + public void setInfoString(int GraphLabel, String Info, float stroke) { + getGraphPointSet(GraphLabel).setInfoString(Info, stroke); + } - /** - * - */ - public void clearAll() { - this.removeAllDElements(); - for (int i = 0; i < m_PointSetContainer.size(); i++) - ((GraphPointSet) (m_PointSetContainer.get(i))).removeAllPoints(); - m_PointSetContainer.clear(); - notifyNegLog = true; - } + /** + * + */ + public void clearAll() { + this.removeAllDElements(); + for (int i = 0; i < m_PointSetContainer.size(); i++) + ((GraphPointSet) (m_PointSetContainer.get(i))).removeAllPoints(); + m_PointSetContainer.clear(); + notifyNegLog = true; + } - /** - * - */ - private GraphPointSet getGraphPointSet(int GraphLabel) { -// System.out.println("looping through " + m_PointSetContainer.size() + " point sets..."); - for (int i = 0; i < m_PointSetContainer.size(); i++) { - if (m_PointSetContainer.get(i) instanceof GraphPointSet) { - GraphPointSet xx = (GraphPointSet) (m_PointSetContainer.get(i)); -// System.out.println("looking at "+xx.getGraphLabel()); - if (xx.getGraphLabel() == GraphLabel) { -// System.out.println("match!"); - return xx; - } - } - } - // create new GraphPointSet - GraphPointSet NewPointSet = new GraphPointSet(GraphLabel, this); -// System.out.println("adding new point set " + GraphLabel); - //NewPointSet.setStroke(new BasicStroke( (float)1.0 )); - //addGraphPointSet(NewPointSet); already done within GraphPointSet!!! - return NewPointSet; - } + /** + * + */ + private GraphPointSet getGraphPointSet(int GraphLabel) { +// System.out.println("looping through " + m_PointSetContainer.size() + " point sets..."); + for (int i = 0; i < m_PointSetContainer.size(); i++) { + if (m_PointSetContainer.get(i) instanceof GraphPointSet) { + GraphPointSet xx = (GraphPointSet) (m_PointSetContainer.get(i)); +// System.out.println("looking at "+xx.getGraphLabel()); + if (xx.getGraphLabel() == GraphLabel) { +// System.out.println("match!"); + return xx; + } + } + } + // create new GraphPointSet + GraphPointSet NewPointSet = new GraphPointSet(GraphLabel, this); +// System.out.println("adding new point set " + GraphLabel); + //NewPointSet.setStroke(new BasicStroke( (float)1.0 )); + //addGraphPointSet(NewPointSet); already done within GraphPointSet!!! + return NewPointSet; + } - /** - * - */ - 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; - } - this.getGraphPointSet(GraphLabel).addDPoint(x, y); - this.getGraphPointSet(GraphLabel).setConnectedMode(false); - repaint(); - } + /** + * + */ + 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; + } + this.getGraphPointSet(GraphLabel).addDPoint(x, y); + this.getGraphPointSet(GraphLabel).setConnectedMode(false); + repaint(); + } - Color[] Colors = new Color[] {Color.black, Color.red, Color.blue, Color.green,Color.magenta, Color.orange, Color.pink, Color.yellow}; + 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) { - this.getGraphPointSet(GraphLabel).setColor(Colors[colorindex%Colors.length]); - } + public void setGraphColor(int GraphLabel,int colorindex) { + this.getGraphPointSet(GraphLabel).setColor(Colors[colorindex%Colors.length]); + } - /** - * Returns the number of points within the graph of the given label. - * - * @param index - * @return - */ - public int getPointCount(int label) { - return getGraphPointSet(label).getPointCount(); - } - - /** - * - */ - public int getContainerSize() { - return m_PointSetContainer.size(); - } + /** + * Returns the number of points within the graph of the given label. + * + * @param index + * @return + */ + public int getPointCount(int label) { + return getGraphPointSet(label).getPointCount(); + } - /** - * - */ - public DPointSet[] printPoints() { - DPointSet[] ret = new DPointSet[m_PointSetContainer.size()]; - for (int i = 0; i < m_PointSetContainer.size(); i++) { - System.out.println(""); - System.out.println("GraphPointSet No " + i); + /** + * + */ + public int getContainerSize() { + return m_PointSetContainer.size(); + } - ret[i] = ((GraphPointSet) m_PointSetContainer.get(i)).printPoints(); - } - return ret; + /** + * + */ + public DPointSet[] printPoints() { + DPointSet[] ret = new DPointSet[m_PointSetContainer.size()]; + for (int i = 0; i < m_PointSetContainer.size(); i++) { + System.out.println(""); + System.out.println("GraphPointSet No " + i); - } + ret[i] = ((GraphPointSet) m_PointSetContainer.get(i)).printPoints(); + } + return ret; - public DPointSet printPoints(int i) { - //for (int i = 0; i < m_PointSetContainer.size();i++) { - System.out.println(""); - System.out.println("GraphPointSet No " + i); + } - return ((GraphPointSet) m_PointSetContainer.get(i)).printPoints(); - //} - } + public DPointSet printPoints(int i) { + //for (int i = 0; i < m_PointSetContainer.size();i++) { + System.out.println(""); + System.out.println("GraphPointSet No " + i); - /** - * - */ - public void toggleLog() { - //System.out.println("ToggleLog log was: "+m_log); - if (m_log == false) { - setMinRectangle(0.001, 0.001, 1, 1); - //setVisibleRectangle( 0.001, 0.001, 100000, 1000 ); - setYScale(new Exp()); - m_Border.setSrcdY(Math.log(10)); - ((java.text.DecimalFormat) m_Border.format_y).applyPattern("0.###E0"); - m_log = true; - } else { - m_log = false; - setYScale(null); - ScaledBorder buffer = m_Border; - m_Border = new ScaledBorder(); - m_Border.x_label = buffer.x_label; //"App. " + Name + " func. calls"; - m_Border.y_label = buffer.y_label; //"fitness"; - setBorder(m_Border); - } - repaint(); - } + return ((GraphPointSet) m_PointSetContainer.get(i)).printPoints(); + //} + } - /** - * Causes all PointSets to interupt the connected painting at the - * current position. - */ - public void jump() { - for (int i = 0; i < m_PointSetContainer.size(); i++) - ((GraphPointSet) (m_PointSetContainer.get(i))).jump(); - } + /** + * + */ + public void toggleLog() { + //System.out.println("ToggleLog log was: "+m_log); + if (m_log == false) { + setMinRectangle(0.001, 0.001, 1, 1); + //setVisibleRectangle( 0.001, 0.001, 100000, 1000 ); + setYScale(new Exp()); + m_Border.setSrcdY(Math.log(10)); + ((java.text.DecimalFormat) m_Border.format_y).applyPattern("0.###E0"); + m_log = true; + } else { + m_log = false; + setYScale(null); + ScaledBorder buffer = m_Border; + m_Border = new ScaledBorder(); + m_Border.x_label = buffer.x_label; //"App. " + Name + " func. calls"; + m_Border.y_label = buffer.y_label; //"fitness"; + setBorder(m_Border); + } + repaint(); + } - /** - */ - public Object openObject() { - if (m_FileChooser == null) - createFileChooser(); - int returnVal = m_FileChooser.showOpenDialog(this); - if (returnVal == JFileChooser.APPROVE_OPTION) { - File selected = m_FileChooser.getSelectedFile(); - try { - ObjectInputStream oi = new ObjectInputStream(new BufferedInputStream(new FileInputStream(selected))); - Object obj = oi.readObject(); - oi.close(); + /** + * Causes all PointSets to interupt the connected painting at the + * current position. + */ + public void jump() { + for (int i = 0; i < m_PointSetContainer.size(); i++) + ((GraphPointSet) (m_PointSetContainer.get(i))).jump(); + } - Object[] objects = (Object[]) obj; - for (int i = 0; i < objects.length; i++) { - GraphPointSet xx = ((GraphPointSet.SerPointSet) objects[i]).getGraphPointSet(); - xx.initGraph(this); - addGraphPointSet(xx); - } - repaint(); - return obj; - } catch (Exception ex) { - JOptionPane.showMessageDialog(this, - "Couldn't read object: " - + selected.getName() - + "\n" + ex.getMessage(), - "Open object file", - JOptionPane.ERROR_MESSAGE); - } - } - return null; - } - - /** - * - */ - public void saveObject() { - Object[] object = new Object[m_PointSetContainer.size()]; - for (int i = 0; i < m_PointSetContainer.size(); i++) { - object[i] = ((GraphPointSet) m_PointSetContainer.get(i)).getSerPointSet(); - } - if (m_FileChooser == null) - createFileChooser(); - int returnVal = m_FileChooser.showSaveDialog(this); - if (returnVal == JFileChooser.APPROVE_OPTION) { - File sFile = m_FileChooser.getSelectedFile(); - try { - ObjectOutputStream oo = new ObjectOutputStream(new BufferedOutputStream(new FileOutputStream(sFile))); - oo.writeObject(object); - oo.close(); - } catch (IOException ex) { - JOptionPane.showMessageDialog(this, - "Couldn't write to file: " - + sFile.getName() - + "\n" + ex.getMessage(), - "Save object", - JOptionPane.ERROR_MESSAGE); - } - } - } - - /** - * - */ - protected void createFileChooser() { - m_FileChooser = new JFileChooser(new File("/resources")); - m_FileChooser.setFileSelectionMode(JFileChooser.FILES_ONLY); - } - - /** Add a popup menu for displaying certain information. - */ - private void addPopup() { - addMouseListener(new MouseAdapter() { - public void mouseClicked(MouseEvent e) { - if ((e.getModifiers() & InputEvent.BUTTON1_MASK) == InputEvent.BUTTON1_MASK) { - // do nothing - } else { - JPopupMenu GraphMenu = new JPopupMenu(); - m_x = e.getX(); - m_y = e.getY(); - - // The first info element - JMenuItem Info = new JMenuItem("Graph Info: " + getGraphInfo(e.getX(), e.getY())); - Info.addActionListener(new ActionListener() { - // - public void actionPerformed(ActionEvent ee) { - DPoint temp = FunctionArea.this.getDMeasures().getDPoint(FunctionArea.this.m_x, FunctionArea.this.m_y); - DPointIcon icon1 = new DPointIcon() { - public void paint(Graphics g) { - g.drawLine( -2, 0, 2, 0); - g.drawLine(0, 0, 0, 4); - } - - public DBorder getDBorder() { - return new DBorder(4, 4, 4, 4); - } - }; - temp.setIcon(icon1); - FunctionArea.this.addDElement(temp); - } - }); - GraphMenu.add(Info); - if (m_RefPointListener != null) { - DPoint temp = getDMeasures().getDPoint(m_x, m_y); - JMenuItem refPoint = new JMenuItem("Reference Point:("+temp.x+"/"+temp.y+")"); - refPoint.addActionListener(new ActionListener() { - public void actionPerformed(ActionEvent ee) { - DPoint temp = getDMeasures().getDPoint(m_x, m_y); - double[] point = new double[2]; - point[0] = temp.x; - point[1] = temp.y; - m_RefPointListener.refPointGiven(point); - } - }); - GraphMenu.add(refPoint); - } - - // darn this point is an empty copy !! - DPoint point = getNearestDPoint(e.getX(), e.getY()); - - if (point != null) { - JMenuItem InfoXY = new JMenuItem("(" + point.x + "/" + point.y+")"); - Info.addActionListener(new ActionListener() { - public void actionPerformed(ActionEvent ee) { - } - }); - GraphMenu.add(InfoXY); - - if (point.getIcon()instanceof InterfaceSelectablePointIcon) { - m_CurrentPointIcon = point.getIcon(); - if (((InterfaceSelectablePointIcon)m_CurrentPointIcon).getSelectionListener() != null) { - JMenuItem select; - AbstractEAIndividual indy = ((InterfaceSelectablePointIcon)m_CurrentPointIcon).getEAIndividual(); - if (indy.isMarked()) select = new JMenuItem("Deselect individual"); - else select = new JMenuItem("Select individual"); - select.addActionListener(new ActionListener() { - public void actionPerformed(ActionEvent ee) { - ((InterfaceSelectablePointIcon)m_CurrentPointIcon).getSelectionListener().individualSelected(((InterfaceSelectablePointIcon)m_CurrentPointIcon).getEAIndividual()); - } - }); - GraphMenu.add(select); - } - } - - if (point.getIcon()instanceof InterfaceDPointWithContent) { - m_CurrentPointIcon = point.getIcon(); - JMenuItem drawIndy = new JMenuItem("Show individual"); - drawIndy.addActionListener(new ActionListener() { - public void actionPerformed(ActionEvent ee) { - ((InterfaceDPointWithContent)m_CurrentPointIcon).showIndividual(); - } - }); - GraphMenu.add(drawIndy); - } - - } - if (FunctionArea.this.m_PointSetContainer.size() > 0) { - JMenuItem removeGraph = new JMenuItem("Remove graph"); - removeGraph.addActionListener(new ActionListener() { - public void actionPerformed(ActionEvent ee) { - clearGraph(FunctionArea.this.m_x, FunctionArea.this.m_y); - } - }); - GraphMenu.add(removeGraph); - } - if (FunctionArea.this.m_PointSetContainer.size() > 0) { - JMenuItem changecolorGraph = new JMenuItem("Change color"); - changecolorGraph.addActionListener(new ActionListener() { - public void actionPerformed(ActionEvent ee) { - changeColorGraph(FunctionArea.this.m_x, FunctionArea.this.m_y); - } - }); - GraphMenu.add(changecolorGraph); - } - if (FunctionArea.this.m_PointSetContainer.size() > 0) { - JMenuItem removePoint = new JMenuItem("Remove point"); - removePoint.addActionListener(new ActionListener() { - public void actionPerformed(ActionEvent ee) { - removePoint(FunctionArea.this.m_x, FunctionArea.this.m_y); - } - }); - GraphMenu.add(removePoint); - } -// if (isStatisticsGraph(e.getX(),e.getY())==true) { -// if (getVar(e.getX(),e.getY())==false) { -// JMenuItem showVar = new JMenuItem("Show varianz "); -// showVar.addActionListener(new ActionListener() { -// // -// public void actionPerformed(ActionEvent ee) { -// setVar(m_x,m_y,true); -// } -// }); -// GraphMenu.add(showVar); +// /** +// */ +// public Object openObject() { +// if (m_FileChooser == null) +// createFileChooser(); +// int returnVal = m_FileChooser.showOpenDialog(this); +// if (returnVal == JFileChooser.APPROVE_OPTION) { +// File selected = m_FileChooser.getSelectedFile(); +// try { +// ObjectInputStream oi = new ObjectInputStream(new BufferedInputStream(new FileInputStream(selected))); +// Object obj = oi.readObject(); +// oi.close(); // -// } -// else { -// JMenuItem hideVar = new JMenuItem("Hide varianz "); -// hideVar.addActionListener(new ActionListener() { -// // -// public void actionPerformed(ActionEvent ee) { -// setVar(m_x,m_y,false); -// } -// }); -// GraphMenu.add(hideVar); -// } -// } - GraphMenu.show(FunctionArea.this, e.getX(), e.getY()); - } - } - }); - } +// Object[] objects = (Object[]) obj; +// for (int i = 0; i < objects.length; i++) { +// GraphPointSet xx = ((GraphPointSet.SerPointSet) objects[i]).getGraphPointSet(); +// xx.initGraph(this); +// addGraphPointSet(xx); +// } +// repaint(); +// return obj; +// } catch (Exception ex) { +// JOptionPane.showMessageDialog(this, +// "Couldn't read object: " +// + selected.getName() +// + "\n" + ex.getMessage(), +// "Open object file", +// JOptionPane.ERROR_MESSAGE); +// } +// } +// return null; +// } - /** This method allows to add a selection listner to the PointIcon - * it should need more than one listener to this abstruse event - * @param a The selection listener - */ - public void addRefPointSelectionListener(InterfaceRefPointListener a) { - this.m_RefPointListener = a; - } +// /** +// * +// */ +// public void saveObject() { +// Object[] object = new Object[m_PointSetContainer.size()]; +// for (int i = 0; i < m_PointSetContainer.size(); i++) { +// object[i] = ((GraphPointSet) m_PointSetContainer.get(i)).getSerPointSet(); +// } +// if (m_FileChooser == null) +// createFileChooser(); +// int returnVal = m_FileChooser.showSaveDialog(this); +// if (returnVal == JFileChooser.APPROVE_OPTION) { +// File sFile = m_FileChooser.getSelectedFile(); +// try { +// ObjectOutputStream oo = new ObjectOutputStream(new BufferedOutputStream(new FileOutputStream(sFile))); +// oo.writeObject(object); +// oo.close(); +// } catch (IOException ex) { +// JOptionPane.showMessageDialog(this, +// "Couldn't write to file: " +// + sFile.getName() +// + "\n" + ex.getMessage(), +// "Save object", +// JOptionPane.ERROR_MESSAGE); +// } +// } +// } - /** This method returns the selection listner to the PointIcon - * @return InterfaceSelectionListener - */ - public InterfaceRefPointListener getRefPointSelectionListener() { - return this.m_RefPointListener; - } + /** + * + */ + protected void createFileChooser() { + m_FileChooser = new JFileChooser(new File("/resources")); + m_FileChooser.setFileSelectionMode(JFileChooser.FILES_ONLY); + } - /** This method allows to remove the selection listner to the PointIcon - */ - public void removeRefPointSelectionListeners() { - this.m_RefPointListener = null; - } + /** Add a popup menu for displaying certain information. + */ + private void addPopup() { + addMouseListener(new MouseAdapter() { + public void mouseClicked(MouseEvent e) { + if ((e.getModifiers() & InputEvent.BUTTON1_MASK) == InputEvent.BUTTON1_MASK) { + // do nothing + } else { + JPopupMenu GraphMenu = new JPopupMenu(); + m_x = e.getX(); + m_y = e.getY(); + + // The first info element + JMenuItem Info = new JMenuItem("Graph Info: " + getGraphInfo(e.getX(), e.getY())); + Info.addActionListener(new ActionListener() { + // + public void actionPerformed(ActionEvent ee) { + DPoint temp = FunctionArea.this.getDMeasures().getDPoint(FunctionArea.this.m_x, FunctionArea.this.m_y); + DPointIcon icon1 = new DPointIcon() { + public void paint(Graphics g) { + g.drawLine( -2, 0, 2, 0); + g.drawLine(0, 0, 0, 4); + } + + public DBorder getDBorder() { + return new DBorder(4, 4, 4, 4); + } + }; + temp.setIcon(icon1); + FunctionArea.this.addDElement(temp); + } + }); + GraphMenu.add(Info); + if (m_RefPointListener != null) { + DPoint temp = getDMeasures().getDPoint(m_x, m_y); + JMenuItem refPoint = new JMenuItem("Reference Point:("+temp.x+"/"+temp.y+")"); + refPoint.addActionListener(new ActionListener() { + public void actionPerformed(ActionEvent ee) { + DPoint temp = getDMeasures().getDPoint(m_x, m_y); + double[] point = new double[2]; + point[0] = temp.x; + point[1] = temp.y; + m_RefPointListener.refPointGiven(point); + } + }); + GraphMenu.add(refPoint); + } + + // darn this point is an empty copy !! + DPoint point = getNearestDPoint(e.getX(), e.getY()); + + if (point != null) { + JMenuItem InfoXY = new JMenuItem("(" + point.x + "/" + point.y+")"); + Info.addActionListener(new ActionListener() { + public void actionPerformed(ActionEvent ee) { + } + }); + GraphMenu.add(InfoXY); + + if (point.getIcon()instanceof InterfaceSelectablePointIcon) { + m_CurrentPointIcon = point.getIcon(); + if (((InterfaceSelectablePointIcon)m_CurrentPointIcon).getSelectionListener() != null) { + JMenuItem select; + AbstractEAIndividual indy = ((InterfaceSelectablePointIcon)m_CurrentPointIcon).getEAIndividual(); + if (indy.isMarked()) select = new JMenuItem("Deselect individual"); + else select = new JMenuItem("Select individual"); + select.addActionListener(new ActionListener() { + public void actionPerformed(ActionEvent ee) { + ((InterfaceSelectablePointIcon)m_CurrentPointIcon).getSelectionListener().individualSelected(((InterfaceSelectablePointIcon)m_CurrentPointIcon).getEAIndividual()); + } + }); + GraphMenu.add(select); + } + } + + if (point.getIcon()instanceof InterfaceDPointWithContent) { + m_CurrentPointIcon = point.getIcon(); + JMenuItem drawIndy = new JMenuItem("Show individual"); + drawIndy.addActionListener(new ActionListener() { + public void actionPerformed(ActionEvent ee) { + ((InterfaceDPointWithContent)m_CurrentPointIcon).showIndividual(); + } + }); + GraphMenu.add(drawIndy); + } + + } + if (FunctionArea.this.m_PointSetContainer.size() > 0) { + JMenuItem removeGraph = new JMenuItem("Remove graph"); + removeGraph.addActionListener(new ActionListener() { + public void actionPerformed(ActionEvent ee) { + clearGraph(FunctionArea.this.m_x, FunctionArea.this.m_y); + } + }); + GraphMenu.add(removeGraph); + } + if (FunctionArea.this.m_PointSetContainer.size() > 0) { + JMenuItem changecolorGraph = new JMenuItem("Change color"); + changecolorGraph.addActionListener(new ActionListener() { + public void actionPerformed(ActionEvent ee) { + changeColorGraph(FunctionArea.this.m_x, FunctionArea.this.m_y); + } + }); + GraphMenu.add(changecolorGraph); + } + if (FunctionArea.this.m_PointSetContainer.size() > 0) { + JMenuItem removePoint = new JMenuItem("Remove point"); + removePoint.addActionListener(new ActionListener() { + public void actionPerformed(ActionEvent ee) { + removePoint(FunctionArea.this.m_x, FunctionArea.this.m_y); + } + }); + GraphMenu.add(removePoint); + } +// if (isStatisticsGraph(e.getX(),e.getY())==true) { +// if (getVar(e.getX(),e.getY())==false) { +// JMenuItem showVar = new JMenuItem("Show varianz "); +// showVar.addActionListener(new ActionListener() { +// // +// public void actionPerformed(ActionEvent ee) { +// setVar(m_x,m_y,true); +// } +// }); +// GraphMenu.add(showVar); + +// } +// else { +// JMenuItem hideVar = new JMenuItem("Hide varianz "); +// hideVar.addActionListener(new ActionListener() { +// // +// public void actionPerformed(ActionEvent ee) { +// setVar(m_x,m_y,false); +// } +// }); +// GraphMenu.add(hideVar); +// } +// } + GraphMenu.show(FunctionArea.this, e.getX(), e.getY()); + } + } + }); + } + + /** This method allows to add a selection listner to the PointIcon + * it should need more than one listener to this abstruse event + * @param a The selection listener + */ + public void addRefPointSelectionListener(InterfaceRefPointListener a) { + this.m_RefPointListener = a; + } + + /** This method returns the selection listner to the PointIcon + * @return InterfaceSelectionListener + */ + public InterfaceRefPointListener getRefPointSelectionListener() { + return this.m_RefPointListener; + } + + /** This method allows to remove the selection listner to the PointIcon + */ + public void removeRefPointSelectionListeners() { + this.m_RefPointListener = null; + } } diff --git a/src/javaeva/gui/GenericObjectEditor.java b/src/javaeva/gui/GenericObjectEditor.java index 57ba800a..d396d4f0 100644 --- a/src/javaeva/gui/GenericObjectEditor.java +++ b/src/javaeva/gui/GenericObjectEditor.java @@ -442,12 +442,13 @@ public class GenericObjectEditor implements PropertyEditor { // setObject(dummy); // } else { if (TRACE) System.out.println(className); - Object n = (Object)Class.forName(className, true, ClassLoader.getSystemClassLoader()).newInstance(); + Object n = (Object)Class.forName(className, true, this.getClass().getClassLoader()).newInstance(); n = (Object)Class.forName(className).newInstance(); setObject(n); // } } catch (Exception ex) { - System.out.println("Exeption in itemStateChanged "+ex.getMessage()); + System.err.println("Exeption in itemStateChanged "+ex.getMessage()); + System.err.println("Classpath is " + System.getProperty("java.class.path")); ex.printStackTrace(); m_ObjectChooser.hidePopup(); m_ObjectChooser.setSelectedIndex(0); diff --git a/src/javaeva/gui/GraphPointSet.java b/src/javaeva/gui/GraphPointSet.java index f6d4c40d..d14bf197 100644 --- a/src/javaeva/gui/GraphPointSet.java +++ b/src/javaeva/gui/GraphPointSet.java @@ -468,64 +468,66 @@ public class GraphPointSet { m_Stroke = stroke; //setStroke(new BasicStroke( m_Stroke )); } - /** - * - */ - public SerPointSet getSerPointSet () { - SerPointSet ret= new SerPointSet(this); - return ret; - } - /** - * - */ - class SerPointSet implements Serializable { - private String m_InfoString; - private int m_GraphLabel; - private Color m_Color; - private float m_Stroke; - private PointSet m_PointSet_1; - private PointSet m_PointSet_2; - private PointSet m_PointSet_3; - private PointSet m_ConnectedPointSet; - private PointSet m_VarPointSetPlus; - private PointSet m_VarPointSetMinus; - private boolean m_isStatisticeGraph; - private boolean m_showVarianz; - /** - * - */ - public SerPointSet (GraphPointSet Source) { - m_InfoString = Source.m_InfoString; - m_GraphLabel = Source.m_GraphLabel; - m_Color = Source.m_Color; - m_Stroke = Source.m_Stroke; - m_isStatisticeGraph = Source.m_isStatisticsGraph; - - // save the connected points - m_ConnectedPointSet = new PointSet(Source.getConnectedPointSet()); -// m_PointSet_1 = new PointSet (Source.m_PointSet_1); -// m_PointSet_2 = new PointSet (Source.m_PointSet_2); -// m_PointSet_3 = new PointSet (Source.m_PointSet_3); - } - /** - * - */ - public GraphPointSet getGraphPointSet () { - GraphPointSet ret = new GraphPointSet(10,m_GraphLabel); - ret.setInfoString(this.m_InfoString,this.m_Stroke); - ret.setColor(this.m_Color); - ret.m_Color = m_Color; - ret.m_Stroke = m_Stroke; - ret.m_isStatisticsGraph = m_isStatisticeGraph; - //@todo why doesn't that work!? -// ret.m_ConnectedPointSet = (DPointSetMultiIcon)m_ConnectedPointSet; -// ret.m_PointSet_1 = m_PointSet_1.getDPointSet(); -// ret.m_PointSet_2 = m_PointSet_2.getDPointSet(); -// ret.m_PointSet_3 = m_PointSet_3.getDPointSet(); - ret.m_ConnectedPointSet.setConnected(true); - return ret; - } - } +// /** +// * +// */ +// public SerPointSet getSerPointSet () { +// SerPointSet ret= new SerPointSet(this); +// return ret; +// } +// +// /** +// * +// */ +// class SerPointSet implements Serializable { +// private String m_InfoString; +// private int m_GraphLabel; +// private Color m_Color; +// private float m_Stroke; +//// private PointSet m_PointSet_1; +//// private PointSet m_PointSet_2; +//// private PointSet m_PointSet_3; +// private PointSet m_ConnectedPointSet; +//// private PointSet m_VarPointSetPlus; +//// private PointSet m_VarPointSetMinus; +// private boolean m_isStatisticeGraph; +//// private boolean m_showVarianz; +// /** +// * +// */ +// public SerPointSet (GraphPointSet Source) { +// m_InfoString = Source.m_InfoString; +// m_GraphLabel = Source.m_GraphLabel; +// m_Color = Source.m_Color; +// m_Stroke = Source.m_Stroke; +// m_isStatisticeGraph = Source.m_isStatisticsGraph; +// +// // save the connected points +// m_ConnectedPointSet = new PointSet(Source.getConnectedPointSet()); +//// m_PointSet_1 = new PointSet (Source.m_PointSet_1); +//// m_PointSet_2 = new PointSet (Source.m_PointSet_2); +//// m_PointSet_3 = new PointSet (Source.m_PointSet_3); +// } +// /** +// * +// */ +// public GraphPointSet getGraphPointSet () { +// GraphPointSet ret = new GraphPointSet(10,m_GraphLabel); +// ret.setInfoString(this.m_InfoString,this.m_Stroke); +// ret.setColor(this.m_Color); +// ret.m_Color = m_Color; +// ret.m_Stroke = m_Stroke; +// ret.m_isStatisticsGraph = m_isStatisticeGraph; +// //@todo why doesn't that work!? +//// ret.m_ConnectedPointSet = (DPointSetMultiIcon)m_ConnectedPointSet; +//// ret.m_PointSet_1 = m_PointSet_1.getDPointSet(); +//// ret.m_PointSet_2 = m_PointSet_2.getDPointSet(); +//// ret.m_PointSet_3 = m_PointSet_3.getDPointSet(); +// ret.m_ConnectedPointSet.setConnected(true); +// return ret; +// } +// } + /** * */ @@ -562,18 +564,19 @@ public class GraphPointSet { public int getSize() { return m_X.length; } - /** - * - */ - public DPointSet printPoints() { - for (int i = 0; i < m_ConnectedPointSet.getSize();i++) { - DPoint p = m_ConnectedPointSet.getDPoint(i); - double x = p.x; - double y = p.y; - //System.out.println("point "+i+ " x= "+x+"y= "+y); - } - return m_ConnectedPointSet.getDPointSet(); - } + +// /** +// * +// */ +// public DPointSet printPoints() { +// for (int i = 0; i < m_ConnectedPointSet.getSize();i++) { +// DPoint p = m_ConnectedPointSet.getDPoint(i); +// double x = p.x; +// double y = p.y; +// //System.out.println("point "+i+ " x= "+x+"y= "+y); +// } +// return m_ConnectedPointSet.getDPointSet(); +// } } } diff --git a/src/javaeva/gui/JModuleGeneralPanel.java b/src/javaeva/gui/JModuleGeneralPanel.java index 5e13db04..6379eecf 100644 --- a/src/javaeva/gui/JModuleGeneralPanel.java +++ b/src/javaeva/gui/JModuleGeneralPanel.java @@ -185,7 +185,7 @@ public class JModuleGeneralPanel implements RemoteStateListener, Serializable { public void performedRestart(String infoString) { } - public void updateProgress(final int percent) { + public void updateProgress(final int percent, String msg) { } /** diff --git a/src/javaeva/gui/JTextoutputFrame.java b/src/javaeva/gui/JTextoutputFrame.java index 8e86fd34..c2ee490f 100644 --- a/src/javaeva/gui/JTextoutputFrame.java +++ b/src/javaeva/gui/JTextoutputFrame.java @@ -40,12 +40,14 @@ public class JTextoutputFrame implements JTextoutputFrameInterface, protected String m_Name ="undefined"; private transient JTextArea m_TextArea; private boolean m_firstprint = true; + private final JFrame frame; /** * */ public JTextoutputFrame(String Title) { if (TRACE) System.out.println("JTextoutputFrame Constructor"); m_Name = Title; + frame = new JEFrame(m_Name); } /** * @@ -59,6 +61,19 @@ public class JTextoutputFrame implements JTextoutputFrameInterface, m_TextArea.append (Text+"\n"); m_TextArea.repaint(); } + + public void setShow(boolean bShow) { + if (frame.isVisible() != bShow) { + if (frame.isVisible()) { + frame.dispose(); + m_TextArea.setText(null); + } else { + if (m_firstprint) createFrame(); + else frame.setVisible(true); + } + } + } + /** * */ @@ -70,13 +85,13 @@ public class JTextoutputFrame implements JTextoutputFrameInterface, m_TextArea.setWrapStyleWord(true); m_TextArea.setEditable(false); m_TextArea.setCaretPosition(0); - final JFrame frame = new JEFrame(m_Name); + BasicResourceLoader loader = BasicResourceLoader.instance(); byte[] bytes = loader.getBytesFromResourceLocation(EvAClient.iconLocation); try { frame.setIconImage(Toolkit.getDefaultToolkit().createImage(bytes)); } catch (java.lang.NullPointerException e) { - System.out.println("Could not find JavaEvA icon, please move rescoure folder to working directory!"); + System.out.println("Could not find JavaEvA icon, please move resource folder to working directory!"); } frame.addWindowListener(new WindowAdapter() { public void windowClosing(WindowEvent e) { diff --git a/src/javaeva/gui/JTextoutputFrameInterface.java b/src/javaeva/gui/JTextoutputFrameInterface.java index 802b3a31..eef53e02 100644 --- a/src/javaeva/gui/JTextoutputFrameInterface.java +++ b/src/javaeva/gui/JTextoutputFrameInterface.java @@ -1,4 +1,7 @@ package javaeva.gui; + +import javaeva.server.stat.InterfaceTextListener; + /* * Title: JavaEvA * Description: @@ -18,6 +21,6 @@ package javaeva.gui; /** * */ -public interface JTextoutputFrameInterface { - public void print (String Text); +public interface JTextoutputFrameInterface extends InterfaceTextListener { + public void setShow(boolean bShow); } \ No newline at end of file diff --git a/src/javaeva/gui/Plot.java b/src/javaeva/gui/Plot.java index efd3631e..2e936e35 100644 --- a/src/javaeva/gui/Plot.java +++ b/src/javaeva/gui/Plot.java @@ -54,376 +54,418 @@ import wsi.ra.tool.BasicResourceLoader; */ public class Plot implements PlotInterface, Serializable { - public static boolean TRACE = false; - private JFileChooser m_FileChooser; - private JPanel m_ButtonPanel; - private String m_PlotName; - private String m_xname; - private String m_yname; - protected FunctionArea m_PlotArea; - protected JFrame m_Frame; - - /** - * You might want to try to assign the x-range as x and y-range as y array parameters. - */ - public Plot(String PlotName,String xname,String yname,double[] x,double[] y) { - if (TRACE) System.out.println("Constructor Plot "+PlotName); - m_xname = xname; - m_yname = yname; - m_PlotName = PlotName; - init(); - DPointSet points = new DPointSet(); - for (int i=0;i this.m_Range[mutationIndex][1]) this.m_Genotype[mutationIndex] = this.m_Range[mutationIndex][1]; } -// /** This method will set the range of the double attributes. If range.length -// * does not equal doubledata.length only range[i] will be used to set all -// * ranges. -// * @param range The new range for the double data. -// */ -// public void SetDoubleRange(double[][] range) { -// if (range.length != this.m_Range.length) { -// System.out.println("Warning: Trying to set a range of length " + range.length + " to a vector of length " -// + this.m_Range.length + "!\n Use method setDoubleDataLength first!"); -// } -// for (int i = 0; ((i < this.m_Range.length) && (i < range.length)); i++) { -// this.m_Range[i][0] = (int)range[i][0]; -// this.m_Range[i][1] = (int)range[i][1]; -// } -// } - /** This method will return the range for all double attributes. * @return The range array. */ diff --git a/src/javaeva/server/go/individuals/ESIndividualPermutationData.java b/src/javaeva/server/go/individuals/ESIndividualPermutationData.java index 86f0da7f..5dc81920 100644 --- a/src/javaeva/server/go/individuals/ESIndividualPermutationData.java +++ b/src/javaeva/server/go/individuals/ESIndividualPermutationData.java @@ -1,5 +1,6 @@ package javaeva.server.go.individuals; +import javaeva.server.go.IndividualInterface; import javaeva.server.go.operators.crossover.CrossoverESDefault; import javaeva.server.go.operators.mutation.InterfaceMutation; import javaeva.server.go.operators.mutation.MutateESGlobal; @@ -384,7 +385,7 @@ public class ESIndividualPermutationData extends AbstractEAIndividual implements } return res; } - + /********************************************************************************************************************** * These are for GUI */ diff --git a/src/javaeva/server/go/mocco/MOCCOParameterizeGDF.java b/src/javaeva/server/go/mocco/MOCCOParameterizeGDF.java index 475b8718..ba27a8dd 100644 --- a/src/javaeva/server/go/mocco/MOCCOParameterizeGDF.java +++ b/src/javaeva/server/go/mocco/MOCCOParameterizeGDF.java @@ -1,7 +1,7 @@ package javaeva.server.go.mocco; import javaeva.server.go.MOCCOStandalone; -import javaeva.server.go.TerminatorInterface; +import javaeva.server.go.InterfaceTerminator; import javaeva.server.go.individuals.AbstractEAIndividual; import javaeva.server.go.operators.moso.MOSOWeightedFitness; import javaeva.server.go.problems.AbstractMultiObjectiveOptimizationProblem; @@ -151,9 +151,9 @@ public class MOCCOParameterizeGDF extends MOCCOPhase implements InterfaceProcess try { editor.m_Value = this.m_Mocco.m_State.m_Terminator; editor.m_Editor = PropertyEditorProvider.findEditor(editor.m_Value.getClass()); - if (editor.m_Editor == null) editor.m_Editor = PropertyEditorProvider.findEditor(TerminatorInterface.class); + if (editor.m_Editor == null) editor.m_Editor = PropertyEditorProvider.findEditor(InterfaceTerminator.class); if (editor.m_Editor instanceof GenericObjectEditor) - ((GenericObjectEditor) editor.m_Editor).setClassType(TerminatorInterface.class); + ((GenericObjectEditor) editor.m_Editor).setClassType(InterfaceTerminator.class); editor.m_Editor.setValue(editor.m_Value); this.findViewFor(editor); if (editor.m_View != null) editor.m_View.repaint(); diff --git a/src/javaeva/server/go/mocco/MOCCOParameterizeMO.java b/src/javaeva/server/go/mocco/MOCCOParameterizeMO.java index 4ed8b441..86db7744 100644 --- a/src/javaeva/server/go/mocco/MOCCOParameterizeMO.java +++ b/src/javaeva/server/go/mocco/MOCCOParameterizeMO.java @@ -1,7 +1,7 @@ package javaeva.server.go.mocco; import javaeva.server.go.MOCCOStandalone; -import javaeva.server.go.TerminatorInterface; +import javaeva.server.go.InterfaceTerminator; import javaeva.server.go.populations.Population; import javaeva.server.go.strategies.GeneticAlgorithm; import javaeva.server.go.strategies.InterfaceOptimizer; @@ -108,9 +108,9 @@ public class MOCCOParameterizeMO extends MOCCOPhase implements InterfaceProcessE try { editor.m_Value = this.m_Mocco.m_State.m_Terminator; editor.m_Editor = PropertyEditorProvider.findEditor(editor.m_Value.getClass()); - if (editor.m_Editor == null) editor.m_Editor = PropertyEditorProvider.findEditor(TerminatorInterface.class); + if (editor.m_Editor == null) editor.m_Editor = PropertyEditorProvider.findEditor(InterfaceTerminator.class); if (editor.m_Editor instanceof GenericObjectEditor) - ((GenericObjectEditor) editor.m_Editor).setClassType(TerminatorInterface.class); + ((GenericObjectEditor) editor.m_Editor).setClassType(InterfaceTerminator.class); editor.m_Editor.setValue(editor.m_Value); this.findViewFor(editor); if (editor.m_View != null) editor.m_View.repaint(); diff --git a/src/javaeva/server/go/mocco/MOCCOParameterizeRefPoint.java b/src/javaeva/server/go/mocco/MOCCOParameterizeRefPoint.java index 2804566e..159cea23 100644 --- a/src/javaeva/server/go/mocco/MOCCOParameterizeRefPoint.java +++ b/src/javaeva/server/go/mocco/MOCCOParameterizeRefPoint.java @@ -1,7 +1,7 @@ package javaeva.server.go.mocco; import javaeva.server.go.MOCCOStandalone; -import javaeva.server.go.TerminatorInterface; +import javaeva.server.go.InterfaceTerminator; import javaeva.server.go.operators.migration.SOBestMigration; import javaeva.server.go.operators.moso.MOSOLpMetric; import javaeva.server.go.problems.AbstractMultiObjectiveOptimizationProblem; @@ -158,9 +158,9 @@ public class MOCCOParameterizeRefPoint extends MOCCOPhase implements InterfacePr try { editor.m_Value = this.m_Mocco.m_State.m_Terminator; editor.m_Editor = PropertyEditorProvider.findEditor(editor.m_Value.getClass()); - if (editor.m_Editor == null) editor.m_Editor = PropertyEditorProvider.findEditor(TerminatorInterface.class); + if (editor.m_Editor == null) editor.m_Editor = PropertyEditorProvider.findEditor(InterfaceTerminator.class); if (editor.m_Editor instanceof GenericObjectEditor) - ((GenericObjectEditor) editor.m_Editor).setClassType(TerminatorInterface.class); + ((GenericObjectEditor) editor.m_Editor).setClassType(InterfaceTerminator.class); editor.m_Editor.setValue(editor.m_Value); this.findViewFor(editor); if (editor.m_View != null) editor.m_View.repaint(); diff --git a/src/javaeva/server/go/mocco/MOCCOParameterizeSO.java b/src/javaeva/server/go/mocco/MOCCOParameterizeSO.java index 551dff72..909479c9 100644 --- a/src/javaeva/server/go/mocco/MOCCOParameterizeSO.java +++ b/src/javaeva/server/go/mocco/MOCCOParameterizeSO.java @@ -1,7 +1,7 @@ package javaeva.server.go.mocco; import javaeva.server.go.MOCCOStandalone; -import javaeva.server.go.TerminatorInterface; +import javaeva.server.go.InterfaceTerminator; import javaeva.server.go.strategies.GeneticAlgorithm; import javaeva.server.go.strategies.InterfaceOptimizer; import javaeva.server.go.strategies.MultiObjectiveEA; @@ -96,9 +96,9 @@ public class MOCCOParameterizeSO extends MOCCOPhase implements InterfaceProcessE try { editor.m_Value = this.m_Mocco.m_State.m_Terminator; editor.m_Editor = PropertyEditorProvider.findEditor(editor.m_Value.getClass()); - if (editor.m_Editor == null) editor.m_Editor = PropertyEditorProvider.findEditor(TerminatorInterface.class); + if (editor.m_Editor == null) editor.m_Editor = PropertyEditorProvider.findEditor(InterfaceTerminator.class); if (editor.m_Editor instanceof GenericObjectEditor) - ((GenericObjectEditor) editor.m_Editor).setClassType(TerminatorInterface.class); + ((GenericObjectEditor) editor.m_Editor).setClassType(InterfaceTerminator.class); editor.m_Editor.setValue(editor.m_Value); this.findViewFor(editor); if (editor.m_View != null) editor.m_View.repaint(); diff --git a/src/javaeva/server/go/mocco/MOCCOParameterizeSTEP.java b/src/javaeva/server/go/mocco/MOCCOParameterizeSTEP.java index 3bf88f05..5233d3d0 100644 --- a/src/javaeva/server/go/mocco/MOCCOParameterizeSTEP.java +++ b/src/javaeva/server/go/mocco/MOCCOParameterizeSTEP.java @@ -1,7 +1,7 @@ package javaeva.server.go.mocco; import javaeva.server.go.MOCCOStandalone; -import javaeva.server.go.TerminatorInterface; +import javaeva.server.go.InterfaceTerminator; import javaeva.server.go.individuals.AbstractEAIndividual; import javaeva.server.go.operators.moso.MOSOWeightedFitness; import javaeva.server.go.problems.AbstractMultiObjectiveOptimizationProblem; @@ -186,9 +186,9 @@ public class MOCCOParameterizeSTEP extends MOCCOPhase implements InterfaceProces try { editor.m_Value = this.m_Mocco.m_State.m_Terminator; editor.m_Editor = PropertyEditorProvider.findEditor(editor.m_Value.getClass()); - if (editor.m_Editor == null) editor.m_Editor = PropertyEditorProvider.findEditor(TerminatorInterface.class); + if (editor.m_Editor == null) editor.m_Editor = PropertyEditorProvider.findEditor(InterfaceTerminator.class); if (editor.m_Editor instanceof GenericObjectEditor) - ((GenericObjectEditor) editor.m_Editor).setClassType(TerminatorInterface.class); + ((GenericObjectEditor) editor.m_Editor).setClassType(InterfaceTerminator.class); editor.m_Editor.setValue(editor.m_Value); this.findViewFor(editor); if (editor.m_View != null) editor.m_View.repaint(); diff --git a/src/javaeva/server/go/mocco/MOCCOParameterizeTchebycheff.java b/src/javaeva/server/go/mocco/MOCCOParameterizeTchebycheff.java index d1250e42..f3b0606a 100644 --- a/src/javaeva/server/go/mocco/MOCCOParameterizeTchebycheff.java +++ b/src/javaeva/server/go/mocco/MOCCOParameterizeTchebycheff.java @@ -1,7 +1,7 @@ package javaeva.server.go.mocco; import javaeva.server.go.MOCCOStandalone; -import javaeva.server.go.TerminatorInterface; +import javaeva.server.go.InterfaceTerminator; import javaeva.server.go.operators.migration.SOBestMigration; import javaeva.server.go.operators.moso.MOSOWeightedLPTchebycheff; import javaeva.server.go.problems.AbstractMultiObjectiveOptimizationProblem; @@ -133,9 +133,9 @@ public class MOCCOParameterizeTchebycheff extends MOCCOPhase implements Interfac try { editor.m_Value = this.m_Mocco.m_State.m_Terminator; editor.m_Editor = PropertyEditorProvider.findEditor(editor.m_Value.getClass()); - if (editor.m_Editor == null) editor.m_Editor = PropertyEditorProvider.findEditor(TerminatorInterface.class); + if (editor.m_Editor == null) editor.m_Editor = PropertyEditorProvider.findEditor(InterfaceTerminator.class); if (editor.m_Editor instanceof GenericObjectEditor) - ((GenericObjectEditor) editor.m_Editor).setClassType(TerminatorInterface.class); + ((GenericObjectEditor) editor.m_Editor).setClassType(InterfaceTerminator.class); editor.m_Editor.setValue(editor.m_Value); this.findViewFor(editor); if (editor.m_View != null) editor.m_View.repaint(); diff --git a/src/javaeva/server/go/mocco/MOCCOState.java b/src/javaeva/server/go/mocco/MOCCOState.java index cc0f0149..9ad1a951 100644 --- a/src/javaeva/server/go/mocco/MOCCOState.java +++ b/src/javaeva/server/go/mocco/MOCCOState.java @@ -1,6 +1,6 @@ package javaeva.server.go.mocco; -import javaeva.server.go.TerminatorInterface; +import javaeva.server.go.InterfaceTerminator; import javaeva.server.go.individuals.AbstractEAIndividual; import javaeva.server.go.operators.archiving.ArchivingAllDominating; import javaeva.server.go.operators.terminators.EvaluationTerminator; @@ -31,7 +31,7 @@ public class MOCCOState { public transient boolean isVisible = false; public InterfaceOptimizer m_Optimizer = new MultiObjectiveEA(); public InterfaceOptimizer m_BackupOptimizer; - public TerminatorInterface m_Terminator = new EvaluationTerminator(); + public InterfaceTerminator m_Terminator = new EvaluationTerminator(); public InterfaceOptimizationProblem m_OriginalProblem = null; public InterfaceOptimizationProblem m_CurrentProblem; public InterfaceOptimizationProblem m_BackupProblem; diff --git a/src/javaeva/server/go/operators/crossover/CrossoverESSPX.java b/src/javaeva/server/go/operators/crossover/CrossoverESSPX.java index 128bf6bb..86bf5cc9 100644 --- a/src/javaeva/server/go/operators/crossover/CrossoverESSPX.java +++ b/src/javaeva/server/go/operators/crossover/CrossoverESSPX.java @@ -186,7 +186,7 @@ public class CrossoverESSPX implements InterfaceCrossover, java.io.Serializable F1Problem prob = new F1Problem(); int n = 2; - RandomNumberGenerator.setseed(1); + RandomNumberGenerator.setRandomSeed(1); // init individual indy1 = new ESIndividualDoubleData(); double[][] range = new double[n][2]; diff --git a/src/javaeva/server/go/operators/crossover/CrossoverESUNDX.java b/src/javaeva/server/go/operators/crossover/CrossoverESUNDX.java index 598762e0..5701ec9d 100644 --- a/src/javaeva/server/go/operators/crossover/CrossoverESUNDX.java +++ b/src/javaeva/server/go/operators/crossover/CrossoverESUNDX.java @@ -286,7 +286,7 @@ public class CrossoverESUNDX implements InterfaceCrossover, java.io.Serializable F1Problem prob = new F1Problem(); int n = 2; - RandomNumberGenerator.setseed(1); + RandomNumberGenerator.setRandomSeed(1); // init individual indy1 = new ESIndividualDoubleData(); double[][] range = new double[n][2]; diff --git a/src/javaeva/server/go/operators/distancemetric/PhenotypeMetric.java b/src/javaeva/server/go/operators/distancemetric/PhenotypeMetric.java index d78acd76..31d2a493 100644 --- a/src/javaeva/server/go/operators/distancemetric/PhenotypeMetric.java +++ b/src/javaeva/server/go/operators/distancemetric/PhenotypeMetric.java @@ -1,5 +1,6 @@ package javaeva.server.go.operators.distancemetric; +import javaeva.gui.BeanInspector; import javaeva.server.go.individuals.AbstractEAIndividual; import javaeva.server.go.individuals.InterfaceDataTypeBinary; import javaeva.server.go.individuals.InterfaceDataTypeDouble; @@ -20,7 +21,8 @@ import java.util.BitSet; * To change this template use File | Settings | File Templates. */ public class PhenotypeMetric implements InterfaceDistanceMetric, java.io.Serializable { - + private static PhenotypeMetric pMetric = null; + public PhenotypeMetric() { } @@ -31,11 +33,11 @@ public class PhenotypeMetric implements InterfaceDistanceMetric, java.io.Seriali return (Object) new PhenotypeMetric(this); } - private int Minimum (int a, int b, int c) { + private static int min(int a, int b, int c) { return Math.min(Math.min(a, b), c); } - private int computeLevenshteinDistance (String s, String t) { + private static int computeLevenshteinDistance (String s, String t) { int d[][]; // matrix int n; // length of s int m; // length of t @@ -69,7 +71,7 @@ public class PhenotypeMetric implements InterfaceDistanceMetric, java.io.Seriali cost = 1; } // Step 6 - d[i][j] = Minimum (d[i-1][j]+1, d[i][j-1]+1, d[i-1][j-1] + cost); + d[i][j] = min(d[i-1][j]+1, d[i][j-1]+1, d[i-1][j-1] + cost); } } // Step 7 @@ -107,33 +109,34 @@ public class PhenotypeMetric implements InterfaceDistanceMetric, java.io.Seriali d2 = ((InterfaceDataTypeInteger) indy2).getIntegerData(); r2 = ((InterfaceDataTypeInteger) indy2).getIntRange(); for (int i = 0; (i < d1.length) && (i < d2.length); i++) { - tmpResult += Math.abs(d1[i] - d2[i])/((double)(r1[i][1]-r1[i][0])); + tmpResult += Math.pow(((d1[i] - r1[i][0])/((double)(r1[i][1]-r1[i][0]))) - ( (d2[i] - r2[i][0])/((double)(r2[i][1]-r2[i][0]))), 2); + //tmpResult += Math.abs(d1[i] - d2[i])/((double)(r1[i][1]-r1[i][0])); } result += Math.sqrt(tmpResult); } if ((indy1 instanceof InterfaceDataTypeDouble) && (indy2 instanceof InterfaceDataTypeDouble)) { - double[] dIndy1, dIndy2; - double[][] range1, range2; + double[] d1, d2; + double[][] r1, r2; double tmpResult = 0; - dIndy1 = ((InterfaceDataTypeDouble) indy1).getDoubleData(); - range1 = ((InterfaceDataTypeDouble) indy1).getDoubleRange(); - dIndy2 = ((InterfaceDataTypeDouble) indy2).getDoubleData(); - range2 = ((InterfaceDataTypeDouble) indy2).getDoubleRange(); - for (int i = 0; (i < dIndy1.length) && (i < dIndy2.length); i++) { - tmpResult += 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); + d1 = ((InterfaceDataTypeDouble) indy1).getDoubleData(); + r1 = ((InterfaceDataTypeDouble) indy1).getDoubleRange(); + d2 = ((InterfaceDataTypeDouble) indy2).getDoubleData(); + r2 = ((InterfaceDataTypeDouble) indy2).getDoubleRange(); + for (int i = 0; (i < d1.length) && (i < d2.length); i++) { + tmpResult += Math.pow(((d1[i] - r1[i][0])/(r1[i][1] - r1[i][0])) - ((d2[i] - r2[i][0])/(r2[i][1] - r2[i][0])), 2); } result += Math.sqrt(tmpResult); } if ((indy1 instanceof InterfaceDataTypePermutation) && (indy2 instanceof InterfaceDataTypePermutation)) { int[] dIndy1, dIndy2; String s1 = "", s2 = ""; - double tmpResult = 0; +// double tmpResult = 0; for (int p = 0; p < ((InterfaceDataTypePermutation) indy1).getPermutationData().length; p++) { dIndy1 = ((InterfaceDataTypePermutation) indy1).getPermutationData()[p]; dIndy2 = ((InterfaceDataTypePermutation) indy2).getPermutationData()[p]; for (int i = 0; i < dIndy1.length; i++) s1 += dIndy1[i]; for (int i = 0; i < dIndy2.length; i++) s2 += dIndy2[i]; - result += this.computeLevenshteinDistance(s1, s2)/((double)Math.max(s1.length(), s2.length())); + result += PhenotypeMetric.computeLevenshteinDistance(s1, s2)/((double)Math.max(s1.length(), s2.length())); } } if ((indy1 instanceof InterfaceDataTypeProgram) && (indy2 instanceof InterfaceDataTypeProgram)) { @@ -143,13 +146,22 @@ public class PhenotypeMetric implements InterfaceDistanceMetric, java.io.Seriali for (int i = 0; i < l1; i++) { s1 = ((InterfaceDataTypeProgram)indy1).getProgramData()[i].getStringRepresentation(); s2 = ((InterfaceDataTypeProgram)indy2).getProgramData()[i].getStringRepresentation(); - result += this.computeLevenshteinDistance(s1, s2)/((double)Math.max(s1.length(), s2.length())); + result += PhenotypeMetric.computeLevenshteinDistance(s1, s2)/((double)Math.max(s1.length(), s2.length())); } } - return result; - - + } + + /** 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 static double dist(AbstractEAIndividual indy1, AbstractEAIndividual indy2) { + if (pMetric == null) pMetric = new PhenotypeMetric(); + return pMetric.distance(indy1, indy2); } public static double euclidianDistance(double[] v1, double[] v2) { @@ -160,6 +172,40 @@ public class PhenotypeMetric implements InterfaceDistanceMetric, java.io.Seriali return Math.sqrt(result); } + public static double norm(AbstractEAIndividual indy) { + double result = 0; + if (indy instanceof InterfaceDataTypeBinary) { + BitSet bs = (BitSet)((InterfaceDataTypeBinary)indy).getBinaryData(); + for (int i = 0; (i < ((InterfaceDataTypeBinary)indy).size()) ; i++) { + if (bs.get(i)) result += 1; + } + result = result/((InterfaceDataTypeBinary)indy).size(); + return result; + } + if (indy instanceof InterfaceDataTypeInteger) { + int[] d1 = ((InterfaceDataTypeInteger) indy).getIntegerData(); + for (int i = 0; i < d1.length; i++) { + result += d1[i]; + } + return result/d1.length; + } + if (indy instanceof InterfaceDataTypeDouble) { + result = norm(((InterfaceDataTypeDouble) indy).getDoubleData()); + return result; + } + if (indy instanceof InterfaceDataTypePermutation) { + // TODO hard to find a norm for permutations. As we use the levenshtein distance metric, + // the normed distance to the empty permutaton is always one... + return 1; + } + if (indy instanceof InterfaceDataTypeProgram) { + // TODO same as for permutations + return 1; + } + System.err.println("error: unknown individual interface in PhenotypeMetric::norm " + BeanInspector.toString(indy)); + return 0; + } + public static double norm(double[] v1) { double result = 0; for (int i = 0; i < v1.length; i++) { diff --git a/src/javaeva/server/go/operators/terminators/CombinedTerminator.java b/src/javaeva/server/go/operators/terminators/CombinedTerminator.java index 16991d0d..9b60220b 100644 --- a/src/javaeva/server/go/operators/terminators/CombinedTerminator.java +++ b/src/javaeva/server/go/operators/terminators/CombinedTerminator.java @@ -1,18 +1,20 @@ package javaeva.server.go.operators.terminators; +import java.beans.BeanInfo; import java.io.Serializable; +import javaeva.gui.BeanInspector; import javaeva.server.go.PopulationInterface; -import javaeva.server.go.TerminatorInterface; +import javaeva.server.go.InterfaceTerminator; import javaeva.tools.SelectedTag; -public class CombinedTerminator implements TerminatorInterface, Serializable { +public class CombinedTerminator implements InterfaceTerminator, Serializable { /** * */ private static final long serialVersionUID = -4748749151972645021L; - private TerminatorInterface t1 = new ConvergenceTerminator(); - private TerminatorInterface t2 = new EvaluationTerminator(); + private InterfaceTerminator t1 = new FitnessConvergenceTerminator(); + private InterfaceTerminator t2 = new EvaluationTerminator(); private SelectedTag andOrTag = new SelectedTag("OR", "AND"); /** @@ -20,6 +22,16 @@ public class CombinedTerminator implements TerminatorInterface, Serializable { */ public CombinedTerminator() {} + /** + * Convenience constructor combining the given terminators in the expected way. + * + */ + public CombinedTerminator(InterfaceTerminator t1, InterfaceTerminator t2, boolean bAnd) { + this.t1 = t1; + this.t2 = t2; + andOrTag.setSelectedTag(bAnd ? "AND" : "OR"); + } + public String globalInfo() { return "Boolean combination of two terminators."; } @@ -29,22 +41,42 @@ public class CombinedTerminator implements TerminatorInterface, Serializable { if (t2 != null) t2.init(); } - public boolean isTerminated(PopulationInterface Pop) { + public boolean isTerminated(PopulationInterface pop) { boolean ret; if ((t1 == null) && (t2 == null)) { System.err.println("Error: No terminator set in CombinedTerminator"); return true; } - if (t1 == null) return t2.isTerminated(Pop); - if (t2 == null) return t1.isTerminated(Pop); + if (t1 == null) return t2.isTerminated(pop); + if (t2 == null) return t1.isTerminated(pop); if (andOrTag.isSelectedString("AND")) { - ret = t1.isTerminated(Pop) && t2.isTerminated(Pop); - } else { - ret = t1.isTerminated(Pop) || t2.isTerminated(Pop); + // make sure that both terminators are triggered by every call, because some judge + // time-dependently and store information on the population. + ret = t1.isTerminated(pop); + ret = ret && t2.isTerminated(pop); + } else { // OR + // make sure that both terminators are triggered by every call, because some judge + // time-dependently and store information on the population. + ret = t1.isTerminated(pop); + ret = ret || t2.isTerminated(pop); } return ret; } + + public String terminatedBecause(PopulationInterface pop) { + if (isTerminated(pop)) { + if (andOrTag.isSelectedString("AND")) { + return "Terminated because both: " + t1.terminatedBecause(pop) + " And " + t2.terminatedBecause(pop); + } else { + if ((t1 != null) && (t1.isTerminated(pop))) { + return t1.terminatedBecause(pop); + } else { + return t2.terminatedBecause(pop); + } + } + } else return "not terminated"; + } /** * @return the andOrTag @@ -67,14 +99,14 @@ public class CombinedTerminator implements TerminatorInterface, Serializable { /** * @return the t1 */ - public TerminatorInterface getTerminatorOne() { + public InterfaceTerminator getTerminatorOne() { return t1; } /** * @param t1 the t1 to set */ - public void setTerminatorOne(TerminatorInterface t1) { + public void setTerminatorOne(InterfaceTerminator t1) { this.t1 = t1; } @@ -85,14 +117,14 @@ public class CombinedTerminator implements TerminatorInterface, Serializable { /** * @return the t2 */ - public TerminatorInterface getTerminatorTwo() { + public InterfaceTerminator getTerminatorTwo() { return t2; } /** * @param t2 the t2 to set */ - public void setTerminatorTwo(TerminatorInterface t2) { + public void setTerminatorTwo(InterfaceTerminator t2) { this.t2 = t2; } diff --git a/src/javaeva/server/go/operators/terminators/ConvergenceTerminator.java b/src/javaeva/server/go/operators/terminators/ConvergenceTerminator.java deleted file mode 100644 index f27b11b0..00000000 --- a/src/javaeva/server/go/operators/terminators/ConvergenceTerminator.java +++ /dev/null @@ -1,174 +0,0 @@ -package javaeva.server.go.operators.terminators; - -/* - * Title: JavaEvA - * Description: - * Copyright: Copyright (c) 2003 - * Company: University of Tuebingen, Computer Architecture - * @author Holger Ulmer, Felix Streichert, Hannes Planatscher - * @version: $Revision: 319 $ - * $Date: 2007-12-05 11:29:32 +0100 (Wed, 05 Dec 2007) $ - * $Author: mkron $ - */ -/*==========================================================================* - * IMPORTS - *==========================================================================*/ -import java.io.Serializable; - -import javaeva.gui.BeanInspector; -import javaeva.server.go.PopulationInterface; -import javaeva.server.go.TerminatorInterface; -import javaeva.server.go.operators.distancemetric.PhenotypeMetric; -import javaeva.tools.SelectedTag; - -/*==========================================================================* - * CLASS DECLARATION - *==========================================================================*/ -/** - * - */ -public class ConvergenceTerminator implements TerminatorInterface, -Serializable { - /** - * - */ - private static final long serialVersionUID = 5749620193474954959L; - private double m_percent = 0.01; - private int m_stagTime = 100; - private int popFitCalls = 1000; - private int popGens = 1000; - private boolean firstTime = true; - private double[] oldFit; - private double oldFitNorm; - private SelectedTag stagnationMeasure = new SelectedTag("Fitness calls", "Generations"); - - /** - * - */ - public ConvergenceTerminator() { - - } - - - /** - * - */ - public String globalInfo() { - return "Stop if a convergence criterion has been met."; - } - - /** - * - * @return - */ - public void init() { - firstTime = true; - } - - /** - * - */ - public boolean isTerminated(PopulationInterface Pop) { - if (!firstTime && isStillConverged(Pop.getBestFitness())) { - if (stagnationTimeHasPassed(Pop)) { - // population hasnt improved much for max time, criterion is met - return true; - } else { - // population hasnt improved much for i= m_stagTime) + " after " + (pop.getFunctionCalls() - popFitCalls)); - return (pop.getFunctionCalls() - popFitCalls) >= m_stagTime; - } else {// by generation -// System.out.println("stagnationTimeHasPassed returns " + ((pop.getFunctionCalls() - popGens) >= m_stagTime) + " after " + (pop.getFunctionCalls() - popGens)); - return (pop.getGenerations() - popGens) >= m_stagTime; - } - } - - /** - * - */ -// public String toString() { -// return BeanTest.toString(this); -// } - - /** - * - */ - public void setFitnessPerCent(double x) { - m_percent = x; - } - - /** - * - */ - public double getFitnessPerCent() { - return m_percent; - } - - public String fitnessPerCentTipText() { - return "Terminate if the fitness has not improved by this percentage for a whole stagnation time period"; - } - - /** - * - */ - public void setStagnationTime(int k) { - m_stagTime = k; - } - - /** - * - */ - public int getStagnationTime() { - return m_stagTime; - } - - public String stagnationTimeTipText() { - return "Terminate if the population has not improved for this time"; - } - - - /** - * @return the stagnationTimeIn - */ - public SelectedTag getStagnationMeasure() { - return stagnationMeasure; - } - - - /** - * @param stagnationTimeIn the stagnationTimeIn to set - */ - public void setStagnationMeasure(SelectedTag stagnationTimeIn) { - this.stagnationMeasure = stagnationTimeIn; - } - - public String stagnationMeasureTipText() { - return "Stagnation time is measured in fitness calls or generations, to be selected here."; - } -} \ No newline at end of file diff --git a/src/javaeva/server/go/operators/terminators/EvaluationTerminator.java b/src/javaeva/server/go/operators/terminators/EvaluationTerminator.java index 88942043..c32349e1 100644 --- a/src/javaeva/server/go/operators/terminators/EvaluationTerminator.java +++ b/src/javaeva/server/go/operators/terminators/EvaluationTerminator.java @@ -15,14 +15,14 @@ package javaeva.server.go.operators.terminators; import java.io.Serializable; import javaeva.server.go.PopulationInterface; -import javaeva.server.go.TerminatorInterface; +import javaeva.server.go.InterfaceTerminator; /*==========================================================================* * CLASS DECLARATION *==========================================================================*/ /** * */ -public class EvaluationTerminator implements TerminatorInterface, +public class EvaluationTerminator implements InterfaceTerminator, Serializable { /** * Number of fitness calls on the problem which is optimized. @@ -49,12 +49,17 @@ public class EvaluationTerminator implements TerminatorInterface, /** * */ - public boolean isTerminated(PopulationInterface Pop) { + public boolean isTerminated(PopulationInterface pop) { //System.out.println("m_FitnessCalls="+m_FitnessCalls); - if (m_FitnessCalls>Pop.getFunctionCalls()) + if (m_FitnessCalls>pop.getFunctionCalls()) return false; return true; } + + public String terminatedBecause(PopulationInterface pop) { + if (isTerminated(pop)) return m_FitnessCalls + " fitness calls were reached."; + else return "Not yet terminated."; + } /** * */ diff --git a/src/javaeva/server/go/operators/terminators/FitnessConvergenceTerminator.java b/src/javaeva/server/go/operators/terminators/FitnessConvergenceTerminator.java new file mode 100644 index 00000000..892768c6 --- /dev/null +++ b/src/javaeva/server/go/operators/terminators/FitnessConvergenceTerminator.java @@ -0,0 +1,225 @@ +package javaeva.server.go.operators.terminators; + +/* + * Title: JavaEvA + * Description: + * Copyright: Copyright (c) 2003 + * Company: University of Tuebingen, Computer Architecture + * @author Holger Ulmer, Felix Streichert, Hannes Planatscher + * @version: $Revision: 319 $ + * $Date: 2007-12-05 11:29:32 +0100 (Wed, 05 Dec 2007) $ + * $Author: mkron $ + */ +/*==========================================================================* + * IMPORTS + *==========================================================================*/ +import java.io.Serializable; + +import javaeva.gui.BeanInspector; +import javaeva.server.go.IndividualInterface; +import javaeva.server.go.InterfaceTerminator; +import javaeva.server.go.PopulationInterface; +import javaeva.server.go.individuals.AbstractEAIndividual; +import javaeva.server.go.operators.distancemetric.PhenotypeMetric; +import javaeva.tools.SelectedTag; + +/*==========================================================================* + * CLASS DECLARATION + *==========================================================================*/ +/** + * + */ +public class FitnessConvergenceTerminator implements InterfaceTerminator, +Serializable { + private static final long serialVersionUID = 5749620193474954959L; + protected static boolean TRACE = false; + protected double convThresh = 0.01; + protected int m_stagTime = 100; + protected int popFitCalls = 1000; + protected int popGens = 1000; + protected boolean firstTime = true; + protected double[] oldFit; + protected double oldNorm; + private SelectedTag stagnationMeasure = new SelectedTag("Fitness calls", "Generations"); + private SelectedTag convergenceCondition = new SelectedTag("Relative", "Absolute"); + PhenotypeMetric pMetric = null; + + public FitnessConvergenceTerminator() { + pMetric = new PhenotypeMetric(); + } + + public FitnessConvergenceTerminator(double thresh, int stagnTime, boolean bFitCallBased, boolean bAbsolute) { + pMetric = new PhenotypeMetric(); + convThresh = thresh; + this.m_stagTime = stagnTime; + if (bFitCallBased) stagnationMeasure.setSelectedTag("Fitness calls"); + else stagnationMeasure.setSelectedTag("Generations"); + if (bAbsolute) convergenceCondition.setSelectedTag("Absolute"); + else convergenceCondition.setSelectedTag("Relative"); + } + + /** + * + */ + public String globalInfo() { + return "Stop if a fitness convergence criterion has been met."; + } + + public void init() { + if (pMetric == null) pMetric = new PhenotypeMetric(); + firstTime = true; + } + + public boolean isTerminated(PopulationInterface Pop) { + if (!firstTime && isStillConverged(Pop.getBestIndividual())) { + if (stagnationTimeHasPassed(Pop)) { + // population hasnt improved much for max time, criterion is met + return true; + } else { + // population hasnt improved much for i= m_stagTime) + " after " + (pop.getFunctionCalls() - popFitCalls)); + return (pop.getFunctionCalls() - popFitCalls) >= m_stagTime; + } else {// by generation +// System.out.println("stagnationTimeHasPassed returns " + ((pop.getFunctionCalls() - popGens) >= m_stagTime) + " after " + (pop.getFunctionCalls() - popGens)); + return (pop.getGenerations() - popGens) >= m_stagTime; + } + } + + /** + * + */ +// public String toString() { +// return BeanTest.toString(this); +// } + + /** + * + */ + public void setConvergenceThreshold(double x) { + convThresh = x; + } + + /** + * + */ + public double getConvergenceThreshold() { + return convThresh; + } + + public String convergenceThresholdTipText() { + return "Terminate if the fitness has not improved by this percentage / absolute value for a whole stagnation time period"; + } + + /** + * + */ + public void setStagnationTime(int k) { + m_stagTime = k; + } + + /** + * + */ + public int getStagnationTime() { + return m_stagTime; + } + + public String stagnationTimeTipText() { + return "Terminate if the population has not improved for this time"; + } + + + /** + * @return the stagnationTimeIn + */ + public SelectedTag getStagnationMeasure() { + return stagnationMeasure; + } + + /** + * @param stagnationTimeIn the stagnationTimeIn to set + */ + public void setStagnationMeasure(SelectedTag stagnationTimeIn) { + this.stagnationMeasure = stagnationTimeIn; + } + + public String stagnationMeasureTipText() { + return "Stagnation time is measured in fitness calls or generations, to be selected here."; + } + + /** + * @return the convergenceCondition + */ + public SelectedTag getConvergenceCondition() { + return convergenceCondition; + } + + /** + * @param convergenceCondition the convergenceCondition to set + */ + public void setConvergenceCondition(SelectedTag convergenceCondition) { + this.convergenceCondition = convergenceCondition; + } + + public String convergenceConditionTipText() { + return "Select between absolute and relative convergence condition"; + } +} \ No newline at end of file diff --git a/src/javaeva/server/go/operators/terminators/FitnessValueTerminator.java b/src/javaeva/server/go/operators/terminators/FitnessValueTerminator.java index 309126bf..1a604b65 100644 --- a/src/javaeva/server/go/operators/terminators/FitnessValueTerminator.java +++ b/src/javaeva/server/go/operators/terminators/FitnessValueTerminator.java @@ -14,62 +14,76 @@ package javaeva.server.go.operators.terminators; *==========================================================================*/ import java.io.Serializable; +import javaeva.gui.BeanInspector; import javaeva.server.go.PopulationInterface; -import javaeva.server.go.TerminatorInterface; +import javaeva.server.go.InterfaceTerminator; /*==========================================================================* -* CLASS DECLARATION -*==========================================================================*/ + * CLASS DECLARATION + *==========================================================================*/ /** * */ -public class FitnessValueTerminator implements TerminatorInterface, - Serializable { - protected double[] m_FitnessValue; - /** - * - */ - public FitnessValueTerminator() { - m_FitnessValue = new double []{0.1}; - } +public class FitnessValueTerminator implements InterfaceTerminator, +Serializable { + protected double[] m_FitnessValue; + /** + * + */ + public FitnessValueTerminator() { + m_FitnessValue = new double []{0.1}; + } - public void init(){} - /** - * - */ - public String globalInfo() { - return "Terminate if a certain fitness value has been reached."; - } - /** - * - */ - public FitnessValueTerminator( double[] x) { - m_FitnessValue = (double[])x.clone(); - } - /** - * - */ - public boolean isTerminated(PopulationInterface Pop) { - if (m_FitnessValue[0]fit[i]) return false; + } + return true; + } + + public String terminatedBecause(PopulationInterface pop) { + if (isTerminated(pop)) { + return "Fitness value below " + BeanInspector.toString(m_FitnessValue); + } else return "Not yet terminated."; + } + + /** + * + */ + public String toString() { + String ret = "FitnessValueTerminator,m_FitnessValue="+m_FitnessValue; + return ret; + } + /** + * + */ + public void setFitnessValue(double[] x) { + m_FitnessValue = x; + } + /** + * + */ + public double[] getFitnessValue() { + return m_FitnessValue; + } + + public String fitnessValueTipText() { + return "Set the fitness objective value."; + } } \ No newline at end of file diff --git a/src/javaeva/server/go/operators/terminators/GenerationTerminator.java b/src/javaeva/server/go/operators/terminators/GenerationTerminator.java index c2e7c6c9..8e3f9075 100644 --- a/src/javaeva/server/go/operators/terminators/GenerationTerminator.java +++ b/src/javaeva/server/go/operators/terminators/GenerationTerminator.java @@ -14,15 +14,16 @@ package javaeva.server.go.operators.terminators; *==========================================================================*/ import java.io.Serializable; +import javaeva.gui.BeanInspector; import javaeva.server.go.PopulationInterface; -import javaeva.server.go.TerminatorInterface; +import javaeva.server.go.InterfaceTerminator; /*==========================================================================* * CLASS DECLARATION *==========================================================================*/ /** * */ -public class GenerationTerminator implements TerminatorInterface, +public class GenerationTerminator implements InterfaceTerminator, Serializable { /** * Number of fitnness calls on the problem which is optimized @@ -48,6 +49,12 @@ public class GenerationTerminator implements TerminatorInterface, return true; return false; } + + public String terminatedBecause(PopulationInterface pop) { + if (isTerminated(pop)) { + return m_Generations + " generations reached."; + } else return "Not yet terminated."; + } /** * */ diff --git a/src/javaeva/server/go/problems/AbstractOptimizationProblem.java b/src/javaeva/server/go/problems/AbstractOptimizationProblem.java index 698aa7d2..fd8f9be6 100644 --- a/src/javaeva/server/go/problems/AbstractOptimizationProblem.java +++ b/src/javaeva/server/go/problems/AbstractOptimizationProblem.java @@ -1,20 +1,22 @@ package javaeva.server.go.problems; +import java.awt.BorderLayout; +import java.util.BitSet; + +import javaeva.server.go.PopulationInterface; import javaeva.server.go.individuals.AbstractEAIndividual; import javaeva.server.go.individuals.InterfaceDataTypeBinary; import javaeva.server.go.individuals.InterfaceDataTypeDouble; import javaeva.server.go.individuals.InterfaceDataTypeInteger; import javaeva.server.go.individuals.InterfaceDataTypePermutation; -import javaeva.server.go.individuals.InterfaceDataTypeProgram; -import javaeva.server.go.individuals.codings.gp.InterfaceProgram; import javaeva.server.go.operators.moso.MOSONoConvert; import javaeva.server.go.populations.Population; import javaeva.server.go.strategies.InterfaceOptimizer; - -import javax.swing.*; -import java.util.BitSet; -import java.awt.*; +import javax.swing.JComponent; +import javax.swing.JPanel; +import javax.swing.JScrollPane; +import javax.swing.JTextArea; /** * Created by IntelliJ IDEA. @@ -156,120 +158,20 @@ public abstract class AbstractOptimizationProblem implements InterfaceOptimizati /******************** Some output methods *******************************************/ /** This method allows you to output a string that describes a found solution - * in a way that is most suiteable for a given problem. + * in a way that is most suitable for a given problem. * @param individual The individual that is to be shown. * @return The description. */ public String getSolutionRepresentationFor(AbstractEAIndividual individual) { - StringBuffer sb = new StringBuffer("Individual:\n"); - if (individual instanceof InterfaceDataTypeBinary) { - sb.append("Binary data : {"); - BitSet b = ((InterfaceDataTypeBinary)individual).getBinaryData(); - for (int i = 0; i < b.length(); i++) { - if (b.get(i)) sb.append("1"); - else sb.append("0"); - } - sb.append("}\n"); - } - if (individual instanceof InterfaceDataTypeInteger) { - sb.append("Integer data : {"); - 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("}\n"); - } - if (individual instanceof InterfaceDataTypeDouble) { - sb.append("Double data : {"); - 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("}\n"); - } - if (individual instanceof InterfaceDataTypePermutation) { - sb.append("Permutation data: {"); - 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("}\n"); - } - if (individual instanceof InterfaceDataTypeProgram) { - sb.append("Program data : "); - 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("}"); - } - double[] fitness = individual.getFitness(); - sb.append("Fitness : {"); - for (int i = 0; i < fitness.length; i++) { - sb.append(fitness[i]); - if ((i+1) < fitness.length) sb.append("; "); - } - sb.append("}\n"); - return sb.toString(); + return AbstractEAIndividual.getDefaultStringRepresentation(individual); } /** This method returns a single line representation of the solution * @param individual The individual * @return The string */ - public String getSolutionDataFor(AbstractEAIndividual individual) { - StringBuffer sb = new StringBuffer(""); - if (individual instanceof InterfaceDataTypeBinary) { - sb.append("{"); - BitSet b = ((InterfaceDataTypeBinary)individual).getBinaryData(); - for (int i = 0; i < b.length(); i++) { - if (b.get(i)) sb.append("1"); - else sb.append("0"); - } - sb.append("}"); - } - if (individual instanceof InterfaceDataTypeInteger) { - sb.append("{"); - 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("}"); - } - if (individual instanceof InterfaceDataTypeDouble) { - sb.append("{"); - 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("}"); - } - if (individual instanceof InterfaceDataTypePermutation) { - sb.append("{"); - 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("}"); - } - if (individual instanceof InterfaceDataTypeProgram) { - sb.append("{"); - 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("}"); - } - return sb.toString(); - } +// public String getSolutionDataFor(IndividualInterface individual) { +// } /** This method returns a string describing the optimization problem. * @return The description. @@ -292,7 +194,7 @@ public abstract class AbstractOptimizationProblem implements InterfaceOptimizati * @param pop The population that is to be refined. * @return String */ - public String getAdditionalFileStringHeader(Population pop) { + public String getAdditionalFileStringHeader(PopulationInterface pop) { return "Solution"; } @@ -300,8 +202,8 @@ public abstract class AbstractOptimizationProblem implements InterfaceOptimizati * @param pop The population that is to be refined. * @return String */ - public String getAdditionalFileStringValue(Population pop) { - return this.getSolutionDataFor(pop.getBestEAIndividual()); + public String getAdditionalFileStringValue(PopulationInterface pop) { + return AbstractEAIndividual.getDefaultDataString(pop.getBestIndividual()); } /** This method allows you to request a graphical represenation for a given diff --git a/src/javaeva/server/go/problems/AbstractProblemBinary.java b/src/javaeva/server/go/problems/AbstractProblemBinary.java new file mode 100644 index 00000000..e7124efb --- /dev/null +++ b/src/javaeva/server/go/problems/AbstractProblemBinary.java @@ -0,0 +1,108 @@ +package javaeva.server.go.problems; + +import java.util.BitSet; + +import javaeva.server.go.individuals.AbstractEAIndividual; +import javaeva.server.go.individuals.GAIndividualBinaryData; +import javaeva.server.go.individuals.InterfaceDataTypeBinary; +import javaeva.server.go.populations.Population; +import javaeva.server.go.strategies.InterfaceOptimizer; + +public abstract class AbstractProblemBinary extends AbstractOptimizationProblem { + + public AbstractProblemBinary() { + initTemplate(); + } + + protected void initTemplate() { + this.m_Template = new GAIndividualBinaryData(); + ((InterfaceDataTypeBinary)this.m_Template).setBinaryDataLength(this.getProblemDimension()); + } + + @Override + public Object clone() { + try { + AbstractProblemBinary prob = this.getClass().newInstance(); + prob.m_Template = (AbstractEAIndividual)m_Template.clone(); + return prob; + } catch(Exception e) { + System.err.println("Error: couldnt instantiate "+this.getClass().getName()); + return null; + } + } + + @Override + public void evaluate(AbstractEAIndividual individual) { + BitSet tmpBitSet; + double[] result; + + tmpBitSet = ((InterfaceDataTypeBinary) individual).getBinaryData(); + // evaluate the fitness + result = eval(tmpBitSet); + // set the fitness + individual.SetFitness(result); + } + + /** + * Evaluate a double vector + * @param x + * @return + */ + public abstract double[] eval(BitSet bs); + + public abstract int getProblemDimension(); + + @Override + public void initPopulation(Population population) { + AbstractEAIndividual tmpIndy; + population.clear(); + + ((InterfaceDataTypeBinary)this.m_Template).setBinaryDataLength(this.getProblemDimension()); + + for (int i = 0; i < population.getPopulationSize(); i++) { + tmpIndy = (AbstractEAIndividual)((AbstractEAIndividual)this.m_Template).clone(); + tmpIndy.init(this); + population.add(tmpIndy); + } + // population init must be last + // it set's fitcalls and generation to zero + population.init(); + } + + @Override + public void initProblem() { + initTemplate(); + } + + /********************************************************************************************************************** + * These are for GUI + */ + /** This method allows the CommonJavaObjectEditorPanel to read the + * name to the current object. + * @return The name. + */ + public String getName() { + return "SimpleProblemBinary"; + } + + /** This method returns a global info string + * @return description + */ + public String globalInfo() { + return "The programmer did not give further details."; + } + + /** This method returns a string describing the optimization problem. + * @param opt The Optimizer that is used or had been used. + * @return The description. + */ + public String getStringRepresentationForProblem(InterfaceOptimizer opt) { + StringBuffer sb = new StringBuffer(200); + sb.append("A binary valued problem:\n"); + sb.append(globalInfo()); + sb.append("Dimension : "); + sb.append(this.getProblemDimension()); + return sb.toString(); + } +} + diff --git a/src/javaeva/server/go/problems/AbstractProblemDouble.java b/src/javaeva/server/go/problems/AbstractProblemDouble.java new file mode 100644 index 00000000..9f9e3fc7 --- /dev/null +++ b/src/javaeva/server/go/problems/AbstractProblemDouble.java @@ -0,0 +1,187 @@ +package javaeva.server.go.problems; + +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.strategies.InterfaceOptimizer; +import javaeva.server.go.tools.RandomNumberGenerator; + +public abstract class AbstractProblemDouble extends AbstractOptimizationProblem { + protected double m_DefaultRange = 10; + protected double m_Noise = 0; + + public AbstractProblemDouble() { + initTemplate(); + } + + protected void initTemplate() { + this.m_Template = new ESIndividualDoubleData(); + ((ESIndividualDoubleData)this.m_Template).setDoubleDataLength(getProblemDimension()); + ((ESIndividualDoubleData)this.m_Template).SetDoubleRange(makeRange()); + } + + @Override + public Object clone() { + try { + AbstractProblemDouble prob = this.getClass().newInstance(); + prob.m_DefaultRange = m_DefaultRange; + prob.m_Noise = m_Noise; + prob.m_Template = (AbstractEAIndividual)m_Template.clone(); + return prob; + } catch(Exception e) { + System.err.println("Error: couldnt instantiate "+this.getClass().getName()); + return null; + } + } + + @Override + public void evaluate(AbstractEAIndividual individual) { + double[] x; + double[] fitness; + + x = new double[((InterfaceDataTypeDouble) individual).getDoubleData().length]; + System.arraycopy(((InterfaceDataTypeDouble) individual).getDoubleData(), 0, x, 0, x.length); + // evaluate the vector + fitness = this.eval(x); + // if indicated, add Gaussian noise + if (m_Noise != 0) RandomNumberGenerator.addNoise(fitness, m_Noise); + // set the fitness + individual.SetFitness(fitness); + } + + /** + * Evaluate a double vector + * @param x + * @return + */ + public abstract double[] eval(double[] x); + + public abstract int getProblemDimension(); + + @Override + public void initPopulation(Population population) { + AbstractEAIndividual tmpIndy; + population.clear(); + ((InterfaceDataTypeDouble)this.m_Template).setDoubleDataLength(this.getProblemDimension()); + ((InterfaceDataTypeDouble)this.m_Template).SetDoubleRange(makeRange()); + + for (int i = 0; i < population.getPopulationSize(); i++) { + tmpIndy = (AbstractEAIndividual)((AbstractEAIndividual)this.m_Template).clone(); + tmpIndy.init(this); + population.add(tmpIndy); + } + // population init must be last + // it set's fitcalls and generation to zero + population.init(); + } + + protected double[][] makeRange() { + double[][] range = new double[this.getProblemDimension()][2]; + for (int i = 0; i < range.length; i++) { + range[i][0] = getRangeLowerBound(i); + range[i][1] = getRangeUpperBound(i); + } + return range; + } + + protected double getRangeLowerBound(int dim) { + return -m_DefaultRange; + } + + protected double getRangeUpperBound(int dim) { + return m_DefaultRange; + } + + @Override + public void initProblem() { + initTemplate(); + } + + /** This method allows you to choose how much noise is to be added to the + * fitness. This can be used to make the optimization problem more difficult. + * @param noise The sigma for a gaussian random number. + */ + public void setNoise(double noise) { + if (noise < 0) noise = 0; + this.m_Noise = noise; + } + public double getNoise() { + return this.m_Noise; + } + public String noiseTipText() { + return "Gaussian noise level on the fitness value."; + } + + /** This method allows you to choose the EA individual + * @param indy The EAIndividual type + */ + public void setEAIndividual(InterfaceDataTypeDouble indy) { + this.m_Template = (AbstractEAIndividual)indy; + } + + public InterfaceDataTypeDouble getEAIndividual() { + return (InterfaceDataTypeDouble)this.m_Template; + } + + public String EAIndividualTipText() { + return "Set the base individual type defining the data representation and mutation/crossover operators"; + } + + /** + * A (symmetric) absolute range limit. + * + * @return value of the absolute range limit + */ + public double getDefaultRange() { + return m_DefaultRange; + } + /** + * Set a (symmetric) absolute range limit. + * + * @param defaultRange + */ + public void setDefaultRange(double defaultRange) { + this.m_DefaultRange = defaultRange; + if (((InterfaceDataTypeDouble)this.m_Template).getDoubleData().length != getProblemDimension()) { + ((InterfaceDataTypeDouble)this.m_Template).setDoubleDataLength(getProblemDimension()); + } + ((InterfaceDataTypeDouble)this.m_Template).SetDoubleRange(makeRange()); + } + public String defaultRangeTipText() { + return "Absolute limit for the symmetric range in any dimension"; + } + + /********************************************************************************************************************** + * These are for GUI + */ + /** This method allows the CommonJavaObjectEditorPanel to read the + * name to the current object. + * @return The name. + */ + public String getName() { + return "SimpleProblemDouble"; + } + + /** This method returns a global info string + * @return description + */ + public String globalInfo() { + return "The programmer did not give further details."; + } + + /** This method returns a string describing the optimization problem. + * @param opt The Optimizer that is used or had been used. + * @return The description. + */ + public String getStringRepresentationForProblem(InterfaceOptimizer opt) { + StringBuffer sb = new StringBuffer(200); + sb.append("A double valued problem:\n"); + sb.append(globalInfo()); + sb.append("Dimension : "); + sb.append(this.getProblemDimension()); + sb.append("\nNoise level : "); + sb.append(this.m_Noise); + return sb.toString(); + } +} diff --git a/src/javaeva/server/go/problems/B1Problem.java b/src/javaeva/server/go/problems/B1Problem.java index e3f419e1..d6b40801 100644 --- a/src/javaeva/server/go/problems/B1Problem.java +++ b/src/javaeva/server/go/problems/B1Problem.java @@ -15,21 +15,19 @@ import java.util.BitSet; * Time: 13:05:33 * To change this template use Options | File Templates. */ -public class B1Problem extends AbstractOptimizationProblem implements java.io.Serializable { - +public class B1Problem extends AbstractProblemBinary implements java.io.Serializable { public int m_ProblemDimension = 30; public B1Problem() { - this.m_Template = new GAIndividualBinaryData(); + super(); } - + public B1Problem(B1Problem b) { //AbstractOptimizationProblem if (b.m_Template != null) this.m_Template = (AbstractEAIndividual)((AbstractEAIndividual)b.m_Template).clone(); //AbstractBinaryOptimizationProblem this.m_ProblemDimension = b.m_ProblemDimension; - // BLOTZ } /** This method returns a deep clone of the problem. @@ -39,12 +37,6 @@ public class B1Problem extends AbstractOptimizationProblem implements java.io.Se return (Object) new B1Problem(this); } - /** This method inits the Problem to log multiruns - */ - public void initProblem() { - // nothing to init here - } - /** This method inits a given population * @param population The populations that is to be inited */ @@ -64,34 +56,17 @@ public class B1Problem extends AbstractOptimizationProblem implements java.io.Se population.init(); } - /** This method evaluate a single individual and sets the fitness values - * @param individual The individual that is to be evalutated - */ - public void evaluate(AbstractEAIndividual individual) { - BitSet tmpBitSet; - double[] result; - InterfaceDataTypeBinary tmpIndy; - - // collect the data - tmpIndy = (InterfaceDataTypeBinary) individual; - tmpBitSet = tmpIndy.getBinaryData(); - // evalutate the fitness - result = this.evaluate(tmpBitSet, tmpIndy.size()); - // set the fitness - individual.SetFitness(result); - } - /** This is a simple method that evaluates a given Individual. The fitness * values of the individual will be set inside this method. * @param b The BitSet that is to be evaluated. * @param l The length of the BitSet. * @return Double[] */ - public double[] evaluate(BitSet b, int l) { + public double[] eval(BitSet b) { double[] result = new double[1]; int fitness = 0; - for (int i = 0; i < l; i++) if (b.get(i)) fitness++; + for (int i = 0; i < getProblemDimension(); i++) if (b.get(i)) fitness++; result[0] = fitness; return result; } @@ -143,12 +118,13 @@ public class B1Problem extends AbstractOptimizationProblem implements java.io.Se return "The task in this problem is to maximize the number of false bits in a BitSet."; } - /** This method allows you to set the number of mulitruns that are to be performed, - * necessary for stochastic optimizers to ensure reliable results. - * @param multiruns The number of multiruns that are to be performed + /** + * Set the problem dimension. + * + * @param dim The problem dimension. */ - public void setProblemDimension(int multiruns) { - this.m_ProblemDimension = multiruns; + public void setProblemDimension(int dim) { + this.m_ProblemDimension = dim; } public int getProblemDimension() { return this.m_ProblemDimension; diff --git a/src/javaeva/server/go/problems/ExternalRuntimeProblem.java b/src/javaeva/server/go/problems/ExternalRuntimeProblem.java index 3045cf3e..a81f2e44 100644 --- a/src/javaeva/server/go/problems/ExternalRuntimeProblem.java +++ b/src/javaeva/server/go/problems/ExternalRuntimeProblem.java @@ -196,7 +196,7 @@ public class ExternalRuntimeProblem extends AbstractOptimizationProblem { * @return description */ public String globalInfo() { - return "Sphere model."; + return "Use an external command as target function."; } diff --git a/src/javaeva/server/go/problems/F11Problem.java b/src/javaeva/server/go/problems/F11Problem.java index 43a80440..d73d3401 100644 --- a/src/javaeva/server/go/problems/F11Problem.java +++ b/src/javaeva/server/go/problems/F11Problem.java @@ -19,7 +19,7 @@ public class F11Problem extends F1Problem implements java.io.Serializable { public F11Problem() { this.m_ProblemDimension = 10; this.m_Template = new ESIndividualDoubleData(); - this.defaultRange = 600; + this.m_DefaultRange = 600; } public F11Problem(F11Problem b) { diff --git a/src/javaeva/server/go/problems/F1Problem.java b/src/javaeva/server/go/problems/F1Problem.java index 0c7c39a1..e2ec7f98 100644 --- a/src/javaeva/server/go/problems/F1Problem.java +++ b/src/javaeva/server/go/problems/F1Problem.java @@ -7,11 +7,6 @@ import javaeva.server.go.populations.Population; import javaeva.server.go.strategies.InterfaceOptimizer; import javaeva.server.go.tools.RandomNumberGenerator; -import javaeva.server.stat.Statistics; -import javaeva.gui.JEFrame; - -import javax.swing.*; - /** * Created by IntelliJ IDEA. * User: streiche @@ -19,7 +14,7 @@ import javax.swing.*; * Time: 17:58:55 * To change this template use Options | File Templates. */ -public class F1Problem extends AbstractOptimizationProblem implements Interface2DBorderProblem, java.io.Serializable { +public class F1Problem extends AbstractProblemDouble implements Interface2DBorderProblem, java.io.Serializable { /** * @@ -27,17 +22,16 @@ public class F1Problem extends AbstractOptimizationProblem implements Interface2 private static final long serialVersionUID = 4870484001737601464L; protected AbstractEAIndividual m_OverallBest = null; protected int m_ProblemDimension = 10; - protected double m_Noise = 0.0; protected double m_XOffSet = 0.0; protected double m_YOffSet = 0.0; protected boolean m_UseTestConstraint = false; - protected double defaultRange = 5.12; public F1Problem() { this.m_Template = new ESIndividualDoubleData(); ((ESIndividualDoubleData)this.m_Template).setDoubleDataLength(m_ProblemDimension); ((ESIndividualDoubleData)this.m_Template).SetDoubleRange(makeRange()); } + public F1Problem(F1Problem b) { //AbstractOptimizationProblem if (b.m_Template != null) @@ -46,7 +40,8 @@ public class F1Problem extends AbstractOptimizationProblem implements Interface2 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_Noise = b.m_Noise; + this.m_DefaultRange = b.m_DefaultRange; this.m_XOffSet = b.m_XOffSet; this.m_YOffSet = b.m_YOffSet; this.m_UseTestConstraint = b.m_UseTestConstraint; @@ -88,42 +83,10 @@ public class F1Problem extends AbstractOptimizationProblem implements Interface2 population.init(); } - protected double[][] makeRange() { - double[][] range = new double[this.m_ProblemDimension][2]; - for (int i = 0; i < range.length; i++) { - range[i][0] = getRangeLowerBound(i); - range[i][1] = getRangeUpperBound(i); - } - return range; - } - - protected double getRangeLowerBound(int dim) { - return -defaultRange; - } - - protected double getRangeUpperBound(int dim) { - return defaultRange; - } - protected double[][] getDoubleRange() { return ((InterfaceDataTypeDouble)this.m_Template).getDoubleRange(); } - /** This method evaluates a given population and set the fitness values - * accordingly - * @param population The population that is to be evaluated. - */ - public void evaluate(Population population) { - AbstractEAIndividual tmpIndy; - //System.out.println("Population size: " + population.size()); - for (int i = 0; i < population.size(); i++) { - tmpIndy = (AbstractEAIndividual) population.get(i); - tmpIndy.resetConstraintViolation(); - this.evaluate(tmpIndy); - population.incrFunctionCalls(); - } - } - /** This method evaluate a single individual and sets the fitness values * @param individual The individual that is to be evalutated */ @@ -131,18 +94,25 @@ public class F1Problem extends AbstractOptimizationProblem implements Interface2 double[] x; double[] fitness; + // retrieve the individual data x = new double[((InterfaceDataTypeDouble) individual).getDoubleData().length]; System.arraycopy(((InterfaceDataTypeDouble) individual).getDoubleData(), 0, x, 0, x.length); + // add an offset in solution space for (int i = 0; i < x.length; i++) x[i] = x[i] - this.m_XOffSet; - fitness = this.doEvaluation(x); - for (int i = 0; i < fitness.length; i++) { - // add noise to the fitness - if (m_Noise != 0) fitness[i] += RandomNumberGenerator.gaussianDouble(this.m_Noise); - fitness[i] += this.m_YOffSet; - // set the fitness of the individual - individual.SetFitness(i, fitness[i]); - } + + // evaluate the vector + fitness = this.eval(x); + + // add noise to the fitness + if (m_Noise != 0) RandomNumberGenerator.addNoise(fitness, m_Noise); + + // add an offset in fitness space + for (int i = 0; i < fitness.length; i++) fitness[i] += this.m_YOffSet; + + // finally set the fitness + individual.SetFitness(fitness); + if (this.m_UseTestConstraint) { if (x[0] < 1) individual.addConstraintViolation(1-x[0]); } @@ -155,7 +125,7 @@ public class F1Problem extends AbstractOptimizationProblem implements Interface2 * @param x The n-dimensional input vector * @return The m-dimensional output vector. */ - public double[] doEvaluation(double[] x) { + public double[] eval(double[] x) { double[] result = new double[1]; result[0] = 0; for (int i = 0; i < x.length; i++) { @@ -189,29 +159,14 @@ public class F1Problem extends AbstractOptimizationProblem implements Interface2 * @return The name. */ public String getName() { - return "F1 Problem"; + return "F1-Problem"; } /** This method returns a global info string * @return description */ public String globalInfo() { - return "Sphere model."; - } - - /** This method allows you to choose how much noise is to be added to the - * fitness. This can be used to make the optimization problem more difficult. - * @param noise The sigma for a gaussian random number. - */ - public void setNoise(double noise) { - if (noise < 0) noise = 0; - this.m_Noise = noise; - } - public double getNoise() { - return this.m_Noise; - } - public String noiseTipText() { - return "Noise level on the fitness value."; + return "F1: multidimensional parabola problem"; } /** This method allows you to set/get an offset for decision variables. @@ -264,49 +219,15 @@ public class F1Problem extends AbstractOptimizationProblem implements Interface2 public String useTestConstraintTipText() { return "Just a simple test constraint of x[0] >= 1."; } - - /** This method allows you to choose the EA individual - * @param indy The EAIndividual type - */ - public void setEAIndividual(InterfaceDataTypeDouble indy) { - this.m_Template = (AbstractEAIndividual)indy; - } - public InterfaceDataTypeDouble getEAIndividual() { - return (InterfaceDataTypeDouble)this.m_Template; - } + public double functionValue(double[] point) { double x[] = new double[m_ProblemDimension]; for (int i=0; i 1) k = 1; this.m_k = k; } - public double getk() { + public double getK() { return this.m_k; } public String kTipText() { diff --git a/src/javaeva/server/go/strategies/ParticleSwarmOptimization.java b/src/javaeva/server/go/strategies/ParticleSwarmOptimization.java index 6c91f875..9aa2d9d2 100644 --- a/src/javaeva/server/go/strategies/ParticleSwarmOptimization.java +++ b/src/javaeva/server/go/strategies/ParticleSwarmOptimization.java @@ -1465,12 +1465,14 @@ public class ParticleSwarmOptimization implements InterfaceOptimizer, java.io.Se result += this.m_Population.getStringRepresentation(); return result; } + /** This method allows you to set an identifier for the algorithm * @param name The indenifier */ public void SetIdentifier(String name) { this.m_Identifier = name; } + public String getIdentifier() { return this.m_Identifier; } @@ -1566,7 +1568,7 @@ public class ParticleSwarmOptimization implements InterfaceOptimizer, java.io.Se * * @param tau2 the */ - public void setWithConstriction(double tau1, double tau2) { + protected void setWithConstriction(double tau1, double tau2) { double pSum = tau1+tau2; if (pSum <= 4) { System.err.println("error, invalid tauSum value in PSO::setWithConstriction"); @@ -1619,6 +1621,31 @@ public class ParticleSwarmOptimization implements InterfaceOptimizer, java.io.Se return "Acceleration for the social model."; } + /** + * Set the phi1 / phi2 parameter values (and in the constriction variant, adapt constriction factor). + * + * @param phi1 + * @param phi2 + */ + public void setPhiValues(double phi1, double phi2) { + m_Phi1 = phi1; + m_Phi2 = phi2; + if (algType.isSelectedString("Constriction")) setWithConstriction(phi1, phi2); + } + + /** + * Directly set all parameter values phi1, phi2 and inertness/constriction factor. + * + * @param phi1 + * @param phi2 + * @param inertness + */ + public void setParameterValues(double phi1, double phi2, double inertness) { + m_Phi1 = phi1; + m_Phi2 = phi2; + setInertnessOrChi(inertness); + } + /** This method allows you to choose the topology type. * @param s The type. */ diff --git a/src/javaeva/server/go/strategies/Tribes.java b/src/javaeva/server/go/strategies/Tribes.java index add1f383..4a38898f 100644 --- a/src/javaeva/server/go/strategies/Tribes.java +++ b/src/javaeva/server/go/strategies/Tribes.java @@ -624,11 +624,14 @@ public class Tribes implements InterfaceOptimizer, java.io.Serializable { * of the indiviuals in the beginning of the run, the indiviudals will be discarded. */ public void setPopulation(Population pop) { + if (pop == null) return; population = pop; if (population.get(0) instanceof InterfaceESIndividual) { range = ((InterfaceESIndividual)population.get(0)).getDoubleRange(); setDimension(range.length); - } else System.err.println("warning, population of non InterfaceESIndividuals. TRIBES couldnt correctly init the problem range."); + } else { + System.err.println("warning, TRIBES requires InterfaceESIndidivual instead of " + population.get(0).getClass() + ". Couldnt correctly init the problem range."); + } } private void setDimension(int length) { diff --git a/src/javaeva/server/go/tools/RandomNumberGenerator.java b/src/javaeva/server/go/tools/RandomNumberGenerator.java index d49a1e6a..291381ba 100644 --- a/src/javaeva/server/go/tools/RandomNumberGenerator.java +++ b/src/javaeva/server/go/tools/RandomNumberGenerator.java @@ -6,7 +6,6 @@ import java.util.ArrayList; public class RandomNumberGenerator extends Random { private static Random random; private static long randomSeed; - //private static int counter =0; /** * */ @@ -16,23 +15,11 @@ public class RandomNumberGenerator extends Random { //System.out.println("randomSeed ="+ randomSeed); random=new Random(randomSeed); } + /** * */ - public static void setseed(long x) { - //System.out.println("!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!seeeeed"+x+"counter"+counter); - //counter=0; - randomSeed=x; - if (x==0) - randomSeed=System.currentTimeMillis(); -// if (x==999) // ??? removed (MK) -// return; - random=new Random(randomSeed); - } - /** - * - */ - public static void setRandomseed() { + public static void setRandomSeed() { //counter++; randomSeed=System.currentTimeMillis(); random=new Random(randomSeed); @@ -50,7 +37,8 @@ public class RandomNumberGenerator extends Random { public static void setRandomSeed(long new_seed){ //counter++; randomSeed=new_seed; - random.setSeed(randomSeed); + if (randomSeed == 0) setRandomSeed(); + else random.setSeed(randomSeed); } /** * @@ -282,5 +270,17 @@ public class RandomNumberGenerator extends Random { } return x; } + + /** + * Adds Gaussian noise to a double vector + * @param v the double vector + * @param dev the Gaussian deviation + */ + public static void addNoise(double[] v, double dev) { + for (int i=0; i textListeners; + + public AbstractStatistics() { + firstPlot = true; + functionCalls = 0; + functionCallSum = 0; + convergenceCnt = 0; + optRunsPerformed = 0; + + textListeners = new ArrayList(); + } + + public void addTextListener(InterfaceTextListener listener) { + textListeners.add(listener); + } + + public boolean removeTextListener(InterfaceTextListener listener) { + return textListeners.remove(listener); + } + + protected void initOutput() { + SimpleDateFormat formatter = new SimpleDateFormat( + "E'_'yyyy.MM.dd'_at_'hh.mm.ss"); + startDate = formatter.format(new Date()); + startTime = System.currentTimeMillis(); + // open the result file: + String resFName = m_StatisticsParameter.getResultFileName(); + if (!resFName.equalsIgnoreCase("none") && !resFName.equals("")) { + String name = resFName + "_" + startDate + ".txt"; + if (TRACE) System.out.println("FileName =" + name); + try { + resultOut = new PrintWriter(new FileOutputStream(name)); + } catch (Exception e) { + e.printStackTrace(); + System.out.println("Error: " + e); + } + resultOut.println("StartDate:" + startDate); + resultOut.println("On Host:" + getHostName()); + } else resultOut = null; + } + + public void startOptPerformed(String infoString, int runNumber) { + if (TRACE) System.out.println("AbstractStatistics.startOptPerformed " + runNumber); + if (runNumber == 0) { + functionCallSum = 0; + firstPlot = true; + optRunsPerformed = 0; + convergenceCnt = 0; + m_StatisticsParameter.saveInstance(); + initOutput(); + bestCurrentIndividual = null; + bestIndivdualAllover = null; + } + functionCalls = 0; + } + + public void stopOptPerformed(boolean normal) { + if (TRACE) System.out.println("AbstractStatistics.stopOptPerformed"); + optRunsPerformed++; + functionCallSum += functionCalls; + // check for convergence + if (bestCurrentIndividual != null) { + if (StatisticUtils.norm(bestCurrentIndividual.getFitness()) < this.m_StatisticsParameter.getConvergenceRateThreshold()) { + convergenceCnt++; + } + printToTextListener(" Best solution: " + BeanInspector.toString(bestCurrentIndividual) + "\n"); + printToTextListener(AbstractEAIndividual.getDefaultDataString(bestCurrentIndividual) + "\n"); + } + if (currentBestFit!= null) { + printToTextListener(" Best Fitness: " + BeanInspector.toString(currentBestFit) + "\n"); + } + if (optRunsPerformed == m_StatisticsParameter.getMultiRuns()) finalizeOutput(); + } + + protected void finalizeOutput() { + printToTextListener("*******\n Reached target " + convergenceCnt + " times with threshold " + m_StatisticsParameter.getConvergenceRateThreshold() + ", rate " + convergenceCnt/(double)m_StatisticsParameter.getMultiRuns() + '\n'); + printToTextListener("Best overall individual: " + BeanInspector.toString(bestIndivdualAllover) + '\n'); + printToTextListener(" solution : " + AbstractEAIndividual.getDefaultDataString(bestIndivdualAllover) + '\n'); + printToTextListener(" fitness : " + BeanInspector.toString(bestIndivdualAllover.getFitness()) + '\n'); + if (TRACE) + System.out.println("stopOptPerformed"); + if (TRACE) + System.out.println("End of run"); + if (resultOut != null) { + SimpleDateFormat formatter = new SimpleDateFormat( + "E'_'yyyy.MM.dd'_at_'hh:mm:ss"); + String StopDate = formatter.format(new Date()); + resultOut.println("StopDate:" + StopDate); + resultOut.close(); + } + } + + public abstract String getHostName(); + + public void printToTextListener(String s) { + if ((resultOut != null)) resultOut.print(s); + for (InterfaceTextListener l : textListeners) { + if (m_StatisticsParameter.isShowTextOutput()) l.print(s); + } + } + + public StatisticsParameter getStatisticsParameter() { + return m_StatisticsParameter; + } + + protected boolean doTextOutput() { + return (resultOut != null) || (textListeners.size()>0); + } + + protected String getOutputHeader(InterfaceAdditionalPopulationInformer informer, PopulationInterface pop) { + String headline = "Fit.-calls \t Best \t Mean \t Worst "; + if (informer == null) + return headline; + else return headline + "\t " + informer.getAdditionalFileStringHeader(pop); + } + + protected String getOutputLine(InterfaceAdditionalPopulationInformer informer, PopulationInterface pop) { + StringBuffer sbuf = new StringBuffer(Integer.toString(functionCalls)); + sbuf.append("\t"); + sbuf.append(BeanInspector.toString(currentBestFit)); + sbuf.append("\t"); + if (meanFitness != null) { + sbuf.append(BeanInspector.toString(meanFitness)); + sbuf.append(" \t "); + } else sbuf.append("- \t "); + if (currentWorstFit != null) { + sbuf.append(BeanInspector.toString(currentWorstFit)); + sbuf.append(" \t "); + } else sbuf.append(" - \t "); + if (informer != null) { + sbuf.append(informer.getAdditionalFileStringValue(pop)); + } +// if (m_BestIndividual instanceof AbstractEAIndividual) { +// sbuf.append(((AbstractEAIndividual)m_BestIndividual).getStringRepresentation()); +// } else { +// sbuf.append(m_BestIndividual.toString()); +// } + + return sbuf.toString(); + } + + /** + * + */ + public synchronized void createNextGenerationPerformed(double[] bestfit, + double[] worstfit, int calls) { + functionCalls = calls; + currentBestFit = bestfit; + currentWorstFit = worstfit; + meanFitness = null; + + if (firstPlot) { + initPlots(m_StatisticsParameter.getPlotDescriptions()); + if (doTextOutput()) printToTextListener(getOutputHeader(null, null)+'\n'); + firstPlot = false; + } + + if (doTextOutput()) printToTextListener(getOutputLine(null, null)+'\n'); + plotCurrentResults(); + } + + /** + * If the population returns a specific data array, this method is called instead of doing standard output + * @param pop + * @param informer + */ + public abstract void plotSpecificData(PopulationInterface pop, InterfaceAdditionalPopulationInformer informer); + + protected abstract void plotCurrentResults(); + + /** + * Called at the very first (multirun mode) plot of a fitness curve. + */ + protected abstract void initPlots(List description); + + /** + * Do some data collection on the population. The informer parameter will not be handled by this method. + * + */ + public synchronized void createNextGenerationPerformed(PopulationInterface + pop, InterfaceAdditionalPopulationInformer informer) { + if (firstPlot) { + initPlots(m_StatisticsParameter.getPlotDescriptions()); + if (doTextOutput()) printToTextListener(getOutputHeader(informer, pop)+'\n'); + firstPlot = false; + } + if (pop.getSpecificData() != null) { + plotSpecificData(pop, informer); + return; + } + // by default plotting only the best + bestCurrentIndividual = pop.getBestIndividual().getClone(); + if ((bestIndivdualAllover == null) || (secondIsBetter(bestIndivdualAllover, bestCurrentIndividual))) { + bestIndivdualAllover = bestCurrentIndividual; +// printToTextListener("new best found!, last was " + BeanInspector.toString(bestIndivdualAllover) + "\n"); + } + +// IndividualInterface WorstInd = Pop.getWorstIndividual(); + if (bestCurrentIndividual == null) { + System.err.println("createNextGenerationPerformed BestInd==null"); + } + + currentBestFit = bestCurrentIndividual.getFitness().clone(); + if (currentBestFit == null) { + System.err.println("BestFitness==null !"); + } + meanFitness = pop.getMeanFitness().clone(); + currentWorstFit = pop.getWorstIndividual().getFitness().clone(); + functionCalls = pop.getFunctionCalls(); + + if (doTextOutput()) printToTextListener(getOutputLine(informer, pop)+'\n'); + plotCurrentResults(); + } + + private boolean secondIsBetter(IndividualInterface indy1, IndividualInterface indy2) { + if (indy1 == null) return true; + if (indy2 == null) return false; + if (indy1 instanceof AbstractEAIndividual) return ((AbstractEAIndividual)indy2).isDominatingDebConstraints((AbstractEAIndividual)indy1); + return (indy1.isDominant(indy2)); + } + + public double[] getBestFitness() { + return currentBestFit; + } + + public IndividualInterface getBestSolution() { + return bestIndivdualAllover; + } + + public int getFitnessCalls() { + return functionCalls; + } +} diff --git a/src/javaeva/server/stat/Statistics.java b/src/javaeva/server/stat/InterfaceStatistics.java similarity index 75% rename from src/javaeva/server/stat/Statistics.java rename to src/javaeva/server/stat/InterfaceStatistics.java index e17ce75c..9dfcddd5 100644 --- a/src/javaeva/server/stat/Statistics.java +++ b/src/javaeva/server/stat/InterfaceStatistics.java @@ -12,20 +12,24 @@ package javaeva.server.stat; /*==========================================================================* * IMPORTS *==========================================================================*/ +import javaeva.server.go.IndividualInterface; import javaeva.server.go.PopulationInterface; +import javaeva.server.go.problems.InterfaceAdditionalPopulationInformer; /*==========================================================================* * INTERFACE DECLARATION *==========================================================================*/ /** * */ -public interface Statistics { +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); + public void createNextGenerationPerformed(PopulationInterface Pop, InterfaceAdditionalPopulationInformer informer); public void createNextGenerationPerformed(double[] bestfit,double[] worstfit,int calls); public StatisticsParameter getStatisticsParameter(); // called from moduleadapter - public Object getBestSolution(); // returns the best overall solution + 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 new file mode 100644 index 00000000..eaa8bba0 --- /dev/null +++ b/src/javaeva/server/stat/InterfaceTextListener.java @@ -0,0 +1,5 @@ +package javaeva.server.stat; + +public interface InterfaceTextListener { + public void print(String str); +} diff --git a/src/javaeva/server/stat/LoggerInterface.java b/src/javaeva/server/stat/LoggerInterface.java deleted file mode 100644 index 03e529d1..00000000 --- a/src/javaeva/server/stat/LoggerInterface.java +++ /dev/null @@ -1,24 +0,0 @@ -package javaeva.server.stat; -/* - * Title: JavaEvA - * Description: - * Copyright: Copyright (c) 2003 - * Company: University of Tuebingen, Computer Architecture - * @author Holger Ulmer, Felix Streichert, Hannes Planatscher - * @version: $Revision: 10 $ - * $Date: 2006-01-18 11:02:22 +0100 (Wed, 18 Jan 2006) $ - * $Author: streiche $ - */ -/*==========================================================================* - * IMPORTS - *==========================================================================*/ -/*==========================================================================* -* INTERFACE DECLARATION -*==========================================================================*/ -/** - * - */ -public interface LoggerInterface { - public void log(double[] values); - public void setlogInfo(String[] infos); -} \ No newline at end of file diff --git a/src/javaeva/server/stat/ProcessControlerInterface.java b/src/javaeva/server/stat/ProcessControlerInterface.java deleted file mode 100644 index 2f4473cd..00000000 --- a/src/javaeva/server/stat/ProcessControlerInterface.java +++ /dev/null @@ -1,26 +0,0 @@ -package javaeva.server.stat; -/* - * Title: JavaEvA - * Description: - * Copyright: Copyright (c) 2003 - * Company: University of Tuebingen, Computer Architecture - * @author Holger Ulmer, Felix Streichert, Hannes Planatscher - * @version: $Revision: 10 $ - * $Date: 2006-01-18 11:02:22 +0100 (Wed, 18 Jan 2006) $ - * $Author: streiche $ - */ -/*==========================================================================* - * IMPORTS - *==========================================================================*/ -/*==========================================================================* -* INTERFACE DECLARATION -*==========================================================================*/ -/** - * - */ -public interface ProcessControlerInterface { - public void startOptPerformed(String InfoString); - public void stopOptPerformed(); - public void printToTextListener(String s); - public StatisticsParameter getStatistisParameter(); -} \ No newline at end of file diff --git a/src/javaeva/server/stat/StatisticsParameter.java b/src/javaeva/server/stat/StatisticsParameter.java index 27326f48..5df2f2dc 100644 --- a/src/javaeva/server/stat/StatisticsParameter.java +++ b/src/javaeva/server/stat/StatisticsParameter.java @@ -12,7 +12,8 @@ package javaeva.server.stat; /*==========================================================================* * IMPORTS *==========================================================================*/ -import javaeva.tools.Tag; +import java.util.List; + import javaeva.tools.SelectedTag; /*==========================================================================* * INTERFACE DECLARATION @@ -24,23 +25,34 @@ public interface StatisticsParameter { public String getName(); public void saveInstance(); public String globalInfo(); - public void setTextoutput(int i); +// public void setTextoutput(int i); public void setPlotoutput(int i); public int GetPlotoutput(); - public int GetTextoutput(); - public String textoutputTipText(); - public String plotFrequencyTipText(); +// public int GetTextoutput(); +// public String textoutputTipText(); +// public String plotFrequencyTipText(); public void setMultiRuns(int x); public int getMultiRuns(); public String multiRunsTipText(); + public String GetInfoString(); public void setInfoString(String s); - public void setResultFileName(String x); + public boolean GetuseStatPlot(); public void setuseStatPlot(boolean x); + + public List getPlotDescriptions(); + public SelectedTag getPlotFitness(); public void setPlotFitness(SelectedTag newMethod); + public String getResultFileName(); + public void setResultFileName(String x); + public void setConvergenceRateThreshold(double x); public double getConvergenceRateThreshold(); + + public boolean isShowTextOutput(); + public void setShowTextOutput(boolean bShow); +// public String showTextOutputTipText(); } \ No newline at end of file diff --git a/src/javaeva/server/stat/StatisticsParameterImpl.java b/src/javaeva/server/stat/StatisticsParameterImpl.java index 91e55819..cbf80da8 100644 --- a/src/javaeva/server/stat/StatisticsParameterImpl.java +++ b/src/javaeva/server/stat/StatisticsParameterImpl.java @@ -14,6 +14,8 @@ package javaeva.server.stat; * IMPORTS *==========================================================================*/ import java.io.Serializable; +import java.util.ArrayList; + import javaeva.tools.Serializer; import javaeva.tools.Tag; import javaeva.tools.SelectedTag; @@ -43,6 +45,7 @@ public class StatisticsParameterImpl implements StatisticsParameter, Serializabl protected String m_InfoString = ""; private boolean m_useStatPlot = true; private double m_ConvergenceRateThreshold=0.001; + private boolean showTextOutput = true; /** * */ @@ -70,6 +73,28 @@ public class StatisticsParameterImpl implements StatisticsParameter, Serializabl return ret; } + /** + * Return a list of String arrays describing the selected plot options, e.g. {"Best"} or {"Best", "Worst"}. + * For now, only one array is returned. + * + * @return a list of String arrays describing the selected plot options + */ + public ArrayList getPlotDescriptions() { + ArrayList desc = new ArrayList(); + switch (getPlotFitness().getSelectedTagID()) { + case StatisticsParameterImpl.PLOT_BEST_AND_WORST: + desc.add(new String[] {"Best", "Worst"}); + break; + case StatisticsParameterImpl.PLOT_BEST: + desc.add(new String[] {"Best"}); + break; + case StatisticsParameterImpl.PLOT_WORST: + desc.add(new String[] {"Worst"}); + break; + } + return desc; + } + /** * */ @@ -108,28 +133,6 @@ public class StatisticsParameterImpl implements StatisticsParameter, Serializabl return "Set of parameter describing the statistics which logs the state of the optimization."; } - /** - * - */ - public void setTextoutput(int i) { - if (i >= 0) - m_Textoutput = i; - } - - /** - * - */ - public int GetTextoutput() { - return m_Textoutput; - } - - /** - * - */ - public String textoutputTipText() { - return "Describes how often information is printed in the textoutput frame. textoutput=1 -> there is a output every generation. textoutput<0 -> there is no text output"; - } - /** * */ @@ -144,12 +147,12 @@ public class StatisticsParameterImpl implements StatisticsParameter, Serializabl return m_Plotoutput; } - /** - * - */ - public String plotFrequencyTipText() { - return "Frequency how often the fitness plot gets an update. plotoutput=1 -> there is a output every generation. plotoutput<0 -> there is no plot output"; - } +// /** +// * +// */ +// public String plotFrequencyTipText() { +// return "Frequency how often the fitness plot gets an update. plotoutput=1 -> there is a output every generation. plotoutput<0 -> there is no plot output"; +// } /** * @@ -267,7 +270,7 @@ public class StatisticsParameterImpl implements StatisticsParameter, Serializabl * */ public String resultFileNameTipText() { - return "File name for the result file, if 'none' no output file will be created."; + return "File name for the result file. If empty or 'none', no output file will be created."; } public String convergenceRateThresholdTipText() { @@ -284,9 +287,27 @@ public class StatisticsParameterImpl implements StatisticsParameter, Serializabl /** * - * @param x */ public double getConvergenceRateThreshold() { return m_ConvergenceRateThreshold; } + + /** + * @return the showOutputData + */ + public boolean isShowTextOutput() { + return showTextOutput; + } + + /** + * + * @param showOutputData the showOutputData to set + */ + public void setShowTextOutput(boolean bShow) { + this.showTextOutput = bShow; + } + + public String showTextOutputTipText() { + return "Indicates whether further text output should be printed"; + } } \ No newline at end of file diff --git a/src/javaeva/server/stat/StatisticsStandalone.java b/src/javaeva/server/stat/StatisticsStandalone.java index 87f78a6f..c86eb1aa 100644 --- a/src/javaeva/server/stat/StatisticsStandalone.java +++ b/src/javaeva/server/stat/StatisticsStandalone.java @@ -18,15 +18,12 @@ import java.io.FileOutputStream; import java.io.PrintWriter; import java.io.Serializable; import java.net.InetAddress; -import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.Arrays; -import java.util.Date; +import java.util.List; -import wsi.ra.tool.StatisticUtils; - -import javaeva.server.go.IndividualInterface; import javaeva.server.go.PopulationInterface; +import javaeva.server.go.problems.InterfaceAdditionalPopulationInformer; /* * ==========================================================================* @@ -36,408 +33,276 @@ import javaeva.server.go.PopulationInterface; /** * */ -public class StatisticsStandalone implements Statistics, Serializable { - public final static boolean TRACE = false; - private static String m_MyHostName = "not def"; +public class StatisticsStandalone extends AbstractStatistics implements InterfaceStatistics, Serializable { - private long m_StartTime; - private String m_StartDate; + /** + * + */ + private static final long serialVersionUID = 2621394534751748968L; - private IndividualInterface m_BestIndividual; + private static String m_MyHostName = "not def"; - private int m_FunctionCalls; - private int m_OptRunsPerformed; - private String m_InfoString; - private ArrayList m_Result; - private ArrayList m_ResultString; - private boolean m_useMedian = false; - private boolean m_TimeTrace; + private String m_InfoString; + private ArrayList[]> m_Result; + private ArrayList m_ResultString; +// private boolean m_useMedian = false; - private double[] m_SpecificData; - private StatisticsParameter m_StatisticsParameter; - private boolean m_NoTrace; - private double m_FitnessMeanofALL; - private double m_SumOfBestFit = 0; - private int m_FunctionALLCalls; - private int m_NumberOfConvergence; - private double[] m_BestFitnessAtEnd; - private double m_ConvergenceRate; - private double m_FitnessMedianofALL; - /** - * - */ - public StatisticsStandalone(boolean trace) { - m_NoTrace = trace; - m_StatisticsParameter = new StatisticsParameterImpl(); - try { - m_MyHostName = InetAddress.getLocalHost().getHostName(); - } catch (Exception e) { - System.out.println("ERROR getting HostName " + e.getMessage()); - } - m_OptRunsPerformed = 0; - m_NumberOfConvergence = 0; - m_FunctionALLCalls = 0; + private double m_FitnessMeanofALL; + private double m_SumOfBestFit = 0; + private double[] m_BestFitnessAtEnd; + private double m_FitnessMedianofALL; + /** + * + */ + public StatisticsStandalone(StatisticsParameter statParams) { + super(); + m_StatisticsParameter = statParams; + try { + m_MyHostName = InetAddress.getLocalHost().getHostName(); + } catch (Exception e) { + System.out.println("ERROR getting HostName " + e.getMessage()); + } + } - } + /** + * + */ + public StatisticsStandalone(String resultFileName) { + this(new StatisticsParameterImpl()); + m_StatisticsParameter.setResultFileName(resultFileName); + } - /** - * - */ - public StatisticsStandalone() { - m_StatisticsParameter = new StatisticsParameterImpl(); - try { - m_MyHostName = InetAddress.getLocalHost().getHostName(); - } catch (Exception e) { - System.out.println("ERROR getting HostName " + e.getMessage()); - } - m_OptRunsPerformed = 0; - m_NumberOfConvergence = 0; - m_FunctionALLCalls = 0; + /** + * + */ + public StatisticsStandalone() { + this(new StatisticsParameterImpl()); + } + + protected void initPlots(List description) { + if (m_Result.size() == 0) + initContainer(new String[] {"Fitness"}); + } + + protected void plotCurrentResults() { + ((ArrayList[]) m_Result.get(0))[optRunsPerformed].add(new double[] {functionCalls, currentBestFit[0]}); + } - } + public void plotSpecificData(PopulationInterface pop, InterfaceAdditionalPopulationInformer informer) { + if (TRACE) System.out.println(" m_SpecificData !!"); + double[] specificData = pop.getSpecificData(); + if (specificData != null) { + for (int i = 0; i < specificData.length; i++) { + ((ArrayList[]) m_Result.get(i))[optRunsPerformed].add(new double[] {functionCalls, specificData[i]}); + } + } + } + + /** + * + */ + private void initContainer(String[] description) { + for (int i = 0; i < description.length; i++) { + m_Result.add(new ArrayList[m_StatisticsParameter.getMultiRuns()]); + m_ResultString.add(description[i]); + } + for (int i = 0; i < m_Result.size(); i++) + ((ArrayList[]) m_Result.get(i))[optRunsPerformed] = new ArrayList(); + } - /** - * - */ - public void setTimeTrace() { - m_TimeTrace = true; - } + /** + * + */ + public void startOptPerformed(String infoString, int runNumber) { + super.startOptPerformed(infoString, runNumber); + if (runNumber == 0) { + m_Result = new ArrayList[]>(); + m_ResultString = new ArrayList(); + m_BestFitnessAtEnd = new double[this.m_StatisticsParameter.getMultiRuns()]; + } else { + for (int i = 0; i < m_Result.size(); i++) + ((ArrayList[]) m_Result.get(i))[optRunsPerformed] = new ArrayList[]>(); + } + m_InfoString = infoString; + } + + /** + * + */ + public void stopOptPerformed(boolean normal) { + super.stopOptPerformed(normal); - /** - * - */ - public synchronized void createNextGenerationPerformed(double[] bestfit, double[] worstfit, int calls) { - m_FunctionCalls = calls; - if (m_Result.size() == 0) - initContainer(new String[] {"Fitness"}); - ((ArrayList[]) m_Result.get(0))[m_OptRunsPerformed].add(new double[] {m_FunctionCalls, bestfit[0]}); + if (bestCurrentIndividual != null) { + m_SumOfBestFit = m_SumOfBestFit + bestCurrentIndividual.getFitness()[0]; + m_BestFitnessAtEnd[optRunsPerformed-1] = bestCurrentIndividual.getFitness()[0]; + } - } + //System.out.println("stopOptPerformed :"+m_OptRunsPerformed); + if (optRunsPerformed == m_StatisticsParameter.getMultiRuns()) { + m_FitnessMeanofALL = m_SumOfBestFit / ((double) optRunsPerformed); + //System.out.println("m_FitnessMeanofALL "+m_FitnessMeanofALL); + m_FitnessMedianofALL = getMedian(m_BestFitnessAtEnd); - /** - * - */ - public void createNextGenerationPerformed(double bestfit, int calls) { - if (m_TimeTrace == true) - m_FunctionCalls = (int) (System.currentTimeMillis() - m_StartTime); - else - m_FunctionCalls = calls; - if (m_Result.size() == 0) - initContainer(new String[] {"Fitness"}); - ((ArrayList[]) m_Result.get(0))[m_OptRunsPerformed].add(new double[] { - m_FunctionCalls, bestfit}); - } + finalizeOutput(); + } + } + + /** + * + */ + private static double getMedian(double[] in) { + double[] x = (double[]) in.clone(); +// double ret = 0; + Arrays.sort(x); + int m = (int) (x.length / 2.0); + return x[m]; + } - /** - * - */ - public void createNextGenerationPerformed(PopulationInterface Pop) { - m_SpecificData = Pop.getSpecificData(); - if (m_TimeTrace == true) - m_FunctionCalls = (int) (System.currentTimeMillis() - m_StartTime); - else - m_FunctionCalls = Pop.getFunctionCalls(); - if (m_NoTrace == true) - return; - if (m_SpecificData != null) { - System.out.println(" m_SpecificData !!"); - for (int i = 0; i < m_SpecificData.length; i++) { - if (m_Result.size() == 0) - initContainer(Pop.getSpecificDataNames()); - ((ArrayList[]) m_Result.get(i))[m_OptRunsPerformed].add(new double[] {m_FunctionCalls, m_SpecificData[i]}); - } - return; - } - // then the default procedure on the best individual - this.m_BestIndividual = Pop.getBestIndividual(); - if (m_BestIndividual == null) { - System.out.println("createNextGenerationPerformed BestInd==null in StatisticsStandalone"); - return; - } - double BestFitness = m_BestIndividual.getFitness()[0]; - if (m_Result.size() == 0) - initContainer(new String[] {"Fitness"}); - ((ArrayList[]) m_Result.get(0))[m_OptRunsPerformed].add(new double[] {m_FunctionCalls, BestFitness}); - } + /** + * write result of all runs. + */ + public static File[] writeResult_All_Container(ArrayList StatList, String FileName) { + File ret[] = new File[((StatisticsStandalone) StatList.get(0)).m_Result.size()]; + //System.out.println("StatList.size " + StatList.size()); + for (int counter = 0; counter < ret.length; counter++) { + ArrayList staticResult = new ArrayList(); + String staticDescription = "calls "; + for (int index = 0; index < StatList.size(); index++) { + StatisticsStandalone Stat = (StatisticsStandalone) StatList.get(index); + staticDescription = staticDescription + Stat.m_InfoString + " "; + for (int row = 0; row < ((ArrayList[]) Stat.m_Result.get(counter))[0].size(); + row++) { + double mean = 0; + double calls = 0; + double[] value = new double[((ArrayList[]) Stat.m_Result.get(counter)). + length]; + for (int i = 0; i < ((ArrayList[]) Stat.m_Result.get(counter)).length; i++) { + //double[] result = (double[]) Stat.m_QRestultContainer[i].get(row); + double[] result = (double[]) ((ArrayList[]) Stat.m_Result.get(counter))[i].get(row); + mean = mean + result[1]; + calls = result[0]; + value[i] = result[1]; + } + //mean = mean / Stat.m_QRestultContainer.length; + mean = mean / ((ArrayList[]) Stat.m_Result.get(counter)).length; +// if (m_useMedian == true) // use the median +// mean = getMedian(value); + if (row == staticResult.size()) + staticResult.add(new String("" + calls)); + String temp = (String) staticResult.get(row); + String newrow = new String(temp + " " + mean); + //System.out.println("newrow"+newrow); + staticResult.set(row, newrow); + } // end of for row + } // end of for index + try { + File d = new File(m_MyHostName); + d.mkdir(); + String info = (String) ((StatisticsStandalone) StatList.get(0)).m_ResultString.get(counter); + ret[counter] = new File(m_MyHostName + "//" + FileName + "_" + info + "_" + counter + ".txt"); + ret[counter].createNewFile(); + PrintWriter Out = new PrintWriter(new FileOutputStream(ret[counter])); + Out.println(staticDescription); + for (int i = 0; i < staticResult.size(); i++) { + Out.println((String) staticResult.get(i)); + //System.out.println("print " + (String) staticResult.get(i)); + } + Out.flush(); + Out.close(); + } catch (Exception e) { + System.out.println("Error in wreiteresult" + e.getMessage()); + e.printStackTrace(); + } + staticResult = null; + staticDescription = ""; + } + return ret; + } - /** - * - */ - private void initContainer(String[] description) { - for (int i = 0; i < description.length; i++) { - m_Result.add(new ArrayList[m_StatisticsParameter.getMultiRuns()]); - m_ResultString.add(description[i]); - } - for (int i = 0; i < m_Result.size(); i++) - ((ArrayList[]) m_Result.get(i))[m_OptRunsPerformed] = new ArrayList(); - } +// /** +// * write result of all runs. +// */ +// public static File writeResultErrorBar(ArrayList StatList, String FileName) { +// File ret = null; +// ArrayList staticResult = new ArrayList(); +// String staticDescription = ""; +// for (int index = 0; index < StatList.size(); index++) { +// StatisticsStandalone Stat = (StatisticsStandalone) StatList.get(index); +// staticDescription = staticDescription + Stat.m_InfoString + " "; +// System.out.println(" laenge m_result "+Stat.m_Result.size()); +// for (int i=0;i end"); + addTextListener(m_ProxyPrinter); + if (TRACE) System.out.println("Constructor RMIStatistics --> end"); } /** * */ - public synchronized void startOptPerformed(String InfoString, int runnumber) { - if (runnumber == 0) { - m_OptRunsPerformed = 0; - m_ConvergenceCnt = 0; - m_firstPlot = true; - m_StatisticsParameter.saveInstance(); - } - if (TRACE) - System.out.println("Statistics.startOptPerformed " + runnumber); - m_GraphInfoString = InfoString; - m_StartTime = System.currentTimeMillis(); - m_TextCounter = m_StatisticsParameter.GetTextoutput(); + public synchronized void startOptPerformed(String infoString, int runNumber) { + super.startOptPerformed(infoString, runNumber); + + m_GraphInfoString = infoString; + +// m_TextCounter = m_StatisticsParameter.GetTextoutput(); m_PlotCounter = m_StatisticsParameter.GetPlotoutput(); - if (m_OptRunsPerformed == 0) { - SimpleDateFormat formatter = new SimpleDateFormat( - "E'_'yyyy.MM.dd'_at_'hh.mm.ss"); - m_StartDate = formatter.format(new Date()); - // open the result file: - String x = m_StatisticsParameter.getResultFileName(); - if (!x.equalsIgnoreCase("none") && !x.equals("")) { - String name = x + "_" + m_StartDate + ".txt"; - if (TRACE) - System.out.println("FileName =" + name); - try { - m_ResultOut = new PrintWriter(new FileOutputStream(name)); - } catch (Exception e) { - e.printStackTrace(); - System.out.println("Error: " + e); - } - m_ResultOut.println("StartDate:" + m_StartDate); - m_ResultOut.println("On Host:" + m_MyHostName); - } else - m_ResultOut = null; - } } - /** - * - */ -// private void plotEndogenAttributes(PopulationInterface Pop) { -// if (m_StatisticsParameter.getPrintObjects() == false) -// return; -// double[] x = ( (IndividualInterface) (Pop.getBestIndividual())). -// getDoubleArray(); -// for (int ii = 0; ii < x.length; ii++) -// m_ObjectsGraph[ii /*+x.length*i*/].setConnectedPoint(m_FunctionCalls, -// x[ii]); -// //} -// } - - /** - * - */ public void stopOptPerformed(boolean normal) { - if (TRACE) - System.out.println("stopOptPerformed"); - m_OptRunsPerformed++; - // overall best objectives: - String s = ""; - if (m_BestSolution != null) { - for (int i = 0; i < m_BestSolution.length; i++) - s = s + " x[" + i + "]=" + m_BestSolution[i]; - } - printToTextListener(" Best solution objectives: " + s); - s = ""; - if (m_BestSolution != null) { - for (int i = 0; i < m_BestFitness.length; i++) - s = s + " f[" + i + "]=" + m_BestFitness[i]; - } - - if (m_BestIndividual != null) { - if (StatisticUtils.norm(m_BestIndividual.getFitness()) < this.m_StatisticsParameter.getConvergenceRateThreshold()) { - m_ConvergenceCnt++; - } - } + super.stopOptPerformed(normal); - printToTextListener(" Best solution fitness: " + s); - if (m_OptRunsPerformed <= m_StatisticsParameter.getMultiRuns()) { - if ((m_StatisticsParameter.getMultiRuns() > 1) && (m_StatGraph != null)) { - // unite the point sets for a multirun - for (int i = 0; i < m_FitnessGraph.length; i++) { - for (int j = 0; j < m_FitnessGraph[i].length; j++) { - // unite the graphs only if the break was "normal" - if (normal && m_FitnessFrame[i].isValid()) { - m_StatGraph[i][j].addGraph(m_FitnessGraph[i][j]); - m_StatGraph[i][j].setInfoString(m_FitnessGraph[i][j].getInfo() + - "_" + - m_StatisticsParameter.GetInfoString() + - " Mean of " + m_OptRunsPerformed + - " runs", - (float) 2.0); - m_FitnessGraph[i][j].clear(); - } + if (optRunsPerformed > m_StatisticsParameter.getMultiRuns()) System.err.println("error: this shouldnt happen (StatisticsWithGUI::stopOptPerformed)"); + // unite the graphs only if the break was "normal" + if (normal && (m_StatisticsParameter.getMultiRuns() > 1) && (m_StatGraph != null)) { + // unite the point sets for a multirun + for (int i = 0; i < m_FitnessGraph.length; i++) { + for (int j = 0; j < m_FitnessGraph[i].length; j++) { + if (m_FitnessFrame[i].isValid()) { + m_StatGraph[i][j].addGraph(m_FitnessGraph[i][j]); + m_StatGraph[i][j].setInfoString( + (m_FitnessGraph[i][j].getInfo().length() > 0 ? (m_FitnessGraph[i][j].getInfo() + "_") : "" ) + + (m_StatisticsParameter.GetInfoString().length() > 0 ? (m_StatisticsParameter.GetInfoString() + "_") : "" ) + + m_StatisticsParameter.GetInfoString() + + "Mean_of_" + optRunsPerformed + " ", + (float) 2.0); + m_FitnessGraph[i][j].clear(); } } - } else { - // create new graphs?? seems superfluous here. (MK) -// for (int i = 0; i < m_FitnessFrame.length; i++) { -// for (int j = 0; j < m_FitnessGraph[i].length; j++) { -// m_FitnessGraph[i][j] = m_FitnessFrame[i].getNewGraph( -// m_StatisticsParameter.GetInfoString() + m_GraphInfoString); -// -// } -// } - } - } - if (m_OptRunsPerformed == m_StatisticsParameter.getMultiRuns()) { - printToTextListener("*******\n Reached target " + m_ConvergenceCnt + " times with threshold " + m_StatisticsParameter.getConvergenceRateThreshold() + ", rate " + m_ConvergenceCnt/(double)m_StatisticsParameter.getMultiRuns()); - m_OptRunsPerformed = 0; - m_ConvergenceCnt = 0; - if (TRACE) - System.out.println("stopOptPerformed"); - if (TRACE) - System.out.println("End of run"); - if (m_ResultOut != null) { - SimpleDateFormat formatter = new SimpleDateFormat( - "E'_'yyyy.MM.dd'_at_'hh:mm:ss"); - String StopDate = formatter.format(new Date()); - m_ResultOut.println("StopDate:" + StopDate); - m_ResultOut.close(); } } + // this is inconsistent, shouldnt be necessary here but reset in startOpt... +// if (optRunsPerformed == m_StatisticsParameter.getMultiRuns()) { +// finalizeRuns(m_ConvergenceCnt); +// m_OptRunsPerformed = 0; +// m_ConvergenceCnt = 0; +// } } - /** - * Called at the very first (multirun mode) plot of a fitness curve. - */ - private void initPlots(ArrayList description) { - if (TRACE) - System.out.println("initPlots"); - m_firstPlot = false; + protected void initPlots(List description) { + if (TRACE) System.out.println("initPlots"); + if (m_ProxyPrinter != null) m_ProxyPrinter.setShow(m_StatisticsParameter.isShowTextOutput()); + m_FitnessFrame = new GraphWindow[description.size()]; for (int i = 0; i < m_FitnessFrame.length; i++) { - m_FitnessFrame[i] = GraphWindow.getInstance(m_MainAdapterClient, - m_GraphInfoString + " " + i + " " + " on " + m_MyHostName + ", VM " + EvAServer.m_NumberOfVM, "function calls", "fitness"); +// m_FitnessFrame[i] = GraphWindow.getInstance(m_MainAdapterClient, m_GraphInfoString + " " + i + " " + " on " + m_MyHostName + ", VM " + EvAServer.m_NumberOfVM, "function calls", "fitness"); + m_FitnessFrame[i] = GraphWindow.getInstance(m_MainAdapterClient, "Optimization " + i + " " + " on " + m_MyHostName + ", VM " + EvAServer.m_NumberOfVM, "function calls", "fitness"); } m_FitnessGraph = new Graph[description.size()][]; @@ -267,6 +155,7 @@ public class StatisticsWithGUI implements Serializable, Statistics { m_FitnessGraph[i] = new Graph[((String[]) description.get(i)).length]; for (int j = 0; j < m_FitnessGraph[i].length; j++) { String[] d = (String[]) description.get(i); + // this is where the column string for ascii export is created! m_FitnessGraph[i][j] = m_FitnessFrame[i].getNewGraph(d[j] + "_" + m_StatisticsParameter.GetInfoString() + @@ -308,94 +197,7 @@ public class StatisticsWithGUI implements Serializable, Statistics { if (isValidGraph) m_FitnessGraph[graph][subGraph].setConnectedPoint(x, y); } - private ArrayList getDescription() { - ArrayList desc = new ArrayList(); - int fitnessplot_setting = 0; - fitnessplot_setting = m_StatisticsParameter.getPlotFitness(). - getSelectedTag().getID(); - switch (fitnessplot_setting) { - case StatisticsParameterImpl.PLOT_BEST_AND_WORST: - desc.add(new String[] {"Best", "Worst"}); - break; - case StatisticsParameterImpl.PLOT_BEST: - desc.add(new String[] {"Best"}); - break; - case StatisticsParameterImpl.PLOT_WORST: - desc.add(new String[] {"Worst"}); - break; - } - return desc; - } - - /** - * - */ - public synchronized void createNextGenerationPerformed(double[] bestfit, - double[] worstfit, int calls) { - m_FunctionCalls = calls; - m_BestFitness = bestfit; - m_WorstFitness = worstfit; - - if (m_firstPlot == true) { - initPlots(getDescription()); - } - plotCurrentResults(); - } - - /** - * - */ - public synchronized void createNextGenerationPerformed(PopulationInterface - Pop) { - m_SpecificData = Pop.getSpecificData(); - if (m_SpecificData != null) { - plotSpecificData(Pop); - return; - } - // by default plotting only the best - IndividualInterface BestInd = Pop.getBestIndividual(); - IndividualInterface WorstInd = Pop.getWorstIndividual(); - if (BestInd == null) { - System.err.println("createNextGenerationPerformed BestInd==null"); - return; - } - - - if (m_firstPlot == true) { - initPlots(getDescription()); - } - - double[] BestFitness = BestInd.getFitness(); - double[] WorstFitness = WorstInd.getFitness(); - if (BestFitness == null) - System.err.println("BestFitness==null !"); - m_BestIndividual = BestInd.getClone(); - m_BestSolution = (double[]) BestInd.getDoubleArray().clone(); - m_BestFitness = (double[]) BestFitness.clone(); - m_WorstFitness = (double[]) WorstFitness.clone(); - m_FunctionCalls = Pop.getFunctionCalls(); - - plotCurrentResults(); - } - - private void plotCurrentResults() { - // Text-Ouput - m_TextCounter--; - if (m_TextCounter == 0 || m_ResultOut != null) { - m_TextCounter = m_StatisticsParameter.GetTextoutput(); - String s = "calls , " + m_FunctionCalls + " bestfit , "; - for (int i = 0; i < m_BestFitness.length; i++) - s = s + m_BestFitness[i]; - - if (m_WorstFitness != null) { - s = s + " , worstfit , "; - for (int i = 0; i < m_WorstFitness.length; i++) - s = s + m_WorstFitness[i] + " , "; - } -// for (int i = 0; i < this.m_BestSolution.length; i++) -// s = s + " x[" + i + "]=" + m_BestSolution[i]; - printToTextListener(s); - } + protected void plotCurrentResults() { // Plots m_PlotCounter--; @@ -408,57 +210,29 @@ public class StatisticsWithGUI implements Serializable, Statistics { boolean doPlotWorst = (fitnessplot_setting == StatisticsParameterImpl.PLOT_WORST) || (fitnessplot_setting == StatisticsParameterImpl.PLOT_BEST_AND_WORST); if (doPlotBest) { - plotFitnessPoint(0, 0, m_FunctionCalls, m_BestFitness[0]); + plotFitnessPoint(0, 0, functionCalls, currentBestFit[0]); } if (doPlotWorst) { // schlechteste Fitness plotten m_PlotCounter = m_StatisticsParameter.GetPlotoutput(); - if (m_WorstFitness == null) { + if (currentWorstFit == null) { System.err.println("m_WorstFitness==null in plotStatisticsPerformed"); return; } - plotFitnessPoint(0, (doPlotBest ? 1 : 0) , m_FunctionCalls, m_WorstFitness[0]); + plotFitnessPoint(0, (doPlotBest ? 1 : 0) , functionCalls, currentWorstFit[0]); } } -// if (m_PlotCounter == 0) { -// m_PlotCounter = m_StatisticsParameter.GetPlotoutput(); -// // int fitnessplot_setting = m_StatisticsParameter.getPlotFitness().getSelectedTag().getID(); -// if ((fitnessplot_setting == StatisticsParameterImpl.PLOT_BEST) -// || -// (fitnessplot_setting == StatisticsParameterImpl.PLOT_BEST_AND_WORST)) { -// if (m_BestFitness == null) { -// System.out.println("m_BestFitness==null in plotStatisticsPerformed"); -// return; -// } -// m_FitnessGraph[0][0].setConnectedPoint(m_FunctionCalls, -// m_BestFitness[0]); -// } -// if ((fitnessplot_setting == StatisticsParameterImpl.PLOT_WORST) -// || -// (fitnessplot_setting == StatisticsParameterImpl.PLOT_BEST_AND_WORST)) { -// // schlecht. Fitness plotten -// m_PlotCounter = m_StatisticsParameter.GetPlotoutput(); -// if (m_WorstFitness == null) { -// System.out.println( -// "m_WorstFitness==null in plotStatisticsPerformed"); -// return; -// } -// m_FitnessGraph[0][m_FitnessGraph[0].length - -// 1].setConnectedPoint(m_FunctionCalls, m_WorstFitness[0]); -// } -// } - } /** * */ - public void plotSpecificData(PopulationInterface Pop) { - // What in the name of ... is this method?? - m_FunctionCalls = Pop.getFunctionCalls(); + public void plotSpecificData(PopulationInterface pop, InterfaceAdditionalPopulationInformer informer) { + double[] specificData = pop.getSpecificData(); + int calls = pop.getFunctionCalls(); ArrayList description = new ArrayList(); ArrayList temp = new ArrayList(); - String[] ss = Pop.getSpecificDataNames(); + String[] ss = pop.getSpecificDataNames(); for (int i = 0; i < ss.length; i++) { if (ss[i].lastIndexOf("*") == -1) { temp.add(ss[i]); @@ -476,23 +250,13 @@ public class StatisticsWithGUI implements Serializable, Statistics { description.add(line); } - if (m_firstPlot == true) - initPlots(description); - m_TextCounter--; - if (m_TextCounter == 0 || m_ResultOut != null) { - m_TextCounter = m_StatisticsParameter.GetTextoutput(); - String s = "calls , " + m_FunctionCalls + " bestfit , "; - for (int i = 0; i < m_BestFitness.length; i++) - s = s + m_BestFitness[i]; - - if (m_WorstFitness != null) { - s = s + " , worstfit , "; - for (int i = 0; i < m_WorstFitness.length; i++) - s = s + m_WorstFitness[i] + " , "; + if (doTextOutput()) { + String s = "calls , " + calls + " bestfit , "; + s = s + BeanInspector.toString(currentBestFit); + if (currentWorstFit != null) { + s = s + " , worstfit , " + BeanInspector.toString(currentWorstFit); } -// for (int i = 0; i < this.m_BestSolution.length; i++) -// s = s + " x[" + i + "]=" + m_BestSolution[i]; - printToTextListener(s); + printToTextListener(s + "\n"); } m_PlotCounter--; @@ -501,43 +265,15 @@ public class StatisticsWithGUI implements Serializable, Statistics { int index = 0; for (int i = 0; i < m_FitnessGraph.length; i++) { for (int j = 0; j < m_FitnessGraph[i].length; j++) { - plotFitnessPoint(i, j, m_FunctionCalls, m_SpecificData[index]); + plotFitnessPoint(i, j, calls, specificData[index]); index++; } } } } - - /** - * - */ - public void printToTextListener(String s) { -// if (m_StatisticsParameter.GetTextoutput() <= 0) -// return; - // System.out.println(s); - if (m_ResultOut != null) - m_ResultOut.println(s); - if (m_ProxyPrinter != null) - m_ProxyPrinter.print(s); - } - /** - * - */ - public StatisticsParameter getStatisticsParameter() { - return m_StatisticsParameter; - } - /** - * - */ - public Object getBestSolution() { - return m_BestSolution; - } - - /** - * - */ - public double[] getBestFitness() { - return m_BestFitness; + + public String getHostName() { + return m_MyHostName; } } \ No newline at end of file diff --git a/src/javaeva/tools/Mathematics.java b/src/javaeva/tools/Mathematics.java index 8d962a03..b0bcca05 100644 --- a/src/javaeva/tools/Mathematics.java +++ b/src/javaeva/tools/Mathematics.java @@ -122,7 +122,6 @@ public class Mathematics { } return linearInterpolation(x, x0, x1, f0, f1); } -//>>>>>>> .merge-right.r288 /** * @param f0 diff --git a/src/javaeva/tools/MatlabControl.java b/src/javaeva/tools/MatlabControl.java new file mode 100644 index 00000000..e461335e --- /dev/null +++ b/src/javaeva/tools/MatlabControl.java @@ -0,0 +1,284 @@ +package javaeva.tools; + +/* MatlabControl.java + * + * "Copyright (c) 2001 and The Regents of the University + * of California. All rights reserved. + * + * Permission to use, copy, modify, and distribute this software and its + * documentation for any purpose, without fee, and without written agreement is + * hereby granted, provided that the above copyright notice and the following + * two paragraphs appear in all copies of this software. + * + * IN NO EVENT SHALL THE UNIVERSITY OF CALIFORNIA BE LIABLE TO ANY PARTY FOR + * DIRECT, INDIRECT, SPECIAL, INCIDENTAL, OR CONSEQUENTIAL DAMAGES ARISING OUT + * OF THE USE OF THIS SOFTWARE AND ITS DOCUMENTATION, EVEN IF THE UNIVERSITY OF + * CALIFORNIA HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + * + * THE UNIVERSITY OF CALIFORNIA SPECIFICALLY DISCLAIMS ANY WARRANTIES, + * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY + * AND FITNESS FOR A PARTICULAR PURPOSE. THE SOFTWARE PROVIDED HEREUNDER IS + * ON AN "AS IS" BASIS, AND THE UNIVERSITY OF CALIFORNIA HAS NO OBLIGATION TO + * PROVIDE MAINTENANCE, SUPPORT, UPDATES, ENHANCEMENTS, OR MODIFICATIONS." + * + * $\Id$ + */ + +/** + * This class interfaces with the current Matlab session, allowing you + * to call matlab commands from Java objects + * + * @author Kamin Whitehouse + */ + +import com.mathworks.jmi.*; + +public class MatlabControl { + Matlab matlab = null; //this is the com.mathworks.jmi.Matlab class,which has functionality allowing one to interact with the matlab session. + boolean useCb=false; + Object returnVal; + String callbackFunction; + + /***************CONSTRUCTORS****************/ + /*** usually, the default constructor with no arguments is fine. + * Sometimes, a callback function is useful. A callback function + * allows the user to pass the command and its arguments to a + * matlab function, which will figure out the best way to execute + * it, instead of trying to execute it directly from java. This + * is often useful for handling/printing errors as well as dealing + * with native matlab data types, like cell arrays. The cell + * array is not really converted to a java type, only the handle + * of the cell array is converted to a java type, so often a + * matlab callback function is useful for dealing specially with + * cell arrays, etc. + ***/ + + public MatlabControl() { + this(false); + } + + public Matlab getMatlab() { + return matlab; + } + + public MatlabControl(boolean useCallback) { + this(useCallback,new String("matlabControlcb")); + } + + public MatlabControl(boolean useCallback, String CallBackFunction) { + try { + if (matlab == null) + matlab = new Matlab();//this command links to the current matlab session + } catch (Exception e) { + System.out.println(e.toString()); + } + returnVal = new String("noReturnValYet"); + this.useCb=useCallback; + callbackFunction=CallBackFunction; + } + + /***************USER-LEVEL FUNCTIONS****************/ + /***call these from any java thread (as long as the thread + * originated from within matlab) + ***/ + + /**Evaluate a string, Matlab script, or Matlab function**/ + public void eval(String Command) { + Matlab.whenMatlabReady(new MatlabEvalCommand(Command,useCb)); + } + + /**Evaluate a Matlab function that requires arguments. Each element of + the "args" vector is an argument to the function "Command"**/ + public void feval(String Command, Object[] args) { + Matlab.whenMatlabReady(new MatlabFevalCommand(Command, args,useCb)); + } + + /**Evaluate a Matlab function that requires arguments and provide return arg. + * Each element of the "args" vector is an argument to the function "Command"**/ + public Object blockingFeval(String Command, Object[] args) throws InterruptedException { + returnVal = new String("noReturnValYet"); + Matlab.whenMatlabReady(new MatlabBlockingFevalCommand(Command, args, useCb, this)); + if (returnVal.equals("noReturnValYet")) { + synchronized(returnVal){ + returnVal.wait(); + } + } + return returnVal; + } + + /**Echoing the eval statement is useful if you want to see in + * matlab each time that a java function tries to execute a matlab + * command **/ + public void setEchoEval(boolean echo){ + Matlab.setEchoEval(echo); + } + + /**********TEST FUNCTIONS***********************/ + /***call these functions from within Matlab itself. These are examples of the general execution order: + 1. instantiate java object from matlab + 2. spawn a new Java thread + 3. call matlab functions from new java thread + + EXAMPLE (from matlab prompt): + + >> mc=MatlabControl; + >> mc.testEval('x = 5') + x = + 5 + > mc.testFeval('help',{'sqrt'}) + SQRT Square root. + SQRT(X) is the square root of the elements of X. Complex + results are produced if X is not positive. + + See also SQRTM. + + Overloaded methods + help sym/sqrt.m + + >> mc.testBlockingFeval('sqrt',{x}) + 2.2361 + ****/ + + public void testEval(final String Command) { + class Caller extends Thread{ + public void run(){ + try{ + eval(Command); + } catch(Exception e){ + // System.out.println(e.toString()); + } + } + } + Caller c = new Caller(); + c.start(); + } + + public void testFeval(final String Command, final Object[] args) { + class Caller extends Thread{ + public void run(){ + try{ + feval(Command, args); + } catch(Exception e){ + // System.out.println(e.toString()); + } + } + } + Caller c = new Caller(); + c.start(); + } + + public void testBlockingFeval(final String Command, final Object[] args) { + class Caller extends Thread{ + public void run(){ + try{ + Object rets[] = new Object[1]; + rets[0] = blockingFeval(Command, args); + feval("disp",rets ); + } catch(Exception e){ + // System.out.println(e.toString()); + } + } + } + Caller c = new Caller(); + c.start(); + } + + + + /******** INTERNAL FUNCTIONS AND CLASSES *******/ + + public void setReturnVal(Object val) { + synchronized(returnVal){ + Object oldVal = returnVal; + returnVal = val; + oldVal.notifyAll(); + } + } + + /** This class is used to execute a string in Matlab **/ + protected class MatlabEvalCommand implements Runnable { + String command; + boolean useCallback,eval; + Object[] args; + + public MatlabEvalCommand(String Command, boolean useCallback) { + command = Command; + this.useCallback = useCallback; + eval=true; + args=null; + } + + protected Object useMatlabCommandCallback(String command, Object[] args){ + int numArgs = (args==null)? 0 : args.length; + Object newArgs[] = new Object[numArgs+1] ; + newArgs[0]=command; + for(int i=0;i> pathMap = new HashMap>(); - static class ClassComparator implements Comparator { - + static class ClassComparator implements Comparator { public int compare(Object o1, Object o2) { return (o1.toString().compareTo(o2.toString())); } - } /** @@ -40,7 +44,7 @@ public class ReflectPackage { * @return * @throws ClassNotFoundException */ - public static HashSet getClassesFromFilesFltr(HashSet set, String path, String pckgname, boolean includeSubs, Class reqSuperCls) { + public static int getClassesFromFilesFltr(HashSet set, String path, String pckgname, boolean includeSubs, Class reqSuperCls) { try { // Get a File object for the package File directory = null; @@ -61,27 +65,28 @@ public class ReflectPackage { System.err.println(directory.getPath()+ " not found in " + path); System.err.println("directory " + (directory.exists() ? "exists" : "doesnt exist")); } - return set; + return 0; } if (directory.exists()) { // Get the list of the files contained in the package - getClassesFromDirFltr(set, directory, pckgname, includeSubs, reqSuperCls); + return getClassesFromDirFltr(set, directory, pckgname, includeSubs, reqSuperCls); } else { if (TRACE) System.err.println(directory.getPath() + " doesnt exist in " + path + ", dir was " + dir); + return 0; } } catch(ClassNotFoundException e) { System.err.println(e.getMessage()); e.printStackTrace(); - return set; + return 0; } - return set; } // public static ArrayList getClassesFromDir(File directory, String pckgname, boolean includeSubs) { // return getClassesFromDirFltr(directory, pckgname, includeSubs, null); // } - public static HashSet getClassesFromDirFltr(HashSet set, File directory, String pckgname, boolean includeSubs, Class reqSuperCls) { + public static int getClassesFromDirFltr(HashSet set, File directory, String pckgname, boolean includeSubs, Class reqSuperCls) { + int cntAdded = 0; if (directory.exists()) { // Get the list of the files contained in the package String[] files = directory.list(); @@ -93,33 +98,45 @@ public class ReflectPackage { Class cls = Class.forName(pckgname + '.' + files[i].substring(0, files[i].length() - 6)); if (reqSuperCls != null) { if (reqSuperCls.isAssignableFrom(cls)) { - addClass(set, cls); + cntAdded += addClass(set, cls); } } else { - addClass(set, cls); + cntAdded += addClass(set, cls); } } catch (Exception e) { - System.err.println("ReflectPackage: Couldnt get Class from jar for "+pckgname+files[i]+": "+e.getMessage()); + System.err.println("ReflectPackage: Couldnt get Class from jar for "+pckgname+'.'+files[i]+": "+e.getMessage()); } catch (Error e) { - System.err.println("ReflectPackage: Couldnt get Class from jar for "+pckgname+files[i]+": "+e.getMessage()); + System.err.println("ReflectPackage: Couldnt get Class from jar for "+pckgname+'.'+files[i]+": "+e.getMessage()); } } else if (includeSubs) { // do a recursive search over subdirs File subDir = new File(directory.getAbsolutePath()+File.separatorChar+files[i]); if (subDir.exists() && subDir.isDirectory()) { - getClassesFromDirFltr(set, subDir, pckgname+"."+files[i], includeSubs, reqSuperCls); + cntAdded += getClassesFromDirFltr(set, subDir, pckgname+"."+files[i], includeSubs, reqSuperCls); } } } } - return set; + return cntAdded; } - private static void addClass(HashSet set, Class cls) { + /** + * If valid classpath entries are stored but you want to reset them, use this method. The classpath + * will then be rescanned on the next request. + */ + public static void resetDynCP() { + dynCP = null; + } + + private static int addClass(HashSet set, Class cls) { if (TRACE) System.out.println("adding class " + cls.getName()); if (set.contains(cls)) { System.err.println("warning, Class " + cls.getName() + " not added twice!"); - } else set.add(cls); + return 0; + } else { + set.add(cls); + return 1; + } } public static ArrayList filterAssignableClasses(ArrayList classes, Class reqSuperCls) { @@ -140,9 +157,10 @@ public class ReflectPackage { * @param packageName * @return */ - public static HashSet getClassesFromJarFltr(HashSet set, String jarName, String packageName, boolean includeSubs, Class reqSuperCls){ + public static int getClassesFromJarFltr(HashSet set, String jarName, String packageName, boolean includeSubs, Class reqSuperCls){ boolean isInSubPackage = true; - + int cntAdded = 0; + packageName = packageName.replaceAll("\\." , "/"); if (TRACE) System.out.println("Jar " + jarName + " looking for " + packageName); try{ @@ -168,9 +186,9 @@ public class ReflectPackage { Class cls = Class.forName(clsName.substring(0, jarEntryName.length() - 6)); if (reqSuperCls != null) { if (reqSuperCls.isAssignableFrom(cls)) { - addClass(set, cls); + cntAdded += addClass(set, cls); } - } else addClass(set, cls); + } else cntAdded += addClass(set, cls); } catch(Exception e) { System.err.println("ReflectPackage: Couldnt get Class from jar for "+clsName+": "+e.getMessage()); } catch(Error e) { @@ -182,10 +200,14 @@ public class ReflectPackage { } } } catch(IOException e) { - System.err.println("coulnt read jar: " + e.getMessage()); - e.printStackTrace(); + missedJarsOnClassPath++; + if (missedJarsOnClassPath == 0) { + System.err.println("Couldnt open jar from class path: " + e.getMessage()); + System.err.println("Dirty class path?"); + } else if (missedJarsOnClassPath == 2) System.err.println("Couldnt open jar from class path more than once..."); + //e.printStackTrace(); } - return set; + return cntAdded; } /** @@ -211,18 +233,68 @@ public class ReflectPackage { * @return */ public static Class[] getClassesInPackageFltr(HashSet set, String pckg, boolean includeSubs, boolean bSort, Class reqSuperCls) { - String classPath = System.getProperty("java.class.path","."); - if (TRACE) System.out.println("classpath is " + classPath); - String[] pathElements = classPath.split(File.pathSeparator); - - for (int i=0; i valids = new ArrayList(pathElements.length); + for (int i=0; i pathes = pathMap.get(pckg); +// System.err.println("stored objects: " + ((pathes != null) ? pathes.size() : 0)); +// if (pathes == null) { +// pathes = new ArrayList(); +// for (int i=0; i 0) pathes.add(dynCP[i]); +// } +// pathMap.put(pckg, pathes); +// } else { +// for (int i=0; i= 0) && (i < this.m_Tags.length)) this.m_Selected = i; } - /** This gives me the chance to set the selected tag index from a java program - * @param i The new selected tag index + /** + * Set the selected tag by String tag name. If the given name doesnt exist, nothing + * will change and an error message will be printed to System.err. This should of course + * be avoided. + * + * @param str The new selected tag name */ public void setSelectedTag(String str) { for (int i=0; i { + /** + * Evaluate a double vector representing a possible problem solution as + * part of an individual in the JavaEvA framework. This makes up the + * target function to be evaluated. + * + * @param x a double vector to be evaluated + * @return the fitness vector assigned to x as to the target function + */ + public double[] eval(T x); + + /** + * Return the problem dimension. + * + * @return the problem dimension + */ + public int getProblemDimension(); + +} + diff --git a/src/simpleprobs/SimpleB1.java b/src/simpleprobs/SimpleB1.java new file mode 100644 index 00000000..71d5e25d --- /dev/null +++ b/src/simpleprobs/SimpleB1.java @@ -0,0 +1,23 @@ +package simpleprobs; + +import java.util.BitSet; + +public class SimpleB1 extends SimpleProblemBinary { + public String globalInfo() { + return "A simple B1 implementation, minimize bits in a binary vector."; + } + + public double[] eval(BitSet b) { + double[] result = new double[1]; + int fitness = 0; + + for (int i = 0; i < getProblemDimension(); i++) if (b.get(i)) fitness++; + result[0] = fitness; + return result; + } + + public int getProblemDimension() { + return 20; + } + +} diff --git a/src/simpleprobs/SimpleF1.java b/src/simpleprobs/SimpleF1.java new file mode 100644 index 00000000..91a68fd8 --- /dev/null +++ b/src/simpleprobs/SimpleF1.java @@ -0,0 +1,27 @@ +package simpleprobs; + + +public class SimpleF1 extends SimpleProblemDouble { + public String globalInfo() { + return "A simple F1 implementation, find the minimum of a hyper parabola."; + } + + public double[] eval(double[] x) { + double res[] = new double[1]; + // this defines the dimension of the fitness vector, which should be always the same + + double sum = 0; + // calculate the fitness value + for (int i=0; i, Serializable { + public String globalInfo() { + return "A simple binary problem. Override globalInfo() to insert more information."; + } +} \ No newline at end of file diff --git a/src/simpleprobs/SimpleProblemDouble.java b/src/simpleprobs/SimpleProblemDouble.java new file mode 100644 index 00000000..ee2dd47a --- /dev/null +++ b/src/simpleprobs/SimpleProblemDouble.java @@ -0,0 +1,9 @@ +package simpleprobs; + +import java.io.Serializable; + +public abstract class SimpleProblemDouble implements InterfaceSimpleProblem, Serializable { + public String globalInfo() { + return "A simple double valued problem. Override globalInfo() to insert more information."; + } +} diff --git a/src/wsi/ra/jproxy/RemoteStateListener.java b/src/wsi/ra/jproxy/RemoteStateListener.java index 2f27825f..180a97ac 100644 --- a/src/wsi/ra/jproxy/RemoteStateListener.java +++ b/src/wsi/ra/jproxy/RemoteStateListener.java @@ -23,5 +23,5 @@ public interface RemoteStateListener { public void performedStop(); public void performedStart(String infoString); public void performedRestart(String infoString); - public void updateProgress(final int percent); + public void updateProgress(final int percent, String msg); }