Further code cleanup 
- renaming variables (mostly removing m_ prefixes)
- commented code removed
- TRACE variables removed
- Changelog will now be held as seperate file and not within EvAInfo

Removed unused class.
This commit is contained in:
Fabian Becker 2012-05-25 23:20:00 +00:00
parent 97ffdbf33a
commit 6362a4a677
9 changed files with 2055 additions and 2557 deletions

View File

@ -1,86 +1,10 @@
package eva2; package eva2;
import eva2.tools.BasicResourceLoader;
import java.io.InputStream; import java.io.InputStream;
import java.util.Properties; import java.util.Properties;
import eva2.tools.BasicResourceLoader; /**
/**
* Main product and version information strings.
*
* ---- Changelog
* 2.05: Added ScatterSearch (real-valued), BinaryScatterSearch, and the Bayesian Optimization Algorithm (thanks
* to Alexander Seitz) to the base package. Added JobList and some statistical measures. Requires to put
* the JSC package on the class path for Mann-Whitney test.
* 2.046: Adaptions to the MatlabInterface: explicit data types are used now, added integer problem support.
* Additional Integer operators: segment-wise mutation and crossover. Added an abstraction over individual
* initialization methods. Added the ERPStarter class which is an example for running a csv-configured
* optimization. Some bug-fixes and clean-ups.
* 2.045: Added MOOCMAES (de Paly); compatibility with Java 1.5 (Draeger); Revision of the statistics class
* with improved pipelining of data (InterfaceAdditionalPopulationInformer); improved FunctionArea
* concerning history, labels, legend and graph coloring; improved StringSelection; restructured
* Terminators, additional ParetoMetricTerminator. Further bugfixes and clean-ups.
* 2.043: Added proper Population equality predicate.
* 2.042: Some bugfixes. Removing dependency on sun.beans.editors, replaced non-free jpeg-codec. There should
* be no more problems on OpenJDK. Added a simple initialization range, especially for use from Matlab.
* Some restructurings (RNG and Mathematics is now in eva2.tools.math). Some cleanup.
* 2.040: Several updates: The clustering interface has been changed for easier implementation of adaptive clustering
* methods. The GradientDescentAlgorithm has been updated and some benchmark problems been made derivable.
* The ClusterBasedNiching algorithm has been slightly restructured updated according to the new clustering.
* An additional clustering method is included: nearest-best clustering with dynamic adaption of niche radius.
* Some changes to (text) statistics: they are now printed regarding the full solution set instead of the
* last population. The Population field "size" is now termed "targetSize" to avoid misunderstandigs. Populations
* can be initialized using a Random Latin Hypercube sampling. Some basic console options are recognized:
* EvA2 can be started without splash screen and even without GUI. If configuration file is given which was
* earlier saved from the GUI, the thus defined optimization run is then processed automatically by EvA2.
* 2.036: New graph selection mode for statistic plots: every property may be selected independently.
* A simple plot legend is produced in the graph window, which can be deactivated.
* 2.035: Reactivated some of the model-based functionality within the GO framework. Minor bugfixes.
* 2.034: Adding a generic parameter control method for optimizers, currently used by PSO to adapt inertness depending
* on EvaluationTerminator or GenerationTerminator instances defining the number of function evaluations.
* The new package is eva2.server.go.operators.paramcontrol.
* A Population may now be ordered by a specific fitness criterion, employed, e.g., by Nelder-Mead-Simplex.
* 2.033: There was an interesting problem with the Matlab-Interface, which just hung up after extensive optimization
* loops, yet only if Matlab was started without X-forwarding (which is necessary for qsub, e.g.).
* Debugging was tedious, since the debugging using System.out. itself caused threading deadlocks. The
* problem showed up to be with System.out itself. Whatever Matlab does with that stream, it does it differently
* depending on the X-forwarding option. More specifically, the text written to System.out when X-forwarding
* is not available seems to never show up (as opposed to being printed to the console when X-forwarding is on)
* and silently fill up the JVM-memory. I havent the faintest idea why there havnt been OutOfMemory exceptions
* earlier or whether and how the deadlocks have to do with it.
* The ingenious solution was: dont print anything to System.out, which is now done at verbosity 0.
* 2.032: Some cosmetics, e.g. to AbstractEAIndividualComparator and older MOCCO classes.
* 2.031: Some updates to the OptimizerFactory. Review of the MatlabInterface with adding an own options structure.
* Better access to the EvAClient, which now may have a RemoteStateListener added monitoring the optimization run.
* 2.030: Added an EnumEditor to access enums easily through the GUI, which will replace SelectedTags sometimes.
* IPOP-ES and RankMuCMA mutator have been added lately (wow!).
* Cleaned up the IndividualInterface and reduced the usage of InterfaceESIndividual. This
* means that, e.g., that DE and PSO now also work on GAIndividualDoubleData. Because this
* requires much time for transcoding, however, this is not useful by itself. Yet it could be
* interesting for combined individuals composed of two data types.
* Cleaned up MutateXXDefault to a single MutateDefault, too. DE may now do range checking.
* The "Description" button has made space for a "Show Solution" button. The Rank-Mu-CMA was improved
* to use a CMAParameterSet which is associated with populations and not static any more.
* Included Nelder-Mead-Simplex and CMA-ES as post processing methods.
* 2.029: Tuned the 2d-graphs which now paints quicker and changes size depending on the
* surrounding plot window. Added a preloader-thread to accelerate the GUI at starting time.
* 2.028: Tuned the Population to sort only when necessary on calls to getBestN... Added StatisticsDummy.
* Slightly tuned SimpleProblemWrapper to call initProblem of simple problems if available.
* 2.027: Renamed SetData and SetDataLamarckian from individual data type interfaces to SetGenotype and SetPhenotype.
* Repaired the GenericArrayEditor. Population measures can now be plotted in stats.
* 2.026: Added DiversityTerminator and KnownOptimaTerminator, slightly changed InterfaceTerminator for these
* and InterfaceStatistics to provide termination message to text window.
* Killed redundant method getGenerations() in Population. Population.getAllSolutions now returns a
* SolutionSet combining last population with a set of possibly archived solutions.
* Post processing with HC may now use variable step size mutation.
* 2.025: FunctionArea may now plot circles easily. The FLensProblemViewer seems to be cured.
* 2.024: Cleaned up AbstractGOParams, deactivated parent logging (saving memory)
* 2.023: Cleaned up the PF strategy
* 2.022: Some changes to the SimpleProblemWrapper, not of great interest. However,
* simple problems may now access a plot quite easily.
*
* --- End Changelog
*
* @author mkron * @author mkron
* *
*/ */

View File

@ -1,11 +1,5 @@
/*
* Copyright (c) ZBiT, University of Tübingen, Germany
*/
package eva2; package eva2;
import java.util.BitSet;
import java.util.Vector;
import eva2.server.go.IndividualInterface; import eva2.server.go.IndividualInterface;
import eva2.server.go.InterfacePopulationChangedEventListener; import eva2.server.go.InterfacePopulationChangedEventListener;
import eva2.server.go.InterfaceTerminator; import eva2.server.go.InterfaceTerminator;
@ -27,12 +21,7 @@ import eva2.server.go.operators.crossover.CrossoverESDefault;
import eva2.server.go.operators.crossover.InterfaceCrossover; import eva2.server.go.operators.crossover.InterfaceCrossover;
import eva2.server.go.operators.crossover.NoCrossover; import eva2.server.go.operators.crossover.NoCrossover;
import eva2.server.go.operators.distancemetric.IndividualDataMetric; import eva2.server.go.operators.distancemetric.IndividualDataMetric;
import eva2.server.go.operators.mutation.InterfaceMutation; import eva2.server.go.operators.mutation.*;
import eva2.server.go.operators.mutation.MutateESCovarianceMatrixAdaption;
import eva2.server.go.operators.mutation.MutateESFixedStepSize;
import eva2.server.go.operators.mutation.MutateESGlobal;
import eva2.server.go.operators.mutation.MutateESRankMuCMA;
import eva2.server.go.operators.mutation.NoMutation;
import eva2.server.go.operators.postprocess.InterfacePostProcessParams; import eva2.server.go.operators.postprocess.InterfacePostProcessParams;
import eva2.server.go.operators.postprocess.PostProcessParams; import eva2.server.go.operators.postprocess.PostProcessParams;
import eva2.server.go.operators.selection.InterfaceSelection; import eva2.server.go.operators.selection.InterfaceSelection;
@ -42,27 +31,13 @@ import eva2.server.go.operators.terminators.EvaluationTerminator;
import eva2.server.go.populations.PBILPopulation; import eva2.server.go.populations.PBILPopulation;
import eva2.server.go.populations.Population; import eva2.server.go.populations.Population;
import eva2.server.go.problems.AbstractOptimizationProblem; import eva2.server.go.problems.AbstractOptimizationProblem;
import eva2.server.go.strategies.ClusterBasedNichingEA; import eva2.server.go.strategies.*;
import eva2.server.go.strategies.ClusteringHillClimbing;
import eva2.server.go.strategies.DifferentialEvolution;
import eva2.server.go.strategies.EsDpiNiching;
import eva2.server.go.strategies.EsDpiNichingCma;
import eva2.server.go.strategies.EvolutionStrategies;
import eva2.server.go.strategies.EvolutionStrategyIPOP;
import eva2.server.go.strategies.GeneticAlgorithm;
import eva2.server.go.strategies.GradientDescentAlgorithm;
import eva2.server.go.strategies.HillClimbing;
import eva2.server.go.strategies.InterfaceOptimizer;
import eva2.server.go.strategies.MonteCarloSearch;
import eva2.server.go.strategies.MultiObjectiveEA;
import eva2.server.go.strategies.NelderMeadSimplex;
import eva2.server.go.strategies.ParticleSwarmOptimization;
import eva2.server.go.strategies.PopulationBasedIncrementalLearning;
import eva2.server.go.strategies.SimulatedAnnealing;
import eva2.server.go.strategies.Tribes;
import eva2.server.modules.GOParameters; import eva2.server.modules.GOParameters;
import eva2.server.stat.InterfaceStatistics; import eva2.server.stat.InterfaceStatistics;
import eva2.tools.math.RNG; import eva2.tools.math.RNG;
import java.util.ArrayList;
import java.util.BitSet;
import java.util.List;
/** /**
* <p> * <p>
@ -1011,19 +986,19 @@ public class OptimizerFactory {
return runnable.getResultPopulation(); return runnable.getResultPopulation();
} }
public static Vector<BitSet> postProcessBinVec(int steps, double sigma, public static List<BitSet> postProcessBinVec(int steps, double sigma,
int nBest) { int nBest) {
return (lastRunnable != null) ? postProcessBinVec(lastRunnable, return (lastRunnable != null) ? postProcessBinVec(lastRunnable,
new PostProcessParams(steps, sigma, nBest)) : null; new PostProcessParams(steps, sigma, nBest)) : null;
} }
public static Vector<BitSet> postProcessBinVec( public static List<BitSet> postProcessBinVec(
InterfacePostProcessParams ppp) { InterfacePostProcessParams ppp) {
return (lastRunnable != null) ? postProcessBinVec(lastRunnable, ppp) return (lastRunnable != null) ? postProcessBinVec(lastRunnable, ppp)
: null; : null;
} }
public static Vector<BitSet> postProcessBinVec(OptimizerRunnable runnable, public static List<BitSet> postProcessBinVec(OptimizerRunnable runnable,
int steps, double sigma, int nBest) { int steps, double sigma, int nBest) {
return postProcessBinVec(runnable, new PostProcessParams(steps, sigma, return postProcessBinVec(runnable, new PostProcessParams(steps, sigma,
nBest)); nBest));
@ -1037,10 +1012,10 @@ public class OptimizerFactory {
* @param ppp * @param ppp
* @return * @return
*/ */
public static Vector<BitSet> postProcessBinVec(OptimizerRunnable runnable, public static List<BitSet> postProcessBinVec(OptimizerRunnable runnable,
InterfacePostProcessParams ppp) { InterfacePostProcessParams ppp) {
Population resPop = postProcess(runnable, ppp); Population resPop = postProcess(runnable, ppp);
Vector<BitSet> ret = new Vector<BitSet>(resPop.size()); List<BitSet> ret = new ArrayList<BitSet>(resPop.size());
for (Object o : resPop) { for (Object o : resPop) {
if (o instanceof InterfaceDataTypeBinary) { if (o instanceof InterfaceDataTypeBinary) {
InterfaceDataTypeBinary indy = (InterfaceDataTypeBinary) o; InterfaceDataTypeBinary indy = (InterfaceDataTypeBinary) o;
@ -1050,19 +1025,19 @@ public class OptimizerFactory {
return ret; return ret;
} }
public static Vector<double[]> postProcessDblVec(int steps, double sigma, public static List<double[]> postProcessDblVec(int steps, double sigma,
int nBest) { int nBest) {
return (lastRunnable == null) ? null : postProcessDblVec(lastRunnable, return (lastRunnable == null) ? null : postProcessDblVec(lastRunnable,
new PostProcessParams(steps, sigma, nBest)); new PostProcessParams(steps, sigma, nBest));
} }
public static Vector<double[]> postProcessDblVec( public static List<double[]> postProcessDblVec(
InterfacePostProcessParams ppp) { InterfacePostProcessParams ppp) {
return (lastRunnable != null) ? postProcessDblVec(lastRunnable, ppp) return (lastRunnable != null) ? postProcessDblVec(lastRunnable, ppp)
: null; : null;
} }
public static Vector<double[]> postProcessDblVec( public static List<double[]> postProcessDblVec(
OptimizerRunnable runnable, int steps, double sigma, int nBest) { OptimizerRunnable runnable, int steps, double sigma, int nBest) {
return postProcessDblVec(runnable, new PostProcessParams(steps, sigma, return postProcessDblVec(runnable, new PostProcessParams(steps, sigma,
nBest)); nBest));
@ -1076,10 +1051,10 @@ public class OptimizerFactory {
* @param ppp * @param ppp
* @return * @return
*/ */
public static Vector<double[]> postProcessDblVec( public static List<double[]> postProcessDblVec(
OptimizerRunnable runnable, InterfacePostProcessParams ppp) { OptimizerRunnable runnable, InterfacePostProcessParams ppp) {
Population resPop = postProcess(runnable, ppp); Population resPop = postProcess(runnable, ppp);
Vector<double[]> ret = new Vector<double[]>(resPop.size()); List<double[]> ret = new ArrayList<double[]>(resPop.size());
for (Object o : resPop) { for (Object o : resPop) {
if (o instanceof InterfaceDataTypeDouble) { if (o instanceof InterfaceDataTypeDouble) {
InterfaceDataTypeDouble indy = (InterfaceDataTypeDouble) o; InterfaceDataTypeDouble indy = (InterfaceDataTypeDouble) o;
@ -1089,19 +1064,19 @@ public class OptimizerFactory {
return ret; return ret;
} }
public static Vector<AbstractEAIndividual> postProcessIndVec(int steps, public static List<AbstractEAIndividual> postProcessIndVec(int steps,
double sigma, int nBest) { double sigma, int nBest) {
return (lastRunnable != null) ? postProcessIndVec(lastRunnable, return (lastRunnable != null) ? postProcessIndVec(lastRunnable,
new PostProcessParams(steps, sigma, nBest)) : null; new PostProcessParams(steps, sigma, nBest)) : null;
} }
public static Vector<AbstractEAIndividual> postProcessIndVec( public static List<AbstractEAIndividual> postProcessIndVec(
InterfacePostProcessParams ppp) { InterfacePostProcessParams ppp) {
return (lastRunnable != null) ? postProcessIndVec(lastRunnable, ppp) return (lastRunnable != null) ? postProcessIndVec(lastRunnable, ppp)
: null; : null;
} }
public static Vector<AbstractEAIndividual> postProcessIndVec( public static List<AbstractEAIndividual> postProcessIndVec(
OptimizerRunnable runnable, int steps, double sigma, int nBest) { OptimizerRunnable runnable, int steps, double sigma, int nBest) {
return postProcessIndVec(runnable, new PostProcessParams(steps, sigma, return postProcessIndVec(runnable, new PostProcessParams(steps, sigma,
nBest)); nBest));
@ -1115,10 +1090,10 @@ public class OptimizerFactory {
* @param ppp * @param ppp
* @return * @return
*/ */
public static Vector<AbstractEAIndividual> postProcessIndVec( public static List<AbstractEAIndividual> postProcessIndVec(
OptimizerRunnable runnable, InterfacePostProcessParams ppp) { OptimizerRunnable runnable, InterfacePostProcessParams ppp) {
Population resPop = postProcess(runnable, ppp); Population resPop = postProcess(runnable, ppp);
Vector<AbstractEAIndividual> ret = new Vector<AbstractEAIndividual>( List<AbstractEAIndividual> ret = new ArrayList<AbstractEAIndividual>(
resPop.size()); resPop.size());
for (Object o : resPop) { for (Object o : resPop) {
if (o instanceof AbstractEAIndividual) { if (o instanceof AbstractEAIndividual) {
@ -1428,8 +1403,7 @@ public class OptimizerFactory {
MutateESRankMuCMA cmaMut = new MutateESRankMuCMA(); MutateESRankMuCMA cmaMut = new MutateESRankMuCMA();
AbstractEAIndividual.setOperators(indy, cmaMut, 1., new CrossoverESDefault(), 0.); AbstractEAIndividual.setOperators(indy, cmaMut, 1., new CrossoverESDefault(), 0.);
} else { } else {
System.err System.err.println("Error, CMA-ES is implemented for ES individuals only (requires double data types)");
.println("Error, CMA-ES is implemented for ES individuals only (requires double data types)");
return null; return null;
} }

View File

@ -1,18 +1,18 @@
package eva2.examples; package eva2.examples;
import java.util.Vector;
import eva2.OptimizerFactory; import eva2.OptimizerFactory;
import eva2.server.go.individuals.AbstractEAIndividual; import eva2.server.go.individuals.AbstractEAIndividual;
import eva2.server.go.operators.postprocess.PostProcessParams; import eva2.server.go.operators.postprocess.PostProcessParams;
import eva2.server.go.operators.terminators.EvaluationTerminator; import eva2.server.go.operators.terminators.EvaluationTerminator;
import eva2.server.go.problems.FM0Problem; import eva2.server.go.problems.FM0Problem;
import eva2.server.modules.GOParameters; import eva2.server.modules.GOParameters;
import java.util.List;
public class TestingCbnPostProc { public class TestingCbnPostProc {
public static void main(String[] args) { public static void main(String[] args) {
// a simple bimodal target function, two optima near (1.7,0) and (-1.44/0) // a simple bimodal target function, two optima near (1.7,0) and (-1.44/0)
FM0Problem fm0 = new FM0Problem(); FM0Problem fm0 = new FM0Problem();
AbstractEAIndividual best; AbstractEAIndividual best;
Vector<AbstractEAIndividual> ppSols; List<AbstractEAIndividual> ppSols;
GOParameters esParams = OptimizerFactory.standardCbnES(fm0); GOParameters esParams = OptimizerFactory.standardCbnES(fm0);
esParams.setTerminator(new EvaluationTerminator(2000)); esParams.setTerminator(new EvaluationTerminator(2000));

View File

@ -185,179 +185,186 @@ public class FunctionArea extends DArea implements Serializable {
/** /**
* Add a popup menu for displaying certain information. * Add a popup menu for displaying certain information.
*/ */
private void addPopup() { private void addPopup() {
addMouseListener(new MouseAdapter() { addMouseListener(new MouseAdapter() {
public void mouseClicked(MouseEvent e) {
if ((e.getModifiers() & InputEvent.BUTTON1_MASK) == InputEvent.BUTTON1_MASK) {
// do nothing
} else {
JPopupMenu graphPopupMenu = new JPopupMenu();
m_x = e.getX();
m_y = e.getY();
addMenuItem(graphPopupMenu, "Rename graph", new ActionListener() { public void mouseClicked(MouseEvent e) {
public void actionPerformed(ActionEvent ee) { if ((e.getModifiers() & InputEvent.BUTTON1_MASK) == InputEvent.BUTTON1_MASK) {
renameGraph(getNearestGraphIndex(FunctionArea.this.m_x, FunctionArea.this.m_y)); // do nothing
} } else {
}); JPopupMenu graphPopupMenu = new JPopupMenu();
// General entries m_x = e.getX();
String togGTTName = (isShowGraphToolTips() ? "Deactivate" m_y = e.getY();
: "Activate")
+ " graph tool tips";
addMenuItem(graphPopupMenu, togGTTName,
new ActionListener() {
public void actionPerformed(ActionEvent ee) {
setShowGraphToolTips(!isShowGraphToolTips());
}
});
String togLName = (isShowLegend() ? "Hide" : "Show") addMenuItem(graphPopupMenu, "Rename graph", new ActionListener() {
+ " legend";
addMenuItem(graphPopupMenu, togLName, new ActionListener() {
public void actionPerformed(ActionEvent ee) {
toggleLegend();
}
});
addMenuItem(graphPopupMenu, "Toggle scientific format", new ActionListener() { public void actionPerformed(ActionEvent ee) {
public void actionPerformed(ActionEvent ee) { renameGraph(getNearestGraphIndex(FunctionArea.this.m_x, FunctionArea.this.m_y));
toggleScientificY(true); }
} });
}); // General entries
String togGTTName = (isShowGraphToolTips() ? "Deactivate"
if (FunctionArea.this.m_PointSetContainer.size() > 0) { : "Activate")
addMenuItem(graphPopupMenu, "Recolor all graphs", + " graph tool tips";
new ActionListener() { addMenuItem(graphPopupMenu, togGTTName,
new ActionListener() {
public void actionPerformed(ActionEvent ee) { public void actionPerformed(ActionEvent ee) {
recolorAllGraphsByIndex(); setShowGraphToolTips(!isShowGraphToolTips());
} }
}); });
}
if (m_RefPointListener != null) { String togLName = (isShowLegend() ? "Hide" : "Show")
DPoint temp = getDMeasures().getDPoint(m_x, m_y); + " legend";
addMenuItem(graphPopupMenu, "Select Reference Point:(" addMenuItem(graphPopupMenu, togLName, new ActionListener() {
+ temp.x + "/" + temp.y + ")",
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);
}
});
}
// darn this point is an empty copy !! public void actionPerformed(ActionEvent ee) {
DPoint point = getNearestDPoint(e.getX(), e.getY()); toggleLegend();
if (point != null) { }
// the point info element });
addMenuItem(graphPopupMenu, "Nearest point: ("
+ point.x + "/" + point.y + ")",
new ActionListener() {
public void actionPerformed(ActionEvent ee) {
}
}, false);
addMenuItem(graphPopupMenu, " Remove point", addMenuItem(graphPopupMenu, "Toggle scientific format", new ActionListener() {
new ActionListener() {
public void actionPerformed(ActionEvent ee) {
removePoint(FunctionArea.this.m_x,
FunctionArea.this.m_y);
}
});
if (point.getIcon() instanceof InterfaceSelectablePointIcon) { public void actionPerformed(ActionEvent ee) {
m_CurrentPointIcon = point.getIcon(); toggleScientificY(true);
if (((InterfaceSelectablePointIcon) m_CurrentPointIcon) }
.getSelectionListener() != null) { });
AbstractEAIndividual indy = ((InterfaceSelectablePointIcon) m_CurrentPointIcon)
.getEAIndividual();
String selectTitle = indy.isMarked() ? " Deselect individual"
: " Select individual";
addMenuItem(graphPopupMenu, selectTitle,
new ActionListener() {
public void actionPerformed(
ActionEvent ee) {
((InterfaceSelectablePointIcon) m_CurrentPointIcon)
.getSelectionListener()
.individualSelected(
((InterfaceSelectablePointIcon) m_CurrentPointIcon)
.getEAIndividual());
}
});
}
}
if (point.getIcon() instanceof InterfaceDPointWithContent) { if (FunctionArea.this.m_PointSetContainer.size() > 0) {
m_CurrentPointIcon = point.getIcon(); addMenuItem(graphPopupMenu, "Recolor all graphs",
addMenuItem(graphPopupMenu, " Show individual", new ActionListener() {
new ActionListener() {
public void actionPerformed(
ActionEvent ee) {
((InterfaceDPointWithContent) m_CurrentPointIcon)
.showIndividual();
}
});
}
} public void actionPerformed(ActionEvent ee) {
if (FunctionArea.this.m_PointSetContainer.size() > 0) { // there recolorAllGraphsByIndex();
// is }
// at });
// least }
// one
// graph
// The graph info element
// int gIndex = getNearestGraphIndex(e.getX(),
// e.getY());
addMenuItem(graphPopupMenu, "Graph Info: "
+ getGraphInfo(e.getX(), e.getY()),
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 DBorder getDBorder() {
return new DBorder(4, 4, 4, 4);
}
public void paint(Graphics g) { if (m_RefPointListener != null) {
g.drawLine(-2, 0, 2, 0); DPoint temp = getDMeasures().getDPoint(m_x, m_y);
g.drawLine(0, 0, 0, 4); addMenuItem(graphPopupMenu, "Select Reference Point:("
} + temp.x + "/" + temp.y + ")",
}; new ActionListener() {
temp.setIcon(icon1);
FunctionArea.this.addDElement(temp);
}
}, false);
addMenuItem(graphPopupMenu, " Remove graph", public void actionPerformed(ActionEvent ee) {
new ActionListener() { DPoint temp = getDMeasures().getDPoint(
public void actionPerformed(ActionEvent ee) { m_x, m_y);
clearGraph(FunctionArea.this.m_x, double[] point = new double[2];
FunctionArea.this.m_y); point[0] = temp.x;
} point[1] = temp.y;
}); m_RefPointListener.refPointGiven(point);
}
});
}
addMenuItem(graphPopupMenu, " Change graph color", // darn this point is an empty copy !!
new ActionListener() { DPoint point = getNearestDPoint(e.getX(), e.getY());
public void actionPerformed(ActionEvent ee) { if (point != null) {
changeColorGraph(FunctionArea.this.m_x, // the point info element
FunctionArea.this.m_y); addMenuItem(graphPopupMenu, "Nearest point: ("
} + point.x + "/" + point.y + ")",
}); new ActionListener() {
}
graphPopupMenu.show(FunctionArea.this, e.getX(), e.getY()); public void actionPerformed(ActionEvent ee) {
} }
} }, false);
});
} addMenuItem(graphPopupMenu, " Remove point",
new ActionListener() {
public void actionPerformed(ActionEvent ee) {
removePoint(FunctionArea.this.m_x,
FunctionArea.this.m_y);
}
});
if (point.getIcon() instanceof InterfaceSelectablePointIcon) {
m_CurrentPointIcon = point.getIcon();
if (((InterfaceSelectablePointIcon) m_CurrentPointIcon).getSelectionListener() != null) {
AbstractEAIndividual indy = ((InterfaceSelectablePointIcon) m_CurrentPointIcon).getEAIndividual();
String selectTitle = indy.isMarked() ? " Deselect individual"
: " Select individual";
addMenuItem(graphPopupMenu, selectTitle,
new ActionListener() {
public void actionPerformed(
ActionEvent ee) {
((InterfaceSelectablePointIcon) m_CurrentPointIcon).getSelectionListener().individualSelected(
((InterfaceSelectablePointIcon) m_CurrentPointIcon).getEAIndividual());
}
});
}
}
if (point.getIcon() instanceof InterfaceDPointWithContent) {
m_CurrentPointIcon = point.getIcon();
addMenuItem(graphPopupMenu, " Show individual",
new ActionListener() {
public void actionPerformed(
ActionEvent ee) {
((InterfaceDPointWithContent) m_CurrentPointIcon).showIndividual();
}
});
}
}
if (FunctionArea.this.m_PointSetContainer.size() > 0) { // there
// is
// at
// least
// one
// graph
// The graph info element
// int gIndex = getNearestGraphIndex(e.getX(),
// e.getY());
addMenuItem(graphPopupMenu, "Graph Info: "
+ getGraphInfo(e.getX(), e.getY()),
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 DBorder getDBorder() {
return new DBorder(4, 4, 4, 4);
}
public void paint(Graphics g) {
g.drawLine(-2, 0, 2, 0);
g.drawLine(0, 0, 0, 4);
}
};
temp.setIcon(icon1);
FunctionArea.this.addDElement(temp);
}
}, false);
addMenuItem(graphPopupMenu, " Remove graph",
new ActionListener() {
public void actionPerformed(ActionEvent ee) {
clearGraph(FunctionArea.this.m_x,
FunctionArea.this.m_y);
}
});
addMenuItem(graphPopupMenu, " Change graph color",
new ActionListener() {
public void actionPerformed(ActionEvent ee) {
changeColorGraph(FunctionArea.this.m_x,
FunctionArea.this.m_y);
}
});
}
graphPopupMenu.show(FunctionArea.this, e.getX(), e.getY());
}
}
});
}
/** /**
* Create an enabled menu item with given title and listener, add it to the * Create an enabled menu item with given title and listener, add it to the

View File

@ -1,488 +0,0 @@
package eva2.gui;
/*
* Title: EvA2
* Description:
* Copyright: Copyright (c) 2003
* Company: University of Tuebingen, Computer Architecture
* @author Holger Ulmer, Felix Streichert, Hannes Planatscher
* @version: $Revision: 201 $
* $Date: 2007-10-25 16:11:23 +0200 (Thu, 25 Oct 2007) $
* $Author: mkron $
*/
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import javax.swing.tree.DefaultMutableTreeNode;
import javax.swing.tree.TreePath;
/**
*
*/
public class JClassTree extends JDialog {
// private ESPara m_Para;
JScrollPane jScrollPane1 = new JScrollPane();
JTree treeView_ = new JTree();
JPanel treeControlsPanel = new JPanel();
JButton expandButton = new JButton();
JButton collapseButton = new JButton();
JButton editButton = new JButton();
JButton cancelButton = new JButton();
// Used for addNotify check.
private boolean fComponentsAdjusted = false;
/**
* Default constructor.
*/
public JClassTree() {
getContentPane().setLayout(new BorderLayout(0, 0));
setVisible(false);
setSize(405, 362);
jScrollPane1 = new javax.swing.JScrollPane();
jScrollPane1.setOpaque(true);
getContentPane().add(BorderLayout.CENTER, jScrollPane1);
treeView_ = new JTree();
treeView_.setBounds(0, 0, 402, 324);
treeView_.setFont(new Font("Dialog", Font.PLAIN, 12));
treeView_.setBackground(java.awt.Color.white);
jScrollPane1.getViewport().add(treeView_);
treeControlsPanel = new javax.swing.JPanel();
treeControlsPanel.setLayout(new FlowLayout(FlowLayout.CENTER, 5, 5));
treeControlsPanel.setFont(new Font("Dialog", Font.PLAIN, 12));
treeControlsPanel.setForeground(java.awt.Color.black);
treeControlsPanel.setBackground(new java.awt.Color(204, 204, 204));
getContentPane().add(BorderLayout.SOUTH, treeControlsPanel);
expandButton = new javax.swing.JButton();
expandButton.setText("Expand All");
expandButton.setActionCommand("Expand All");
expandButton.setFont(new Font("Dialog", Font.BOLD, 12));
expandButton.setBackground(new java.awt.Color(204, 204, 204));
treeControlsPanel.add(expandButton);
collapseButton = new javax.swing.JButton();
collapseButton.setText("Collapse All");
collapseButton.setActionCommand("Collapse All");
collapseButton.setFont(new Font("Dialog", Font.BOLD, 12));
collapseButton.setBackground(new java.awt.Color(204, 204, 204));
treeControlsPanel.add(collapseButton);
editButton = new javax.swing.JButton();
editButton.setText("Edit Selected");
editButton.setActionCommand("Edit Selected");
editButton.setFont(new Font("Dialog", Font.BOLD, 12));
editButton.setBackground(new java.awt.Color(204, 204, 204));
treeControlsPanel.add(editButton);
cancelButton = new javax.swing.JButton();
cancelButton.setText("Close");
cancelButton.setActionCommand("Close");
cancelButton.setFont(new Font("Dialog", Font.BOLD, 12));
cancelButton.setBackground(new java.awt.Color(204, 204, 204));
treeControlsPanel.add(cancelButton);
setTitle("Class View");
SymWindow aSymWindow = new SymWindow();
this.addWindowListener(aSymWindow);
SymAction lSymAction = new SymAction();
expandButton.addActionListener(lSymAction);
collapseButton.addActionListener(lSymAction);
editButton.addActionListener(lSymAction);
cancelButton.addActionListener(lSymAction);
MouseListener ml =
new MouseAdapter() {
public void mouseClicked(MouseEvent e) {
int selRow = treeView_.getRowForLocation(e.getX(), e.getY());
TreePath selPath = treeView_.getPathForLocation(e.getX(), e.getY());
if (selRow != -1) {
if ((e.getClickCount() == 2) ||
((e.getModifiers() & InputEvent.BUTTON3_MASK) != 0)) {
doubleClick(selRow, selPath);
}
}
}
};
treeView_.addMouseListener(ml);
//
Insets inset = new Insets(0, 5, 0, 5);
expandButton.setMargin(inset);
collapseButton.setMargin(inset);
editButton.setMargin(inset);
cancelButton.setMargin(inset);
}
/**
* Description of the Method
*
*@param selRow Description of the Parameter
*@param selPath Description of the Parameter
*/
void doubleClick(int selRow, TreePath selPath) {
System.out.println("row " + selRow + " selected");
Object[] objs = selPath.getPath();
Object thing = ((DefaultMutableTreeNode) objs[objs.length - 1]).getUserObject();
showProperties(thing);
}
/**
* Constructor for the JClassTree object
*
*@param sTitle Description of the Parameter
*/
public JClassTree(String sTitle) {
this();
setTitle(sTitle);
}
/**
* Make the dialog visible.
*
*@param b The new visible value
*/
public void setVisible(boolean b) {
if (b) {
setLocation(50, 50);
}
super.setVisible(b);
}
/**
* Adds a feature to the Notify attribute of the JClassTree object
*/
public void addNotify() {
// Record the size of the window prior to calling parents addNotify.
Dimension d = getSize();
Insets in = getInsets();
super.addNotify();
if (fComponentsAdjusted) {
return;
}
// Adjust components according to the insets
setSize(in.left + in.right + d.width, in.top + in.bottom + d.height);
Component components[] = getContentPane().getComponents();
for (int i = 0; i < components.length; i++) {
Point p = components[i].getLocation();
p.translate(in.left, in.top);
components[i].setLocation(p);
}
fComponentsAdjusted = true;
}
/**
* The main program for the JClassTree class
*
*@param args The command line arguments
*/
public static void main(String[] args) {
JClassTree Main = new JClassTree();
Main.setVisible(true);
}
/**
* Description of the Class
*
*@author ulmerh
*@created 20. Januar 2003
*/
class SymWindow extends WindowAdapter {
/**
* Description of the Method
*
*@param event Description of the Parameter
*/
public void windowClosing(java.awt.event.WindowEvent event) {
Object object = event.getSource();
if (object == JClassTree.this) {
JClassTree_WindowClosing(event);
}
}
}
/**
* Description of the Method
*
*@param event Description of the Parameter
*/
void JClassTree_WindowClosing(WindowEvent event) {
setVisible(false);
// hide the Frame
}
/**
* Description of the Class
*
*@author ulmerh
*@created 20. Januar 2003
*/
class SymAction implements ActionListener {
/**
* Description of the Method
*
*@param event Description of the Parameter
*/
public void actionPerformed(java.awt.event.ActionEvent event) {
Object object = event.getSource();
if (object == expandButton) {
expandButton_actionPerformed(event);
} else if (object == collapseButton) {
collapseButton_actionPerformed(event);
} else if (object == editButton) {
editButton_actionPerformed(event);
} else if (object == cancelButton) {
cancelButton_actionPerformed(event);
}
}
}
/**
* Description of the Method
*
*@param event Description of the Parameter
*/
void expandButton_actionPerformed(java.awt.event.ActionEvent event) {
expandTree();
}
/**
* Expand the tree to show all nodes.
*/
public void expandTree() {
int row = 0;
while (row < treeView_.getRowCount()) {
if (treeView_.isCollapsed(row)) {
treeView_.expandRow(row);
}
row++;
}
}
/**
* Description of the Method
*
*@param event Description of the Parameter
*/
void collapseButton_actionPerformed(java.awt.event.ActionEvent event) {
treeView_.collapseRow(0);
}
/**
* Description of the Method
*
*@param event Description of the Parameter
*/
void editButton_actionPerformed(java.awt.event.ActionEvent event) {
Object[] objs = treeView_.getSelectionPath().getPath();
showProperties(((DefaultMutableTreeNode) objs[objs.length - 1]).getUserObject());
}
/**
* Description of the Method
*
*@param event Description of the Parameter
*/
void cancelButton_actionPerformed(java.awt.event.ActionEvent event) {
setVisible(false);
}
/**
* Set the <code>JPane</code> for which the <code>JTree</code> is to be
* built.
*
*@param obj Description of the Parameter
*/
// public void setPara(JPane Para) {
// Enumeration layers;
// Layer ly;
// LayerChild child;
// Graph graph;
// Axis axis;
// CartesianRenderer rend;
// LineAttribute attr;
// GridAttribute gattr;
// PointAttribute pattr;
// //
// DefaultTreeModel treeModel;
// DefaultMutableTreeNode node;
// DefaultMutableTreeNode paneNode;
//
// DefaultMutableTreeNode layerNode;
// DefaultMutableTreeNode childNode;
// DefaultMutableTreeNode graphNode;
// DefaultMutableTreeNode attrNode;
// DefaultMutableTreeNode gattrNode;
// DefaultMutableTreeNode pattrNode;
// DefaultMutableTreeNode axisNode;
// DefaultMutableTreeNode titleNode;
//
// m_Para = Para;
// paneNode = new DefaultMutableTreeNode(m_Para);
// treeModel = new DefaultTreeModel(paneNode);
// treeView_.setModel(treeModel);
// //
// Component[] comps = pane_.getComponents();
// for(int il=0; il < comps.length; il++) {
// if(comps[il] instanceof Layer) {
// ly = (Layer)comps[il];
// } else {
// continue;
// }
// String name, className;
// layerNode = new DefaultMutableTreeNode(ly);
// treeModel.insertNodeInto(layerNode, paneNode, treeModel.getChildCount(paneNode));
// for(Enumeration childs = ly.childElements(); childs.hasMoreElements();) {
// child = (LayerChild)childs.nextElement();
// className = child.getClass().getName();
// name = className.substring(className.lastIndexOf(".")+1);
// childNode = new DefaultMutableTreeNode(child);
// treeModel.insertNodeInto(childNode,layerNode,treeModel.getChildCount(layerNode));
// }
// graph = ly.getGraph();
// className = graph.getClass().getName();
// name = className.substring(className.lastIndexOf(".")+1);
// if(graph instanceof CartesianGraph) {
// graphNode = new DefaultMutableTreeNode(graph);
// treeModel.insertNodeInto(graphNode,layerNode,treeModel.getChildCount(layerNode));
// rend = ((CartesianGraph)graph).getRenderer();
// if(rend instanceof LineCartesianRenderer) {
// attr = (LineAttribute)((LineCartesianRenderer)rend).getAttribute();
// if(attr != null) {
// className = attr.getClass().getName();
// name = className.substring(className.lastIndexOf(".")+1);
// attrNode = new DefaultMutableTreeNode(attr);
// treeModel.insertNodeInto(attrNode,graphNode,treeModel.getChildCount(graphNode));
// }
// } else if(rend instanceof GridCartesianRenderer) {
// gattr = (GridAttribute)((GridCartesianRenderer)rend).getAttribute();
// if(gattr != null) {
// className = gattr.getClass().getName();
// name = className.substring(className.lastIndexOf(".")+1);
// gattrNode = new DefaultMutableTreeNode(gattr);
// treeModel.insertNodeInto(gattrNode,
// graphNode,
// treeModel.getChildCount(graphNode));
// }
// } else if(rend instanceof PointCartesianRenderer) {
// pattr = (PointAttribute)((PointCartesianRenderer)rend).getAttribute();
// if(pattr != null) {
// className = pattr.getClass().getName();
// name = className.substring(className.lastIndexOf(".")+1);
// pattrNode = new DefaultMutableTreeNode(pattr);
// treeModel.insertNodeInto(pattrNode,
// graphNode,
// treeModel.getChildCount(graphNode));
// }
// }
// for(Enumeration axes = ((CartesianGraph)graph).xAxisElements();
// axes.hasMoreElements();) {
// axis = (Axis)axes.nextElement();
// className = axis.getClass().getName();
// name = className.substring(className.lastIndexOf(".")+1);
// if(axis instanceof SpaceAxis) {
// axisNode = new DefaultMutableTreeNode(axis);
// treeModel.insertNodeInto(axisNode,
// graphNode,
// treeModel.getChildCount(graphNode));
// SGLabel title = axis.getTitle();
// if(title != null) {
// titleNode = new DefaultMutableTreeNode(title);
// treeModel.insertNodeInto(titleNode,
// axisNode,
// treeModel.getChildCount(axisNode));
// }
// } else { // not a SpaceAxis
// axisNode = new DefaultMutableTreeNode(axis);
// treeModel.insertNodeInto(axisNode,
// graphNode,
// treeModel.getChildCount(graphNode));
// }
// }
// for(Enumeration axes = ((CartesianGraph)graph).yAxisElements();
// axes.hasMoreElements();) {
// axis = (Axis)axes.nextElement();
// className = axis.getClass().getName();
// name = className.substring(className.lastIndexOf(".")+1);
// if(axis instanceof SpaceAxis) {
// axisNode = new DefaultMutableTreeNode(axis);
// treeModel.insertNodeInto(axisNode,
// graphNode,
// treeModel.getChildCount(graphNode));
// SGLabel title = axis.getTitle();
// if(title != null) {
// titleNode = new DefaultMutableTreeNode(title);
// treeModel.insertNodeInto(titleNode,
// axisNode,
// treeModel.getChildCount(axisNode));
// }
// } else { // not a SpaceAxis
// axisNode = new DefaultMutableTreeNode(axis);
// treeModel.insertNodeInto(axisNode,
// graphNode,
// treeModel.getChildCount(graphNode));
// }
// }
// } else { // not a CartesianGraph
// graphNode = new DefaultMutableTreeNode(graph);
// treeModel.insertNodeInto(graphNode,
// layerNode,
// treeModel.getChildCount(layerNode));
// }
// } // for layers
// int row=0;
// while(row < treeView_.getRowCount()) {
// if(treeView_.isCollapsed(row)) {
// treeView_.expandRow(row);
// }
// row++;
// }
// }
void showProperties(Object obj) {
System.out.println("showProperties obj=" + obj.getClass());
// if(obj instanceof SGLabel) {
// if(sg_ == (SGLabelDialog) null)
// sg_ = new SGLabelDialog();
//
// sg_.setSGLabel((SGLabel) obj, pane_);
// if(!sg_.isShowing())
// sg_.setVisible(true);
// }
// else
// if(obj instanceof Logo) {
// if(lg_ == null) {
// lg_ = new LogoDialog();
// }
// lg_.setLogo((Logo) obj, pane_);
// if(!lg_.isShowing())
// lg_.setVisible(true);
// }
}
/**
* Gets the frame attribute of the JClassTree object
*
*@return The frame value
*/
private Frame getFrame() {
Container theFrame = this;
do {
theFrame = theFrame.getParent();
} while ((theFrame != null) && !(theFrame instanceof Frame));
if (theFrame == null) {
theFrame = new Frame();
}
return (Frame) theFrame;
}
}

View File

@ -1,18 +1,11 @@
package eva2.gui; package eva2.gui;
/* /*
* Title: EvA2 * Title: EvA2 Description: Copyright: Copyright (c) 2003 Company: University of
* Description: * Tuebingen, Computer Architecture @author Holger Ulmer, Felix Streichert,
* Copyright: Copyright (c) 2003 * Hannes Planatscher @version: $Revision: 322 $ $Date: 2007-12-11 17:24:07
* Company: University of Tuebingen, Computer Architecture * +0100 (Tue, 11 Dec 2007) $ $Author: mkron $
* @author Holger Ulmer, Felix Streichert, Hannes Planatscher
* @version: $Revision: 322 $
* $Date: 2007-12-11 17:24:07 +0100 (Tue, 11 Dec 2007) $
* $Author: mkron $
*/ */
/*==========================================================================*
* IMPORTS
*==========================================================================*/
import java.awt.AWTException; import java.awt.AWTException;
import java.awt.Dimension; import java.awt.Dimension;
import java.awt.FlowLayout; import java.awt.FlowLayout;
@ -48,491 +41,489 @@ import eva2.server.go.individuals.AbstractEAIndividual;
import eva2.server.go.populations.Population; import eva2.server.go.populations.Population;
import eva2.tools.BasicResourceLoader; import eva2.tools.BasicResourceLoader;
import eva2.tools.chart2d.DPointSet; import eva2.tools.chart2d.DPointSet;
import java.awt.*;
import javax.swing.*; import javax.swing.*;
import javax.swing.event.InternalFrameAdapter; import javax.swing.event.InternalFrameAdapter;
import javax.swing.event.InternalFrameEvent; import javax.swing.event.InternalFrameEvent;
/*==========================================================================*
* CLASS DECLARATION
*==========================================================================*/
/** /**
* * ToDo: Rename to PlotWindow
*/ */
public class Plot implements PlotInterface, Serializable { public class Plot implements PlotInterface, Serializable {
/** /**
* Generated serial version identifier. * Generated serial version identifier.
*/ */
private static final long serialVersionUID = -9027101244918249825L; private static final long serialVersionUID = -9027101244918249825L;
public static boolean TRACE = false; private JFileChooser m_FileChooser;
private JFileChooser m_FileChooser; private JPanel m_ButtonPanel;
private JPanel m_ButtonPanel; private String plotName;
private String m_PlotName; private String xAxisText;
private String m_xname; private String yAxisText;
private String m_yname; protected FunctionArea m_PlotArea;
protected FunctionArea m_PlotArea; protected JInternalFrame m_Frame;
protected JInternalFrame m_Frame;
/** /**
* You might want to try to assign the x-range as x and y-range as y array * You might want to try to assign the x-range as x and y-range as y array
* parameters. * parameters.
*/ */
public Plot(String PlotName, String xname, String yname, double[] x, double[] y) { public Plot(String plotName, String xname, String yname, double[] x, double[] y) {
this(PlotName, xname, yname, true); this(plotName, xname, yname, true);
DPointSet points = new DPointSet(); DPointSet points = new DPointSet();
for (int i = 0; i < x.length; i++) { for (int i = 0; i < x.length; i++) {
points.addDPoint(x[i], y[i]); points.addDPoint(x[i], y[i]);
} }
m_PlotArea.addDElement(points); m_PlotArea.addDElement(points);
} }
/** /**
* A basic constructor. * A basic constructor.
* *
* @param PlotName * @param PlotName
* @param xname * @param xname
* @param yname * @param yname
* @param init * @param init
*/ */
public Plot(String PlotName, String xname, String yname) { public Plot(String PlotName, String xname, String yname) {
this(PlotName, xname, yname, true); this(PlotName, xname, yname, true);
} }
/**
* A basic constructor.
*
* @param PlotName
* @param xname
* @param yname
* @param init
*/
public Plot(String PlotName, String xname, String yname, boolean init) {
if (TRACE)
System.out.println("Constructor Plot " + PlotName);
m_xname = xname;
m_yname = yname;
m_PlotName = PlotName;
if (init)
init();
}
protected void installButtons(JPanel buttonPan) { /**
JButton ClearButton = new JButton("Clear"); * A basic constructor.
ClearButton.addActionListener(new ActionListener() { *
public void actionPerformed(ActionEvent e) { * @param plotName
clearAll(); * @param xname
} * @param yname
}); * @param init
JButton LOGButton = new JButton("Log/Lin"); */
LOGButton public Plot(String plotName, String xname, String yname, boolean init) {
.setToolTipText("Toggle between a linear and a log scale on the y-axis."); xAxisText = xname;
LOGButton.addActionListener(new ActionListener() { yAxisText = yname;
public void actionPerformed(ActionEvent e) { this.plotName = plotName;
m_PlotArea.toggleLog(); if (init) {
} this.init();
}); }
JButton ExportButton = new JButton("Export..."); }
ExportButton
.setToolTipText("Exports the graph data to a simple ascii file.");
ExportButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
exportPlot();
}
});
JButton DumpButton = new JButton("Dump");
DumpButton.setToolTipText("Dump the graph data to standard output");
DumpButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
m_PlotArea.exportToAscii();
}
});
JButton saveImageButton = new JButton("Save as PNG..."); protected void installButtons(JPanel buttonPan) {
saveImageButton.addActionListener(new ActionListener() { JButton ClearButton = new JButton("Clear");
public void actionPerformed(ActionEvent e) { ClearButton.addActionListener(new ActionListener() {
try {
Robot robot = new Robot();
Rectangle area;
area = m_Frame.getBounds();
BufferedImage bufferedImage = robot
.createScreenCapture(area);
JFileChooser fc = new JFileChooser();
if (fc.showSaveDialog(m_Frame) != JFileChooser.APPROVE_OPTION)
return;
// System.out.println("Name " + outfile);
try {
/*
* Old version FileOutputStream fos = new
* FileOutputStream
* (fc.getSelectedFile().getAbsolutePath()+".jpeg");
* BufferedOutputStream bos = new
* BufferedOutputStream(fos); JPEGImageEncoder encoder =
* JPEGCodec.createJPEGEncoder(bos);
* encoder.encode(bufferedImage); bos.close();
*/
File file = new File(fc.getSelectedFile()
.getAbsolutePath()
+ ".png");
ImageIO.write(bufferedImage, "png", file);
/*
* JPEG version with javax.imageio float compression =
* 0.8f; FileImageOutputStream out = new
* FileImageOutputStream(new
* File(fc.getSelectedFile().getAbsolutePath
* ()+".jpeg")); ImageWriter encoder =
* (ImageWriter)ImageIO
* .getImageWritersByFormatName("JPEG").next();
* JPEGImageWriteParam param = new
* JPEGImageWriteParam(null);
*
*
* param.setCompressionMode(ImageWriteParam.MODE_EXPLICIT
* ); param.setCompressionQuality(compression);
*
* encoder.setOutput(out); encoder.write((IIOMetadata)
* null, new IIOImage(bufferedImage,null,null), param);
*
* out.close();
*/
} catch (Exception eee) { public void actionPerformed(ActionEvent e) {
System.err.println("Error on exporting PNG: " clearAll();
+ eee.getMessage()); }
} });
} catch (AWTException ee) { JButton LOGButton = new JButton("Log/Lin");
System.err.println("Error on creating PNG: " LOGButton.setToolTipText("Toggle between a linear and a log scale on the y-axis.");
+ ee.getMessage()); LOGButton.addActionListener(new ActionListener() {
ee.printStackTrace();
}
}
});
buttonPan.add(ClearButton); public void actionPerformed(ActionEvent e) {
buttonPan.add(LOGButton); m_PlotArea.toggleLog();
buttonPan.add(DumpButton); }
buttonPan.add(ExportButton); });
// m_ButtonPanel.add(PrintButton); JButton ExportButton = new JButton("Export...");
// m_ButtonPanel.add(OpenButton); ExportButton.setToolTipText("Exports the graph data to a simple ascii file.");
// m_ButtonPanel.add(SaveButton); ExportButton.addActionListener(new ActionListener() {
buttonPan.add(saveImageButton);
}
/** public void actionPerformed(ActionEvent e) {
* exportPlot();
*/ }
public void init() { });
m_Frame = new JEFrame("Plot: " + m_PlotName); JButton DumpButton = new JButton("Dump");
BasicResourceLoader loader = BasicResourceLoader.instance(); DumpButton.setToolTipText("Dump the graph data to standard output");
byte[] bytes = loader.getBytesFromResourceLocation(EvAInfo.iconLocation, true); DumpButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
m_PlotArea.exportToAscii();
}
});
JButton saveImageButton = new JButton("Save as PNG...");
saveImageButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
try {
Robot robot = new Robot();
Rectangle area;
area = m_Frame.getBounds();
BufferedImage bufferedImage = robot.createScreenCapture(area);
JFileChooser fc = new JFileChooser();
if (fc.showSaveDialog(m_Frame) != JFileChooser.APPROVE_OPTION) {
return;
}
// System.out.println("Name " + outfile);
try {
/*
* Old version FileOutputStream fos = new
* FileOutputStream
* (fc.getSelectedFile().getAbsolutePath()+".jpeg");
* BufferedOutputStream bos = new
* BufferedOutputStream(fos); JPEGImageEncoder encoder =
* JPEGCodec.createJPEGEncoder(bos);
* encoder.encode(bufferedImage); bos.close();
*/
File file = new File(fc.getSelectedFile().getAbsolutePath()
+ ".png");
ImageIO.write(bufferedImage, "png", file);
/*
* JPEG version with javax.imageio float compression =
* 0.8f; FileImageOutputStream out = new
* FileImageOutputStream(new
* File(fc.getSelectedFile().getAbsolutePath
* ()+".jpeg")); ImageWriter encoder =
* (ImageWriter)ImageIO
* .getImageWritersByFormatName("JPEG").next();
* JPEGImageWriteParam param = new
* JPEGImageWriteParam(null);
*
*
* param.setCompressionMode(ImageWriteParam.MODE_EXPLICIT
* ); param.setCompressionQuality(compression);
*
* encoder.setOutput(out); encoder.write((IIOMetadata)
* null, new IIOImage(bufferedImage,null,null), param);
*
* out.close();
*/
} catch (Exception eee) {
System.err.println("Error on exporting PNG: "
+ eee.getMessage());
}
} catch (AWTException ee) {
System.err.println("Error on creating PNG: "
+ ee.getMessage());
ee.printStackTrace();
}
}
});
buttonPan.add(ClearButton);
buttonPan.add(LOGButton);
buttonPan.add(DumpButton);
buttonPan.add(ExportButton);
// m_ButtonPanel.add(PrintButton);
// m_ButtonPanel.add(OpenButton);
// m_ButtonPanel.add(SaveButton);
buttonPan.add(saveImageButton);
}
/**
*
*/
public void init() {
m_Frame = new JEFrame("Plot: " + plotName);
BasicResourceLoader loader = BasicResourceLoader.instance();
byte[] bytes = loader.getBytesFromResourceLocation(EvAInfo.iconLocation, true);
// m_Frame.setIconImage(Toolkit.getDefaultToolkit().createImage(bytes)); // m_Frame.setIconImage(Toolkit.getDefaultToolkit().createImage(bytes));
m_ButtonPanel = new JPanel(); m_ButtonPanel = new JPanel();
m_PlotArea = new FunctionArea(m_xname, m_yname); m_PlotArea = new FunctionArea(xAxisText, yAxisText);
m_ButtonPanel.setLayout(new FlowLayout(FlowLayout.LEFT, 10, 10)); m_ButtonPanel.setLayout(new FlowLayout(FlowLayout.LEFT, 10, 10));
installButtons(m_ButtonPanel); installButtons(m_ButtonPanel);
// getContentPane().smultetLayout( new GridLayout(1, 4) ); // getContentPane().smultetLayout( new GridLayout(1, 4) );
m_Frame.getContentPane().add(m_ButtonPanel, "South"); m_Frame.add(m_ButtonPanel, BorderLayout.PAGE_END);
m_Frame.getContentPane().add(m_PlotArea, "Center"); // north was not so m_Frame.add(m_PlotArea, BorderLayout.CENTER); // north was not so
// nice // nice
m_Frame.addInternalFrameListener(new InternalFrameAdapter() { m_Frame.addInternalFrameListener(new InternalFrameAdapter() {
@Override @Override
public void internalFrameClosing(InternalFrameEvent e) { public void internalFrameClosing(InternalFrameEvent e) {
super.internalFrameClosing(e); super.internalFrameClosing(e);
m_PlotArea.clearAll(); // this was a memory leak m_PlotArea.clearAll(); // this was a memory leak
m_PlotArea = null; m_PlotArea = null;
m_Frame.dispose(); m_Frame.dispose();
} }
}); });
m_Frame.pack(); m_Frame.pack();
m_Frame.setVisible(true); m_Frame.setVisible(true);
} }
/**
* Indicate whether graph legend entries should show their unique number.
*/
public void setAppendIndexInLegend(boolean appendIndexInLegend) {
this.m_PlotArea.setAppendIndexInLegend(appendIndexInLegend);
}
/**
* Indicates whether graph legend entries show their unique number.
*/
public boolean isAppendIndexInLegend() {
return m_PlotArea.isAppendIndexInLegend();
}
/**
* Indicate whether the graphs are annotated by tool tip info strings.
* @return true if the graphs are annotated by tool tip info strings
*/
public boolean isShowGraphToolTips() {
return m_PlotArea.isShowGraphToolTips();
}
/**
* Toggle whether the graphs should be annotated by tool tip info strings.
* @param doShowGraphToolTips true if the graphs should be annotated by tool tip info strings
*/
public void setShowGraphToolTips(boolean doShowGraphToolTips) {
m_PlotArea.setShowGraphToolTips(doShowGraphToolTips);
}
/**
* Draw a population to the Plot instance. Each individual is annotated with
* the given prefix and its fitness.
*
* @param prefix
* @param pop
*/
public void drawPopulation(String prefix, Population pop) {
for (int i = 0; i < pop.size(); i++) {
drawIndividual(0, 2, prefix, pop.getEAIndividual(i));
}
}
/** /**
* Draw an individual to the Plot instance. It is annotated with the * Indicate whether graph legend entries should show their unique number.
* given prefix and its fitness with short scientific notation. */
* public void setAppendIndexInLegend(boolean appendIndexInLegend) {
* @param prefix this.m_PlotArea.setAppendIndexInLegend(appendIndexInLegend);
* @param pop }
* @see FunctionArea.drawIcon
*/
public void drawIndividual(int iconType, int graphID, String prefix, AbstractEAIndividual indy) {
StringBuffer sb = new StringBuffer();
Formatter formatter = new Formatter(sb, Locale.US);
formatter.format("%s %.3e", prefix, indy.getFitness(0));
getFunctionArea().drawIcon(iconType, sb.toString(), indy.getDoublePosition(), graphID); /**
} * Indicates whether graph legend entries show their unique number.
*/
public boolean isAppendIndexInLegend() {
return m_PlotArea.isAppendIndexInLegend();
}
public void setPreferredSize(Dimension prefSize) { /**
if (m_Frame != null) { * Indicate whether the graphs are annotated by tool tip info strings.
m_Frame.setPreferredSize(prefSize); *
m_Frame.pack(); * @return true if the graphs are annotated by tool tip info strings
} */
} public boolean isShowGraphToolTips() {
return m_PlotArea.isShowGraphToolTips();
}
/** /**
* Return true if the Plot object is valid. * Toggle whether the graphs should be annotated by tool tip info strings.
* *
* @return true if the Plot object is valid * @param doShowGraphToolTips true if the graphs should be annotated by tool
*/ * tip info strings
public boolean isValid() { */
return (m_Frame != null) && (m_PlotArea != null); public void setShowGraphToolTips(boolean doShowGraphToolTips) {
} m_PlotArea.setShowGraphToolTips(doShowGraphToolTips);
}
/** /**
* * Draw a population to the Plot instance. Each individual is annotated with
*/ * the given prefix and its fitness.
public void setConnectedPoint(double x, double y, int func) { *
if (TRACE) * @param prefix
System.out.println("size before is " * @param pop
+ m_PlotArea.getPointCount(func)); */
m_PlotArea.setConnectedPoint(x, y, func); public void drawPopulation(String prefix, Population pop) {
if (TRACE) { for (int i = 0; i < pop.size(); i++) {
System.out.println("added " + x + "/" + y + " to graph " + func); drawIndividual(0, 2, prefix, pop.getEAIndividual(i));
System.out.println("size is now " + m_PlotArea.getPointCount(func)); }
} }
}
public int getPointCount(int graphLabel) { /**
return m_PlotArea.getPointCount(graphLabel); * Draw an individual to the Plot instance. It is annotated with the given
} * prefix and its fitness with short scientific notation.
*
* @param prefix
* @param pop
* @see FunctionArea.drawIcon
*/
public void drawIndividual(int iconType, int graphID, String prefix, AbstractEAIndividual indy) {
StringBuffer sb = new StringBuffer();
Formatter formatter = new Formatter(sb, Locale.US);
formatter.format("%s %.3e", prefix, indy.getFitness(0));
/** getFunctionArea().drawIcon(iconType, sb.toString(), indy.getDoublePosition(), graphID);
* }
*/
public void addGraph(int g1, int g2, boolean forceAdd) {
m_PlotArea.addGraph(g1, g2, forceAdd);
}
/** public void setPreferredSize(Dimension prefSize) {
* if (m_Frame != null) {
*/ m_Frame.setPreferredSize(prefSize);
public void setUnconnectedPoint(double x, double y, int GraphLabel) { m_Frame.pack();
m_PlotArea.setUnconnectedPoint(x, y, GraphLabel); }
} }
/** /**
* * Return true if the Plot object is valid.
*/ *
public void clearAll() { * @return true if the Plot object is valid
m_PlotArea.clearAll(); */
m_PlotArea.removeAllDElements(); public boolean isValid() {
m_PlotArea.clearLegend(); return (m_Frame != null) && (m_PlotArea != null);
m_Frame.repaint(); }
}
/** /**
* *
*/ */
public void clearGraph(int GraphNumber) { public void setConnectedPoint(double x, double y, int func) {
m_PlotArea.clearGraph(GraphNumber); m_PlotArea.setConnectedPoint(x, y, func);
} }
/** public int getPointCount(int graphLabel) {
* return m_PlotArea.getPointCount(graphLabel);
*/ }
public void setInfoString(int GraphLabel, String Info, float stroke) {
m_PlotArea.setInfoString(GraphLabel, Info, stroke);
}
/** /**
* *
*/ */
public void jump() { public void addGraph(int g1, int g2, boolean forceAdd) {
m_PlotArea.jump(); m_PlotArea.addGraph(g1, g2, forceAdd);
} }
/** /**
*/ *
protected Object openObject() { */
if (m_FileChooser == null) public void setUnconnectedPoint(double x, double y, int GraphLabel) {
createFileChooser(); m_PlotArea.setUnconnectedPoint(x, y, GraphLabel);
int returnVal = m_FileChooser.showOpenDialog(m_Frame); }
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();
Class<?> ClassType = Class.forName("FunctionArea");
if (!ClassType.isAssignableFrom(obj.getClass()))
throw new Exception("Object not of type: "
+ ClassType.getName());
return obj;
} catch (Exception ex) {
JOptionPane.showMessageDialog(m_Frame, "Couldn't read object: "
+ selected.getName() + "\n" + ex.getMessage(),
"Open object file", JOptionPane.ERROR_MESSAGE);
}
}
return null;
}
/** /**
* Just dump the plot to stdout. *
*/ */
protected void dumpPlot() { public void clearAll() {
m_PlotArea.exportToAscii(); m_PlotArea.clearAll();
} m_PlotArea.removeAllDElements();
m_PlotArea.clearLegend();
m_Frame.repaint();
}
/** /**
* *
*/ */
protected void exportPlot() { public void clearGraph(int GraphNumber) {
if (m_FileChooser == null) m_PlotArea.clearGraph(GraphNumber);
createFileChooser(); }
int returnVal = m_FileChooser.showSaveDialog(m_Frame);
if (returnVal == JFileChooser.APPROVE_OPTION) {
File sFile = m_FileChooser.getSelectedFile();
if (sFile.exists()) {
returnVal = JOptionPane.showConfirmDialog(m_Frame, "The file "
+ sFile.getName() + " already exists. Overwrite?");
if (returnVal != JOptionPane.YES_OPTION)
return;
}
if (!(m_PlotArea.exportToAscii(sFile))) {
JOptionPane.showMessageDialog(m_Frame,
"Couldn't write to file: " + sFile.getName(),
"Export error", JOptionPane.ERROR_MESSAGE);
}
}
}
/** /**
* *
*/ */
protected void saveObject(Object object) { public void setInfoString(int GraphLabel, String Info, float stroke) {
if (m_FileChooser == null) m_PlotArea.setInfoString(GraphLabel, Info, stroke);
createFileChooser(); }
int returnVal = m_FileChooser.showSaveDialog(m_Frame);
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(m_Frame,
"Couldn't write to file: " + sFile.getName() + "\n"
+ ex.getMessage(), "Save object",
JOptionPane.ERROR_MESSAGE);
}
}
}
/** /**
* *
*/ */
protected void createFileChooser() { public void jump() {
m_FileChooser = new JFileChooser(new File("/resources")); m_PlotArea.jump();
m_FileChooser.setFileSelectionMode(JFileChooser.FILES_ONLY); }
}
/** /**
* */
*/ protected Object openObject() {
public String getName() { if (m_FileChooser == null) {
return this.m_PlotName; createFileChooser();
} }
int returnVal = m_FileChooser.showOpenDialog(m_Frame);
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();
Class<?> ClassType = Class.forName("FunctionArea");
if (!ClassType.isAssignableFrom(obj.getClass())) {
throw new Exception("Object not of type: "
+ ClassType.getName());
}
return obj;
} catch (Exception ex) {
JOptionPane.showMessageDialog(m_Frame, "Couldn't read object: "
+ selected.getName() + "\n" + ex.getMessage(),
"Open object file", JOptionPane.ERROR_MESSAGE);
}
}
return null;
}
/** /**
* * Just dump the plot to stdout.
*/ */
public FunctionArea getFunctionArea() { protected void dumpPlot() {
return m_PlotArea; m_PlotArea.exportToAscii();
} }
/** /**
* *
*/ */
public void dispose() { protected void exportPlot() {
m_Frame.dispose(); if (m_FileChooser == null) {
m_Frame = null; createFileChooser();
} }
int returnVal = m_FileChooser.showSaveDialog(m_Frame);
if (returnVal == JFileChooser.APPROVE_OPTION) {
File sFile = m_FileChooser.getSelectedFile();
if (sFile.exists()) {
returnVal = JOptionPane.showConfirmDialog(m_Frame, "The file "
+ sFile.getName() + " already exists. Overwrite?");
if (returnVal != JOptionPane.YES_OPTION) {
return;
}
}
if (!(m_PlotArea.exportToAscii(sFile))) {
JOptionPane.showMessageDialog(m_Frame,
"Couldn't write to file: " + sFile.getName(),
"Export error", JOptionPane.ERROR_MESSAGE);
}
}
}
/** /**
* Add the corners of the given range as unconnected points. *
* */
* @param range protected void saveObject(Object object) {
* @param graphLabel if (m_FileChooser == null) {
*/ createFileChooser();
public void setCornerPoints(double[][] range, int graphLabel) { }
setUnconnectedPoint(range[0][0], range[1][0], graphLabel); int returnVal = m_FileChooser.showSaveDialog(m_Frame);
setUnconnectedPoint(range[0][1], range[1][1], graphLabel); 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(m_Frame,
"Couldn't write to file: " + sFile.getName() + "\n"
+ ex.getMessage(), "Save object",
JOptionPane.ERROR_MESSAGE);
}
}
}
public void setColorByIndex(int graphLabel, int index) { /**
getFunctionArea().setColorByIndex(graphLabel, index); *
} */
protected void createFileChooser() {
m_FileChooser = new JFileChooser(new File("/resources"));
m_FileChooser.setFileSelectionMode(JFileChooser.FILES_ONLY);
}
public void recolorAllGraphsByIndex() { /**
getFunctionArea().recolorAllGraphsByIndex(); *
} */
public String getName() {
// /** return this.plotName;
// * Just for testing the Plot class. }
// */
// public static void main( String[] args ){ /**
// Plot plot = new Plot("Plot-Test","x-value","y-value"); *
// plot.init(); */
// double x; public FunctionArea getFunctionArea() {
// for (x= 0; x <6000; x++) { return m_PlotArea;
// //double y = SpecialFunction.getnormcdf(x); }
// // double yy = 0.5*SpecialFunction.getnormpdf(x);
// double n = Math.sin(((double)x/1000*Math.PI)); /**
// //plot.setConnectedPoint(x,Math.sin(x),0); *
// //plot.setConnectedPoint(x,Math.cos(x),1); */
// //plot.setConnectedPoint(x,y,0); public void dispose() {
// plot.setConnectedPoint(x,n,1); m_Frame.dispose();
// } m_Frame = null;
// //plot.addGraph(1,2); }
// }
/**
* Add the corners of the given range as unconnected points.
*
* @param range
* @param graphLabel
*/
public void setCornerPoints(double[][] range, int graphLabel) {
setUnconnectedPoint(range[0][0], range[1][0], graphLabel);
setUnconnectedPoint(range[0][1], range[1][1], graphLabel);
}
public void setColorByIndex(int graphLabel, int index) {
getFunctionArea().setColorByIndex(graphLabel, index);
}
public void recolorAllGraphsByIndex() {
getFunctionArea().recolorAllGraphsByIndex();
}
// /**
// * Just for testing the Plot class.
// */
// public static void main( String[] args ){
// Plot plot = new Plot("Plot-Test","x-value","y-value");
// plot.init();
// double x;
// for (x= 0; x <6000; x++) {
// //double y = SpecialFunction.getnormcdf(x);
// // double yy = 0.5*SpecialFunction.getnormpdf(x);
// double n = Math.sin(((double)x/1000*Math.PI));
// //plot.setConnectedPoint(x,Math.sin(x),0);
// //plot.setConnectedPoint(x,Math.cos(x),1);
// //plot.setConnectedPoint(x,y,0);
// plot.setConnectedPoint(x,n,1);
// }
// //plot.addGraph(1,2);
// }
} }

File diff suppressed because it is too large Load Diff

View File

@ -27,63 +27,60 @@ import eva2.server.go.problems.InterfaceOptimizationProblem;
* $Date: 2007-12-04 14:31:47 +0100 (Tue, 04 Dec 2007) $ * $Date: 2007-12-04 14:31:47 +0100 (Tue, 04 Dec 2007) $
* $Author: mkron $ * $Author: mkron $
*/ */
public class EvolutionStrategies implements InterfaceOptimizer, java.io.Serializable { public class EvolutionStrategies implements InterfaceOptimizer, java.io.Serializable {
//private double m_MyuRatio = 6; protected int mu = 5;
protected int m_Mu = 5; protected int lambda = 20;
protected int m_Lambda = 20; protected boolean usePlusStrategy = false;
protected boolean m_UsePlusStrategy = false; protected Population population = new Population();
protected Population m_Population = new Population(); protected InterfaceOptimizationProblem optimizationProblem = new B1Problem();
protected InterfaceOptimizationProblem m_Problem = new B1Problem(); private InterfaceSelection parentSelection = new SelectRandom();
private InterfaceSelection m_ParentSelection = new SelectRandom(); private InterfaceSelection partnerSelection = new SelectRandom();
private InterfaceSelection m_PartnerSelection = new SelectRandom(); private InterfaceSelection environmentSelection = new SelectBestIndividuals();
private InterfaceSelection m_EnvironmentSelection = new SelectBestIndividuals(); private int numberOfPartners = 1;
private int m_NumberOfPartners = 1; protected int origPopSize = -1; // especially for CBN
protected int origPopSize = -1; // especially for CBN private boolean forceOrigPopSize = true;// especially for CBN
// private double[] m_FitnessOfParents = null; transient private String identifier = "";
private boolean forceOrigPopSize = true;// especially for CBN transient private InterfacePopulationChangedEventListener changeListener;
transient private String m_Identifier = "";
transient private InterfacePopulationChangedEventListener m_Listener;
private static final boolean TRACE = false;
public static final String esMuParam = "EvolutionStrategyMuParameter"; public static final String esMuParam = "EvolutionStrategyMuParameter";
public static final String esLambdaParam = "EvolutionStrategyLambdaParameter"; public static final String esLambdaParam = "EvolutionStrategyLambdaParameter";
public EvolutionStrategies() { public EvolutionStrategies() {
this.m_Population.setTargetSize(this.m_Lambda); this.population.setTargetSize(this.lambda);
} }
public EvolutionStrategies(int mu, int lambda, boolean usePlus) { public EvolutionStrategies(int mu, int lambda, boolean usePlus) {
setMu(mu); setMu(mu);
setLambda(lambda); setLambda(lambda);
setPlusStrategy(usePlus); setPlusStrategy(usePlus);
this.checkPopulationConstraints(); this.checkPopulationConstraints();
} }
public EvolutionStrategies(EvolutionStrategies a) { public EvolutionStrategies(EvolutionStrategies evStrategies) {
this.m_Mu = a.m_Mu; this.mu = evStrategies.mu;
this.m_Lambda = a.m_Lambda; this.lambda = evStrategies.lambda;
this.m_UsePlusStrategy = a.m_UsePlusStrategy; this.usePlusStrategy = evStrategies.usePlusStrategy;
this.m_Population = (Population)a.m_Population.clone(); this.population = (Population) evStrategies.population.clone();
this.m_Problem = (InterfaceOptimizationProblem)a.m_Problem.clone(); this.optimizationProblem = (InterfaceOptimizationProblem) evStrategies.optimizationProblem.clone();
this.m_NumberOfPartners = a.m_NumberOfPartners; this.numberOfPartners = evStrategies.numberOfPartners;
this.m_ParentSelection = (InterfaceSelection)a.m_ParentSelection.clone(); this.parentSelection = (InterfaceSelection) evStrategies.parentSelection.clone();
this.m_PartnerSelection = (InterfaceSelection)a.m_PartnerSelection.clone(); this.partnerSelection = (InterfaceSelection) evStrategies.partnerSelection.clone();
this.m_EnvironmentSelection = (InterfaceSelection)a.m_EnvironmentSelection.clone(); this.environmentSelection = (InterfaceSelection) evStrategies.environmentSelection.clone();
this.m_NumberOfPartners = a.m_NumberOfPartners; this.numberOfPartners = evStrategies.numberOfPartners;
this.origPopSize = a.origPopSize; this.origPopSize = evStrategies.origPopSize;
this.forceOrigPopSize = a.forceOrigPopSize; this.forceOrigPopSize = evStrategies.forceOrigPopSize;
} }
/** /**
* Set to true in CBN, false for any extension which changes the population size during optimization. * Set to true in CBN, false for any extension which changes the population
* size during optimization.
*
* @param force * @param force
*/ */
public void setForceOrigPopSize(boolean force) { public void setForceOrigPopSize(boolean force) {
forceOrigPopSize = force; forceOrigPopSize = force;
} }
public void hideHideable() { public void hideHideable() {
// GenericObjectEditor.setHideProperty(this.getClass(), "population", true); // GenericObjectEditor.setHideProperty(this.getClass(), "population", true);
} }
@ -93,496 +90,430 @@ public class EvolutionStrategies implements InterfaceOptimizer, java.io.Serializ
} }
public void init() { public void init() {
// @todo In case of CBN-ES i need to read the population size!? checkPopulationConstraints();
// int orgPopSize = this.m_Population.getPopulationSize(); population.putData(esMuParam, getMu());
// if (this.m_InitialPopulationSize > orgPopSize) { population.putData(esLambdaParam, getLambda());
// this.m_Population.setPopulationSize(this.m_InitialPopulationSize); this.optimizationProblem.initPopulation(this.population);
// } this.evaluatePopulation(this.population);
//System.out.println("init");
checkPopulationConstraints();
m_Population.putData(esMuParam, getMu());
m_Population.putData(esLambdaParam, getLambda());
this.m_Problem.initPopulation(this.m_Population);
this.evaluatePopulation(this.m_Population);
// this.m_Population.setPopulationSize(orgPopSize);
// this.firePropertyChangedEvent(Population.nextGenerationPerformed);// not necessary if incrGeneration is called
} }
/**
/** This method will init the optimizer with a given population * This method will init the optimizer with a given population
* @param pop The initial population *
* @param reset If true the population is reset. * @param pop The initial population
* @param reset If true the population is reset.
*/ */
public void initByPopulation(Population pop, boolean reset) { public void initByPopulation(Population pop, boolean reset) {
origPopSize = pop.getTargetSize(); origPopSize = pop.getTargetSize();
// System.out.println("ES: orig popsize is " + origPopSize); this.population = (Population) pop.clone();
this.m_Population = (Population)pop.clone();
if (reset) { if (reset) {
this.m_Population.init(); this.population.init();
this.evaluatePopulation(this.m_Population); this.evaluatePopulation(this.population);
// this.firePropertyChangedEvent(Population.nextGenerationPerformed); // not necessary if incrGeneration is called
} }
} }
/** This method will evaluate the current population using the /**
* given problem. * This method will evaluate the current population using the given problem.
*
* @param population The population that is to be evaluated * @param population The population that is to be evaluated
*/ */
protected void evaluatePopulation(Population population) { protected void evaluatePopulation(Population population) {
this.m_Problem.evaluate(population); this.optimizationProblem.evaluate(population);
population.incrGeneration(); population.incrGeneration();
if (TRACE) System.out.println("ES Evaluated " + population.size());
} }
// /** This method allows you to set myu and lambda
// * @param myu The size of the temporary population
// * @param lambda The size of the offsprings created
// * @param plus The general population strategy.
// */
// public void setGenerationStrategy(int myu, int lambda, boolean plus) {
// this.m_UsePlusStrategy = plus;
// this.m_Myu = myu;
// this.m_Lambda = lambda;
// this.m_MyuRatio = this.m_Lambda/(double)this.m_Myu;
// if (this.m_UsePlusStrategy) this.m_Population.setPopulationSize(myu+lambda);
// else this.m_Population.setPopulationSize(lambda);
// }
/** /**
* This method will generate the offspring population from the * This method will generate the offspring population from the given
* given population of evaluated individuals. * population of evaluated individuals.
*/ */
protected Population generateEvalChildren(Population fromPopulation) { protected Population generateEvalChildren(Population fromPopulation) {
Population result = m_Population.cloneWithoutInds(), parents; Population result = population.cloneWithoutInds(), parents;
result.clear(); result.clear();
parents = generateChildren(fromPopulation, result, this.m_Lambda); parents = generateChildren(fromPopulation, result, this.lambda);
this.evaluatePopulation(result); this.evaluatePopulation(result);
if (result.getEAIndividual(0).getMutationOperator() instanceof InterfaceAdaptOperatorGenerational) { if (result.getEAIndividual(0).getMutationOperator() instanceof InterfaceAdaptOperatorGenerational) {
// this seems to be the right moment for the 1/5-success rule // this seems to be the right moment for the 1/5-success rule
// parents and result have the same size and correspond per individual // parents and result have the same size and correspond per individual
((InterfaceAdaptOperatorGenerational)parents.getEAIndividual(0).getMutationOperator()).adaptGenerational(fromPopulation, parents, result, m_UsePlusStrategy); ((InterfaceAdaptOperatorGenerational) parents.getEAIndividual(0).getMutationOperator()).adaptGenerational(fromPopulation, parents, result, usePlusStrategy);
} }
if (parents.getEAIndividual(0).getCrossoverOperator() instanceof InterfaceAdaptOperatorGenerational) { if (parents.getEAIndividual(0).getCrossoverOperator() instanceof InterfaceAdaptOperatorGenerational) {
((InterfaceAdaptOperatorGenerational)parents.getEAIndividual(0).getCrossoverOperator()).adaptGenerational(fromPopulation, parents, result, m_UsePlusStrategy); ((InterfaceAdaptOperatorGenerational) parents.getEAIndividual(0).getCrossoverOperator()).adaptGenerational(fromPopulation, parents, result, usePlusStrategy);
} }
return result; return result;
} }
/** /**
* Create a new population by parent selection, partner selection, recombination and crossover. * Create a new population by parent selection, partner selection,
* The new population is added to the result population, while the selected parent population (after * recombination and crossover. The new population is added to the result
* selection but before recombination/crossover) is returned. * population, while the selected parent population (after selection but
* Returned parents and result population are to have the same size and correspond per individual. * before recombination/crossover) is returned. Returned parents and result
* * population are to have the same size and correspond per individual.
*
* @param fromPopulation * @param fromPopulation
* @param result * @param result
* @param lambda * @param lambda
* @return * @return
*/ */
protected Population generateChildren(Population fromPopulation, Population result, int lambda) { protected Population generateChildren(Population fromPopulation, Population result, int lambda) {
AbstractEAIndividual tmpIndy; AbstractEAIndividual tmpIndy;
AbstractEAIndividual[] offSprings; AbstractEAIndividual[] offSprings;
Population parents; Population parents;
if (TRACE ) System.out.println("ES From pop size " + fromPopulation.size() + " selecting parents/creating children: " + lambda); this.parentSelection.prepareSelection(fromPopulation);
this.m_ParentSelection.prepareSelection(fromPopulation); this.partnerSelection.prepareSelection(fromPopulation);
this.m_PartnerSelection.prepareSelection(fromPopulation); parents = this.parentSelection.selectFrom(fromPopulation, lambda);
parents = this.m_ParentSelection.selectFrom(fromPopulation, lambda);
for (int i = 0; i < parents.size(); i++) { for (int i = 0; i < parents.size(); i++) {
tmpIndy = (AbstractEAIndividual)parents.get(i); tmpIndy = (AbstractEAIndividual) parents.get(i);
offSprings = tmpIndy.mateWith(this.m_PartnerSelection.findPartnerFor(tmpIndy, fromPopulation, this.m_NumberOfPartners)); offSprings = tmpIndy.mateWith(this.partnerSelection.findPartnerFor(tmpIndy, fromPopulation, this.numberOfPartners));
offSprings[0].mutate(); offSprings[0].mutate();
result.add(i, offSprings[0]); result.add(i, offSprings[0]);
} }
return parents; return parents;
} }
protected Population selectParents(Population fromPop, int mu) { protected Population selectParents(Population fromPop, int mu) {
if (TRACE) System.out.println("ES env selecting parents: " + mu + " of " + fromPop.size()); this.environmentSelection.prepareSelection(fromPop);
this.m_EnvironmentSelection.prepareSelection(fromPop); return this.environmentSelection.selectFrom(fromPop, mu);
return this.m_EnvironmentSelection.selectFrom(fromPop, mu);
} }
/** /**
* The optimize method will compute an improved and evaluated population. * The optimize method will compute an improved and evaluated population.
*/ */
@Override
public void optimize() { public void optimize() {
Population nextGeneration, parents; Population nextGeneration, parents;
//System.out.println("optimize");
// first perform the environment selection to select myu parents // first perform the environment selection to select myu parents
parents = selectParents(m_Population, this.m_Mu); parents = selectParents(population, this.mu);
// System.out.println("-- selected avg fit " + BeanInspector.toString(parents.getMeanFitness()) + " from last gen " + BeanInspector.toString(m_Population.getMeanFitness())); // population / parents are of sizes lambda / mu
// m_Population / parents are of sizes lambda / mu
if (parents.getEAIndividual(0).getMutationOperator() instanceof InterfaceAdaptOperatorGenerational) { if (parents.getEAIndividual(0).getMutationOperator() instanceof InterfaceAdaptOperatorGenerational) {
((InterfaceAdaptOperatorGenerational)parents.getEAIndividual(0).getMutationOperator()).adaptAfterSelection(getPopulation(), parents); ((InterfaceAdaptOperatorGenerational) parents.getEAIndividual(0).getMutationOperator()).adaptAfterSelection(getPopulation(), parents);
} }
if (parents.getEAIndividual(0).getCrossoverOperator() instanceof InterfaceAdaptOperatorGenerational) { if (parents.getEAIndividual(0).getCrossoverOperator() instanceof InterfaceAdaptOperatorGenerational) {
((InterfaceAdaptOperatorGenerational)parents.getEAIndividual(0).getCrossoverOperator()).adaptAfterSelection(getPopulation(), parents); ((InterfaceAdaptOperatorGenerational) parents.getEAIndividual(0).getCrossoverOperator()).adaptAfterSelection(getPopulation(), parents);
} }
// now generate the lambda offsprings // now generate the lambda offsprings
nextGeneration = this.generateEvalChildren(parents); // create lambda new ones from mu parents // create lambda new ones from mu parents
nextGeneration = this.generateEvalChildren(parents);
if (this.isPlusStrategy()) nextGeneration.addPopulation(parents);
if (this.isPlusStrategy()) {
nextGeneration.addPopulation(parents);
}
setPop(getReplacePop(nextGeneration)); setPop(getReplacePop(nextGeneration));
// System.out.println("Population size: " + this.m_Population.size());
// System.out.println("-- Best Fitness " + this.m_Population.getBestFitness()[0]);
this.firePropertyChangedEvent(Population.nextGenerationPerformed); // necessary here because evalPop was not called on m_Population // necessary here because evalPop was not called on population
} this.firePropertyChangedEvent(Population.nextGenerationPerformed);
}
/** /**
* Usually, this just returns the given population. * Usually, this just returns the given population. However, in case of CBN
* However, in case of CBN this method prepares the next generation according to the species size. * this method prepares the next generation according to the species size.
* *
* @param nextGeneration * @param nextGeneration
* @return * @return
*/ */
protected Population getReplacePop(Population nextGeneration) { protected Population getReplacePop(Population nextGeneration) {
if (forceOrigPopSize && (origPopSize > 0) && (origPopSize < nextGeneration.size())) { if (forceOrigPopSize && (origPopSize > 0) && (origPopSize < nextGeneration.size())) {
// this is especially for CBN: earlier selection to immediately reduce the size of mu+lambda to lambda // this is especially for CBN: earlier selection to immediately reduce the size of mu+lambda to lambda
this.m_EnvironmentSelection.prepareSelection(nextGeneration); this.environmentSelection.prepareSelection(nextGeneration);
Population tmpPop = (Population)nextGeneration.clone(); Population tmpPop = (Population) nextGeneration.clone();
nextGeneration.clear(); nextGeneration.clear();
nextGeneration.addPopulation(this.m_EnvironmentSelection.selectFrom(tmpPop, origPopSize)); nextGeneration.addPopulation(this.environmentSelection.selectFrom(tmpPop, origPopSize));
// System.out.println("ES post selection! " + origPopSize + " from " + tmpPop.size()); } else {
} else { if ((origPopSize > 0) && (origPopSize != nextGeneration.size())) {
if ((origPopSize > 0) && (origPopSize != nextGeneration.size())) { System.err.println("Warning in ES! orig: " + origPopSize + " / " + nextGeneration.size());
System.err.println("Warning in ES! orig: " + origPopSize + " / " + nextGeneration.size()); }
} }
} return nextGeneration;
return nextGeneration;
} }
/** This method is just a shortcut to set the mutation step size for /**
* all individuals of these two populations for the 1/5 Success rule. * This method allows you to add the LectureGUI as listener to the Optimizer
* This is only necessary because i decided to make the variable *
* non static
* @param successRate The success rate
* @param oldPop The old population
* @param newPop The new population
*/
// private void applySuccessRule(double successRate, Population oldPop, Population newPop) {
// MutateESSuccessRule mutator = (MutateESSuccessRule)((AbstractEAIndividual)oldPop.get(0)).getMutationOperator();
// boolean success = (successRate < mutator.getSuccessRate());
// // this was the old solution when the mutation step size was still static
//// if (successRate < mutator.getSuccessRate()) {
//// mutator.decreaseMutationStepSize();
//// } else {
//// mutator.increaseMutationStepSize();
//// }
// if (isPlusStrategy()) for (int i = 0; i < oldPop.size(); i++) { // applied to the old population as well for plus strategy
// if (((AbstractEAIndividual)oldPop.get(i)).getMutationOperator() instanceof MutateESSuccessRule) {
// mutator = (MutateESSuccessRule)((AbstractEAIndividual)oldPop.get(i)).getMutationOperator();
// if (success) mutator.decreaseMutationStepSize();
// else mutator.increaseMutationStepSize();
// System.out.println("old pop step size " + mutator.getSigma()+ " (" + mutator+ ")");
// }
// }
// for (int i = 0; i < newPop.size(); i++) {
// if (((AbstractEAIndividual)newPop.get(i)).getMutationOperator() instanceof MutateESSuccessRule) {
// mutator = (MutateESSuccessRule)((AbstractEAIndividual)newPop.get(i)).getMutationOperator();
// if (success) mutator.decreaseMutationStepSize();
// else mutator.increaseMutationStepSize();
// System.out.println("new pop step size " + mutator.getSigma() + " (" + mutator+ ")");
// }
// }
//// this.m_FitnessOfParents = null;
// }
// /** This is for debugging only
// */
// private String showFitness(Population pop) {
// String result = "";
// AbstractEAIndividual indy;
// double[] fitness;
// for (int i = 0; i < pop.size(); i++) {
// indy = (AbstractEAIndividual)pop.get(i);
// fitness = indy.getFitness();
// for (int j = 0; j < fitness.length; j++) result += fitness[j] +"; ";
// result += "\n";
// }
// return result;
// }
/** This method allows you to add the LectureGUI as listener to the Optimizer
* @param ea * @param ea
*/ */
@Override
public void addPopulationChangedEventListener(InterfacePopulationChangedEventListener ea) { public void addPopulationChangedEventListener(InterfacePopulationChangedEventListener ea) {
this.m_Listener = ea; this.changeListener = ea;
} }
public boolean removePopulationChangedEventListener(
InterfacePopulationChangedEventListener ea) { @Override
if (m_Listener==ea) { public boolean removePopulationChangedEventListener(InterfacePopulationChangedEventListener ea) {
m_Listener=null; if (changeListener == ea) {
return true; changeListener = null;
} else return false; return true;
} } else {
/** Something has changed return false;
}
}
/**
* Something has changed
*/ */
protected void firePropertyChangedEvent(String name) { protected void firePropertyChangedEvent(String name) {
if (this.m_Listener != null) this.m_Listener.registerPopulationStateChanged(this, name); if (this.changeListener != null) {
this.changeListener.registerPopulationStateChanged(this, name);
}
} }
/** This method will set the problem that is to be optimized /**
* This method will set the problem that is to be optimized
*
* @param problem * @param problem
*/ */
public void SetProblem (InterfaceOptimizationProblem problem) { public void SetProblem(InterfaceOptimizationProblem problem) {
this.m_Problem = problem; this.optimizationProblem = problem;
}
public InterfaceOptimizationProblem getProblem () {
return this.m_Problem;
} }
/** This method will return a string describing all properties of the optimizer public InterfaceOptimizationProblem getProblem() {
* and the applied methods. return this.optimizationProblem;
}
/**
* This method will return a string describing all properties of the
* optimizer and the applied methods.
*
* @return A descriptive string * @return A descriptive string
*/ */
public String getStringRepresentation() { public String getStringRepresentation() {
String result = ""; String result = "";
result += "Evolution Strategies:\n"; result += "Evolution Strategies:\n";
result += "Optimization Problem: "; result += "Optimization Problem: ";
result += this.m_Problem.getStringRepresentationForProblem(this) +"\n"; result += this.optimizationProblem.getStringRepresentationForProblem(this) + "\n";
result += this.m_Population.getStringRepresentation(); result += this.population.getStringRepresentation();
return result; return result;
} }
/** This method allows you to set myu and lambda in one step /**
* This method allows you to set myu and lambda in one step
*
* @param myu * @param myu
* @param lambda * @param lambda
* @param plus True if plus, false if comma strategy * @param plus True if plus, false if comma strategy
*/ */
public void setGenerationStrategy(int myu, int lambda, boolean plus) { public void setGenerationStrategy(int myu, int lambda, boolean plus) {
this.m_Mu = myu; this.mu = myu;
this.m_Lambda = lambda; this.lambda = lambda;
this.m_UsePlusStrategy = plus; this.usePlusStrategy = plus;
this.checkPopulationConstraints(); this.checkPopulationConstraints();
} }
/** /**
* This method will check the population constraints * This method will check the population constraints myu <= lambda and will
* myu <= lambda and will calculate the population size * calculate the population size accordingly.
* accordingly.
*/ */
protected void checkPopulationConstraints() { protected void checkPopulationConstraints() {
if (this.m_Lambda < this.m_Mu) { if (this.lambda < this.mu) {
System.err.println("Invalid mu/lambda ratio! Setting mu=lambda="+m_Mu); System.err.println("Invalid mu/lambda ratio! Setting mu=lambda=" + mu);
this.m_Lambda = this.m_Mu; this.lambda = this.mu;
} }
// if (this.m_UsePlusStrategy) this.m_Population.setTargetSize(this.m_Mu + this.m_Lambda); this.population.setTargetSize(this.lambda);
// else this.m_Population.setTargetSize(this.m_Lambda); origPopSize = population.getTargetSize();
this.m_Population.setTargetSize(this.m_Lambda);
origPopSize=m_Population.getTargetSize();
} }
/** This method allows you to set an identifier for the algorithm /**
* @param name The indenifier * This method allows you to set an identifier for the algorithm
*
* @param name The indenifier
*/ */
public void SetIdentifier(String name) { public void SetIdentifier(String name) {
this.m_Identifier = name; this.identifier = name;
} }
public String getIdentifier() {
return this.m_Identifier;
}
/** This method is required to free the memory on a RMIServer, public String getIdentifier() {
* but there is nothing to implement. return this.identifier;
}
/**
* This method is required to free the memory on a RMIServer, but there is
* nothing to implement.
*/ */
public void freeWilly() { public void freeWilly() {
}
} /**
/********************************************************************************************************************** * These are for GUI
* These are for GUI */
*/
/** This method returns a global info string /**
* This method returns a global info string
*
* @return description * @return description
*/ */
public static String globalInfo() { public static String globalInfo() {
return "This is an Evolution Strategy. Note that the population size depends on mu (number of parents) and lambda (number of offspring)."; return "This is an Evolution Strategy. Note that the population size depends on mu (number of parents) and lambda (number of offspring).";
} }
public String[] customPropertyOrder() { public String[] customPropertyOrder() {
return new String[]{"mu", "lambda"}; return new String[]{"mu", "lambda"};
} }
/** This method will return a naming String /**
* This method will return a naming String
*
* @return The name of the algorithm * @return The name of the algorithm
*/ */
public String getName() { public String getName() {
return "("+getMu()+(isPlusStrategy() ? "+" : ",")+getLambda()+")-ES"; return "(" + getMu() + (isPlusStrategy() ? "+" : ",") + getLambda() + ")-ES";
} }
/** /**
* Assuming that all optimizer will store their data in a population * Assuming that all optimizer will store their data in a population we will
* we will allow access to this population to query to current state * allow access to this population to query to current state of the
* of the optimizer. * optimizer.
*
* @return The population of current solutions to a given problem. * @return The population of current solutions to a given problem.
*/ */
public Population getPopulation() { public Population getPopulation() {
return this.m_Population; return this.population;
} }
// for internal usage // for internal usage
protected void setPop(Population pop) { protected void setPop(Population pop) {
if (TRACE) System.out.println("ES Setting pop of " + pop.size()); this.population = pop;
m_Population = pop;
} }
public void setPopulation(Population pop){ public void setPopulation(Population pop) {
if (TRACE) System.out.println("ES Setting pop of " + pop.size()); origPopSize = pop.size();
origPopSize = pop.size(); this.population = pop;
// System.err.println("In ES: orig popsize is " + origPopSize);
this.m_Population = pop;
} }
public String populationTipText() { public String populationTipText() {
return "Edit the properties of the population used."; return "Edit the properties of the population used.";
} }
public InterfaceSolutionSet getAllSolutions() {
return new SolutionSet(getPopulation());
}
// /** This method will set the normation method that is to be used.
// * @param normation
// */
// public void setNormationMethod (InterfaceNormation normation) {
// this.m_NormationOperator = normation;
// }
// public InterfaceNormation getNormationMethod () {
// return this.m_NormationOperator;
// }
// public String normationMethodTipText() {
// return "Select the normation method.";
// }
/** This method will set the selection method that is to be used public InterfaceSolutionSet getAllSolutions() {
return new SolutionSet(getPopulation());
}
/**
* This method will set the selection method that is to be used
*
* @param selection * @param selection
*/ */
public void setEnvironmentSelection(InterfaceSelection selection) { public void setEnvironmentSelection(InterfaceSelection selection) {
this.m_EnvironmentSelection = selection; this.environmentSelection = selection;
} }
public InterfaceSelection getEnvironmentSelection() { public InterfaceSelection getEnvironmentSelection() {
return this.m_EnvironmentSelection; return this.environmentSelection;
} }
public String environmentSelectionTipText() { public String environmentSelectionTipText() {
return "Choose a method for selecting the reduced population."; return "Choose a method for selecting the reduced population.";
} }
/** This method will set the selection method that is to be used to select the partners /**
* This method will set the selection method that is to be used to select
* the partners
*
* @param selection * @param selection
*/ */
public void setPartnerSelection(InterfaceSelection selection) { public void setPartnerSelection(InterfaceSelection selection) {
this.m_PartnerSelection = selection; this.partnerSelection = selection;
} }
public InterfaceSelection getPartnerSelection() { public InterfaceSelection getPartnerSelection() {
return this.m_PartnerSelection; return this.partnerSelection;
} }
public String partnerSelectionTipText() { public String partnerSelectionTipText() {
return "Choose a selection method for selecting recombination partners."; return "Choose a selection method for selecting recombination partners.";
} }
/** This method will set the selection method that is to be used to select the parents /**
* This method will set the selection method that is to be used to select
* the parents
*
* @param selection * @param selection
*/ */
public void setParentSelection(InterfaceSelection selection) { public void setParentSelection(InterfaceSelection selection) {
this.m_ParentSelection = selection; this.parentSelection = selection;
} }
public InterfaceSelection getParentSelection() { public InterfaceSelection getParentSelection() {
return this.m_ParentSelection; return this.parentSelection;
} }
public String parentSelectionTipText() { public String parentSelectionTipText() {
return "Choose a selection method for selecting parents."; return "Choose a selection method for selecting parents.";
} }
/** This method will toggel between plus and comma selection strategy /**
* This method will toggle between plus and comma selection strategy
*
* @param elitism * @param elitism
*/ */
public void setPlusStrategy (boolean elitism) { public void setPlusStrategy(boolean elitism) {
this.m_UsePlusStrategy = elitism; this.usePlusStrategy = elitism;
// this.checkPopulationConstraints(); // do this on init only
} }
public boolean isPlusStrategy() { public boolean isPlusStrategy() {
return this.m_UsePlusStrategy; return this.usePlusStrategy;
} }
public String plusStrategyTipText() { public String plusStrategyTipText() {
return "Select between plus and comma strategy."; return "Select between plus and comma strategy.";
} }
/** This method will set the number of partners that are needed to create /**
* This method will set the number of partners that are needed to create
* offsprings by mating * offsprings by mating
*
* @param partners * @param partners
*/ */
public void setNumberOfPartners(int partners) { public void setNumberOfPartners(int partners) {
if (partners < 0) partners = 0; if (partners < 0) {
this.m_NumberOfPartners = partners; partners = 0;
}
this.numberOfPartners = partners;
} }
public int getNumberOfPartners() { public int getNumberOfPartners() {
return this.m_NumberOfPartners; return this.numberOfPartners;
} }
public String numberOfPartnersTipText() { public String numberOfPartnersTipText() {
return "The number of mating partners needed to create offsprings."; return "The number of mating partners needed to create offsprings.";
} }
// /** This method will set the ratio between myu and lambda /**
// * @param lambdaratio * This method allows you to set parent population size myu
// */ *
// public void setLambdaRatio(int lambdaratio) { * @param myu The parent population size.
// if (lambdaratio < 1) lambdaratio = 1;
// this.m_LambdaRatio = lambdaratio;
// }
// public int getLambdaRatio() {
// return this.m_LambdaRatio;
// }
// public String lambdaRatioTipText() {
// return "This is the myu/lambda ratio.";
// }
/** This method will set the ratio between myu and lambda
* @param myuratio
*/
// public void setMyuRatio(double myuratio) {
// if (myuratio < 1) myuratio = 1;
// this.m_MyuRatio = myuratio;
// }
// public double getMyuRatio() {
// return this.m_MyuRatio;
// }
// public String myuRatioTipText() {
// return "This is the lambda/myu ratio.";
// }
/** This method allows you to set parent population size myu
* @param myu The parent population size.
*/ */
public void setMu(int mu) { public void setMu(int mu) {
this.m_Mu = mu; this.mu = mu;
// this.checkPopulationConstraints(); // do this on init only
} }
public int getMu() { public int getMu() {
return this.m_Mu; return this.mu;
} }
public String muTipText() { public String muTipText() {
return "This is the parent population size."; return "This is the parent population size.";
} }
/** This is the children population size lambda /**
* @param lambda The children population size. * This is the children population size lambda
*
* @param lambda The children population size.
*/ */
public void setLambda(int lambda) { public void setLambda(int lambda) {
this.m_Lambda = lambda; this.lambda = lambda;
// this.checkPopulationConstraints(); // do this on init only
} }
public int getLambda() { public int getLambda() {
return this.m_Lambda; return this.lambda;
} }
public String lambdaTipText() { public String lambdaTipText() {
return "This is the children population size."; return "This is the children population size.";
} }

View File

@ -1,18 +1,8 @@
package eva2.server.modules; package eva2.server.modules;
import eva2.EvAInfo; import eva2.EvAInfo;
import java.util.List;
import java.util.Vector;
import javax.swing.JOptionPane;
import eva2.gui.BeanInspector; import eva2.gui.BeanInspector;
import eva2.server.go.InterfaceGOParameters; import eva2.server.go.*;
import eva2.server.go.InterfaceNotifyOnInformers;
import eva2.server.go.InterfacePopulationChangedEventListener;
import eva2.server.go.InterfaceProcessor;
import eva2.server.go.InterfaceTerminator;
import eva2.server.go.PopulationInterface;
import eva2.server.go.operators.paramcontrol.ConstantParameters; import eva2.server.go.operators.paramcontrol.ConstantParameters;
import eva2.server.go.operators.paramcontrol.InterfaceParameterControl; import eva2.server.go.operators.paramcontrol.InterfaceParameterControl;
import eva2.server.go.operators.postprocess.PostProcess; import eva2.server.go.operators.postprocess.PostProcess;
@ -32,8 +22,11 @@ import eva2.tools.EVAHELP;
import eva2.tools.StringTools; import eva2.tools.StringTools;
import eva2.tools.jproxy.RemoteStateListener; import eva2.tools.jproxy.RemoteStateListener;
import eva2.tools.math.RNG; import eva2.tools.math.RNG;
import java.util.ArrayList;
import java.util.List;
import java.util.logging.Level; import java.util.logging.Level;
import java.util.logging.Logger; import java.util.logging.Logger;
import javax.swing.JOptionPane;
/** /**
* The Processor may run as a thread permanently (GenericModuleAdapter) and is then stopped and started * The Processor may run as a thread permanently (GenericModuleAdapter) and is then stopped and started
@ -400,7 +393,7 @@ public class Processor extends Thread implements InterfaceProcessor, InterfacePo
} }
protected List<InterfaceAdditionalPopulationInformer> getInformerList() { protected List<InterfaceAdditionalPopulationInformer> getInformerList() {
Vector<InterfaceAdditionalPopulationInformer> informerList = new Vector<InterfaceAdditionalPopulationInformer>(2); List<InterfaceAdditionalPopulationInformer> informerList = new ArrayList<InterfaceAdditionalPopulationInformer>(2);
informerList.add(this.goParams.getProblem()); informerList.add(this.goParams.getProblem());
if (this.goParams.getOptimizer() instanceof InterfaceAdditionalPopulationInformer) { if (this.goParams.getOptimizer() instanceof InterfaceAdditionalPopulationInformer) {
informerList.add((InterfaceAdditionalPopulationInformer) this.goParams.getOptimizer()); informerList.add((InterfaceAdditionalPopulationInformer) this.goParams.getOptimizer());