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;
import eva2.tools.BasicResourceLoader;
import java.io.InputStream;
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
*
*/

View File

@ -1,11 +1,5 @@
/*
* Copyright (c) ZBiT, University of Tübingen, Germany
*/
package eva2;
import java.util.BitSet;
import java.util.Vector;
import eva2.server.go.IndividualInterface;
import eva2.server.go.InterfacePopulationChangedEventListener;
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.NoCrossover;
import eva2.server.go.operators.distancemetric.IndividualDataMetric;
import eva2.server.go.operators.mutation.InterfaceMutation;
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.mutation.*;
import eva2.server.go.operators.postprocess.InterfacePostProcessParams;
import eva2.server.go.operators.postprocess.PostProcessParams;
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.Population;
import eva2.server.go.problems.AbstractOptimizationProblem;
import eva2.server.go.strategies.ClusterBasedNichingEA;
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.go.strategies.*;
import eva2.server.modules.GOParameters;
import eva2.server.stat.InterfaceStatistics;
import eva2.tools.math.RNG;
import java.util.ArrayList;
import java.util.BitSet;
import java.util.List;
/**
* <p>
@ -1011,19 +986,19 @@ public class OptimizerFactory {
return runnable.getResultPopulation();
}
public static Vector<BitSet> postProcessBinVec(int steps, double sigma,
public static List<BitSet> postProcessBinVec(int steps, double sigma,
int nBest) {
return (lastRunnable != null) ? postProcessBinVec(lastRunnable,
new PostProcessParams(steps, sigma, nBest)) : null;
}
public static Vector<BitSet> postProcessBinVec(
public static List<BitSet> postProcessBinVec(
InterfacePostProcessParams ppp) {
return (lastRunnable != null) ? postProcessBinVec(lastRunnable, ppp)
: null;
}
public static Vector<BitSet> postProcessBinVec(OptimizerRunnable runnable,
public static List<BitSet> postProcessBinVec(OptimizerRunnable runnable,
int steps, double sigma, int nBest) {
return postProcessBinVec(runnable, new PostProcessParams(steps, sigma,
nBest));
@ -1037,10 +1012,10 @@ public class OptimizerFactory {
* @param ppp
* @return
*/
public static Vector<BitSet> postProcessBinVec(OptimizerRunnable runnable,
public static List<BitSet> postProcessBinVec(OptimizerRunnable runnable,
InterfacePostProcessParams 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) {
if (o instanceof InterfaceDataTypeBinary) {
InterfaceDataTypeBinary indy = (InterfaceDataTypeBinary) o;
@ -1050,19 +1025,19 @@ public class OptimizerFactory {
return ret;
}
public static Vector<double[]> postProcessDblVec(int steps, double sigma,
public static List<double[]> postProcessDblVec(int steps, double sigma,
int nBest) {
return (lastRunnable == null) ? null : postProcessDblVec(lastRunnable,
new PostProcessParams(steps, sigma, nBest));
}
public static Vector<double[]> postProcessDblVec(
public static List<double[]> postProcessDblVec(
InterfacePostProcessParams ppp) {
return (lastRunnable != null) ? postProcessDblVec(lastRunnable, ppp)
: null;
}
public static Vector<double[]> postProcessDblVec(
public static List<double[]> postProcessDblVec(
OptimizerRunnable runnable, int steps, double sigma, int nBest) {
return postProcessDblVec(runnable, new PostProcessParams(steps, sigma,
nBest));
@ -1076,10 +1051,10 @@ public class OptimizerFactory {
* @param ppp
* @return
*/
public static Vector<double[]> postProcessDblVec(
public static List<double[]> postProcessDblVec(
OptimizerRunnable runnable, InterfacePostProcessParams 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) {
if (o instanceof InterfaceDataTypeDouble) {
InterfaceDataTypeDouble indy = (InterfaceDataTypeDouble) o;
@ -1089,19 +1064,19 @@ public class OptimizerFactory {
return ret;
}
public static Vector<AbstractEAIndividual> postProcessIndVec(int steps,
public static List<AbstractEAIndividual> postProcessIndVec(int steps,
double sigma, int nBest) {
return (lastRunnable != null) ? postProcessIndVec(lastRunnable,
new PostProcessParams(steps, sigma, nBest)) : null;
}
public static Vector<AbstractEAIndividual> postProcessIndVec(
public static List<AbstractEAIndividual> postProcessIndVec(
InterfacePostProcessParams ppp) {
return (lastRunnable != null) ? postProcessIndVec(lastRunnable, ppp)
: null;
}
public static Vector<AbstractEAIndividual> postProcessIndVec(
public static List<AbstractEAIndividual> postProcessIndVec(
OptimizerRunnable runnable, int steps, double sigma, int nBest) {
return postProcessIndVec(runnable, new PostProcessParams(steps, sigma,
nBest));
@ -1115,10 +1090,10 @@ public class OptimizerFactory {
* @param ppp
* @return
*/
public static Vector<AbstractEAIndividual> postProcessIndVec(
public static List<AbstractEAIndividual> postProcessIndVec(
OptimizerRunnable runnable, InterfacePostProcessParams ppp) {
Population resPop = postProcess(runnable, ppp);
Vector<AbstractEAIndividual> ret = new Vector<AbstractEAIndividual>(
List<AbstractEAIndividual> ret = new ArrayList<AbstractEAIndividual>(
resPop.size());
for (Object o : resPop) {
if (o instanceof AbstractEAIndividual) {
@ -1428,8 +1403,7 @@ public class OptimizerFactory {
MutateESRankMuCMA cmaMut = new MutateESRankMuCMA();
AbstractEAIndividual.setOperators(indy, cmaMut, 1., new CrossoverESDefault(), 0.);
} else {
System.err
.println("Error, CMA-ES is implemented for ES individuals only (requires double data types)");
System.err.println("Error, CMA-ES is implemented for ES individuals only (requires double data types)");
return null;
}

View File

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

View File

@ -187,6 +187,7 @@ public class FunctionArea extends DArea implements Serializable {
*/
private void addPopup() {
addMouseListener(new MouseAdapter() {
public void mouseClicked(MouseEvent e) {
if ((e.getModifiers() & InputEvent.BUTTON1_MASK) == InputEvent.BUTTON1_MASK) {
// do nothing
@ -196,6 +197,7 @@ public class FunctionArea extends DArea implements Serializable {
m_y = e.getY();
addMenuItem(graphPopupMenu, "Rename graph", new ActionListener() {
public void actionPerformed(ActionEvent ee) {
renameGraph(getNearestGraphIndex(FunctionArea.this.m_x, FunctionArea.this.m_y));
}
@ -206,6 +208,7 @@ public class FunctionArea extends DArea implements Serializable {
+ " graph tool tips";
addMenuItem(graphPopupMenu, togGTTName,
new ActionListener() {
public void actionPerformed(ActionEvent ee) {
setShowGraphToolTips(!isShowGraphToolTips());
}
@ -214,12 +217,14 @@ public class FunctionArea extends DArea implements Serializable {
String togLName = (isShowLegend() ? "Hide" : "Show")
+ " legend";
addMenuItem(graphPopupMenu, togLName, new ActionListener() {
public void actionPerformed(ActionEvent ee) {
toggleLegend();
}
});
addMenuItem(graphPopupMenu, "Toggle scientific format", new ActionListener() {
public void actionPerformed(ActionEvent ee) {
toggleScientificY(true);
}
@ -240,6 +245,7 @@ public class FunctionArea extends DArea implements Serializable {
addMenuItem(graphPopupMenu, "Select Reference Point:("
+ temp.x + "/" + temp.y + ")",
new ActionListener() {
public void actionPerformed(ActionEvent ee) {
DPoint temp = getDMeasures().getDPoint(
m_x, m_y);
@ -258,12 +264,14 @@ public class FunctionArea extends DArea implements Serializable {
addMenuItem(graphPopupMenu, "Nearest point: ("
+ point.x + "/" + point.y + ")",
new ActionListener() {
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);
@ -272,21 +280,17 @@ public class FunctionArea extends DArea implements Serializable {
if (point.getIcon() instanceof InterfaceSelectablePointIcon) {
m_CurrentPointIcon = point.getIcon();
if (((InterfaceSelectablePointIcon) m_CurrentPointIcon)
.getSelectionListener() != null) {
AbstractEAIndividual indy = ((InterfaceSelectablePointIcon) m_CurrentPointIcon)
.getEAIndividual();
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());
((InterfaceSelectablePointIcon) m_CurrentPointIcon).getSelectionListener().individualSelected(
((InterfaceSelectablePointIcon) m_CurrentPointIcon).getEAIndividual());
}
});
}
@ -296,10 +300,10 @@ public class FunctionArea extends DArea implements Serializable {
m_CurrentPointIcon = point.getIcon();
addMenuItem(graphPopupMenu, " Show individual",
new ActionListener() {
public void actionPerformed(
ActionEvent ee) {
((InterfaceDPointWithContent) m_CurrentPointIcon)
.showIndividual();
((InterfaceDPointWithContent) m_CurrentPointIcon).showIndividual();
}
});
}
@ -317,12 +321,13 @@ public class FunctionArea extends DArea implements Serializable {
addMenuItem(graphPopupMenu, "Graph Info: "
+ getGraphInfo(e.getX(), e.getY()),
new ActionListener() {
public void actionPerformed(ActionEvent ee) {
DPoint temp = FunctionArea.this
.getDMeasures().getDPoint(
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);
}
@ -339,6 +344,7 @@ public class FunctionArea extends DArea implements Serializable {
addMenuItem(graphPopupMenu, " Remove graph",
new ActionListener() {
public void actionPerformed(ActionEvent ee) {
clearGraph(FunctionArea.this.m_x,
FunctionArea.this.m_y);
@ -347,6 +353,7 @@ public class FunctionArea extends DArea implements Serializable {
addMenuItem(graphPopupMenu, " Change graph color",
new ActionListener() {
public void actionPerformed(ActionEvent ee) {
changeColorGraph(FunctionArea.this.m_x,
FunctionArea.this.m_y);

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;
/*
* Title: EvA2
* Description:
* Copyright: Copyright (c) 2003
* Company: University of Tuebingen, Computer Architecture
* @author Holger Ulmer, Felix Streichert, Hannes Planatscher
* @version: $Revision: 322 $
* $Date: 2007-12-11 17:24:07 +0100 (Tue, 11 Dec 2007) $
* $Author: mkron $
* Title: EvA2 Description: Copyright: Copyright (c) 2003 Company: University of
* Tuebingen, Computer Architecture @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.Dimension;
import java.awt.FlowLayout;
@ -48,15 +41,13 @@ import eva2.server.go.individuals.AbstractEAIndividual;
import eva2.server.go.populations.Population;
import eva2.tools.BasicResourceLoader;
import eva2.tools.chart2d.DPointSet;
import java.awt.*;
import javax.swing.*;
import javax.swing.event.InternalFrameAdapter;
import javax.swing.event.InternalFrameEvent;
/*==========================================================================*
* CLASS DECLARATION
*==========================================================================*/
/**
*
* ToDo: Rename to PlotWindow
*/
public class Plot implements PlotInterface, Serializable {
@ -64,12 +55,11 @@ public class Plot implements PlotInterface, Serializable {
* Generated serial version identifier.
*/
private static final long serialVersionUID = -9027101244918249825L;
public static boolean TRACE = false;
private JFileChooser m_FileChooser;
private JPanel m_ButtonPanel;
private String m_PlotName;
private String m_xname;
private String m_yname;
private String plotName;
private String xAxisText;
private String yAxisText;
protected FunctionArea m_PlotArea;
protected JInternalFrame m_Frame;
@ -77,8 +67,8 @@ public class Plot implements PlotInterface, Serializable {
* You might want to try to assign the x-range as x and y-range as y array
* parameters.
*/
public Plot(String PlotName, String xname, String yname, double[] x, double[] y) {
this(PlotName, xname, yname, true);
public Plot(String plotName, String xname, String yname, double[] x, double[] y) {
this(plotName, xname, yname, true);
DPointSet points = new DPointSet();
for (int i = 0; i < x.length; i++) {
points.addDPoint(x[i], y[i]);
@ -101,40 +91,40 @@ public class Plot implements PlotInterface, Serializable {
/**
* A basic constructor.
*
* @param PlotName
* @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();
public Plot(String plotName, String xname, String yname, boolean init) {
xAxisText = xname;
yAxisText = yname;
this.plotName = plotName;
if (init) {
this.init();
}
}
protected void installButtons(JPanel buttonPan) {
JButton ClearButton = new JButton("Clear");
ClearButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
clearAll();
}
});
JButton LOGButton = new JButton("Log/Lin");
LOGButton
.setToolTipText("Toggle between a linear and a log scale on the y-axis.");
LOGButton.setToolTipText("Toggle between a linear and a log scale on the y-axis.");
LOGButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
m_PlotArea.toggleLog();
}
});
JButton ExportButton = new JButton("Export...");
ExportButton
.setToolTipText("Exports the graph data to a simple ascii file.");
ExportButton.setToolTipText("Exports the graph data to a simple ascii file.");
ExportButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
exportPlot();
}
@ -142,6 +132,7 @@ public class Plot implements PlotInterface, Serializable {
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();
}
@ -149,16 +140,17 @@ public class Plot implements PlotInterface, Serializable {
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);
BufferedImage bufferedImage = robot.createScreenCapture(area);
JFileChooser fc = new JFileChooser();
if (fc.showSaveDialog(m_Frame) != JFileChooser.APPROVE_OPTION)
if (fc.showSaveDialog(m_Frame) != JFileChooser.APPROVE_OPTION) {
return;
}
// System.out.println("Name " + outfile);
try {
/*
@ -170,8 +162,7 @@ public class Plot implements PlotInterface, Serializable {
* JPEGCodec.createJPEGEncoder(bos);
* encoder.encode(bufferedImage); bos.close();
*/
File file = new File(fc.getSelectedFile()
.getAbsolutePath()
File file = new File(fc.getSelectedFile().getAbsolutePath()
+ ".png");
ImageIO.write(bufferedImage, "png", file);
/*
@ -221,20 +212,20 @@ public class Plot implements PlotInterface, Serializable {
*
*/
public void init() {
m_Frame = new JEFrame("Plot: " + m_PlotName);
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_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));
installButtons(m_ButtonPanel);
// getContentPane().smultetLayout( new GridLayout(1, 4) );
m_Frame.getContentPane().add(m_ButtonPanel, "South");
m_Frame.getContentPane().add(m_PlotArea, "Center"); // north was not so
m_Frame.add(m_ButtonPanel, BorderLayout.PAGE_END);
m_Frame.add(m_PlotArea, BorderLayout.CENTER); // north was not so
// nice
m_Frame.addInternalFrameListener(new InternalFrameAdapter() {
@ -266,6 +257,7 @@ public class Plot implements PlotInterface, Serializable {
/**
* 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() {
@ -274,7 +266,9 @@ public class Plot implements PlotInterface, Serializable {
/**
* 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
*
* @param doShowGraphToolTips true if the graphs should be annotated by tool
* tip info strings
*/
public void setShowGraphToolTips(boolean doShowGraphToolTips) {
m_PlotArea.setShowGraphToolTips(doShowGraphToolTips);
@ -294,8 +288,8 @@ public class Plot implements PlotInterface, Serializable {
}
/**
* Draw an individual to the Plot instance. It is annotated with the
* given prefix and its fitness with short scientific notation.
* 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
@ -329,14 +323,7 @@ public class Plot implements PlotInterface, Serializable {
*
*/
public void setConnectedPoint(double x, double y, int func) {
if (TRACE)
System.out.println("size before is "
+ m_PlotArea.getPointCount(func));
m_PlotArea.setConnectedPoint(x, y, func);
if (TRACE) {
System.out.println("added " + x + "/" + y + " to graph " + func);
System.out.println("size is now " + m_PlotArea.getPointCount(func));
}
}
public int getPointCount(int graphLabel) {
@ -391,8 +378,9 @@ public class Plot implements PlotInterface, Serializable {
/**
*/
protected Object openObject() {
if (m_FileChooser == null)
if (m_FileChooser == null) {
createFileChooser();
}
int returnVal = m_FileChooser.showOpenDialog(m_Frame);
if (returnVal == JFileChooser.APPROVE_OPTION) {
File selected = m_FileChooser.getSelectedFile();
@ -402,9 +390,10 @@ public class Plot implements PlotInterface, Serializable {
Object obj = oi.readObject();
oi.close();
Class<?> ClassType = Class.forName("FunctionArea");
if (!ClassType.isAssignableFrom(obj.getClass()))
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: "
@ -426,17 +415,19 @@ public class Plot implements PlotInterface, Serializable {
*
*/
protected void exportPlot() {
if (m_FileChooser == null)
if (m_FileChooser == 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)
if (returnVal != JOptionPane.YES_OPTION) {
return;
}
}
if (!(m_PlotArea.exportToAscii(sFile))) {
JOptionPane.showMessageDialog(m_Frame,
"Couldn't write to file: " + sFile.getName(),
@ -449,8 +440,9 @@ public class Plot implements PlotInterface, Serializable {
*
*/
protected void saveObject(Object object) {
if (m_FileChooser == null)
if (m_FileChooser == null) {
createFileChooser();
}
int returnVal = m_FileChooser.showSaveDialog(m_Frame);
if (returnVal == JFileChooser.APPROVE_OPTION) {
File sFile = m_FileChooser.getSelectedFile();
@ -480,7 +472,7 @@ public class Plot implements PlotInterface, Serializable {
*
*/
public String getName() {
return this.m_PlotName;
return this.plotName;
}
/**
@ -516,7 +508,6 @@ public class Plot implements PlotInterface, Serializable {
public void recolorAllGraphsByIndex() {
getFunctionArea().recolorAllGraphsByIndex();
}
// /**
// * Just for testing the Plot class.
// */

View File

@ -34,55 +34,67 @@ import eva2.tools.math.Mathematics;
import eva2.tools.math.RNG;
/**
* The ES niching with dynamic peak identification. Basically, for a set of "peaks" a set of (mu,lambda)-ESes are
* performed in parallel, with interaction based on a niche radius (fixed so far).
* The number of peaks must be predefined, and lambda new samples are drawn for every peak in every iteration.
* Thus, in relation to the standard ES, some new parameters are due. On the other hand, the selection schemes
* are predefined. This is done according to Shir&Bäck, Niching in Evolution Strategies, Tec.Report 2005.
* The ES niching with dynamic peak identification. Basically, for a set of
* "peaks" a set of (mu,lambda)-ESes are performed in parallel, with interaction
* based on a niche radius (fixed so far). The number of peaks must be
* predefined, and lambda new samples are drawn for every peak in every
* iteration. Thus, in relation to the standard ES, some new parameters are due.
* On the other hand, the selection schemes are predefined. This is done
* according to Shir&Bäck, Niching in Evolution Strategies, Tec.Report 2005.
*
* Unfortunately the algorithm was not described in every detail. It remained unclear how exactly the
* peak population where filled and esp. what happens if DPI returns less than q peaks.
* In this implementation, this is solved by setting a maximum size to each peak cluster (muPerPeak). For
* a peak population, only the best muPerPeak remain and the rest is assigned to the unclustered set. From these,
* pseudo-peaks are then formed until the expected number of peak populations is produced.
* Unfortunately the algorithm was not described in every detail. It remained
* unclear how exactly the peak population where filled and esp. what happens if
* DPI returns less than q peaks. In this implementation, this is solved by
* setting a maximum size to each peak cluster (muPerPeak). For a peak
* population, only the best muPerPeak remain and the rest is assigned to the
* unclustered set. From these, pseudo-peaks are then formed until the expected
* number of peak populations is produced.
*
* Also, they gave a general rule for setting the niche radius depending on the problem domain, however in their
* experiments, they were able to identify optima which were much closer (i.e., on Ackley's), so it is unclear
* which niche radius was actually used there
* Also, they gave a general rule for setting the niche radius depending on the
* problem domain, however in their experiments, they were able to identify
* optima which were much closer (i.e., on Ackley's), so it is unclear which
* niche radius was actually used there
*
* Due to the "non-standard" environmental selection mechanism (a fixed proportion is chosen from the children, the
* rest from the parents), a preselection mechanism was implemented here, slightly breaking the ES framework
* which is still used to optimize the single peak populations.
* Due to the "non-standard" environmental selection mechanism (a fixed
* proportion is chosen from the children, the rest from the parents), a
* preselection mechanism was implemented here, slightly breaking the ES
* framework which is still used to optimize the single peak populations.
*
* This class should also cover "Dynamic niching in evolution strategies with covariance matrix adaptation"
* by Shir & Bäck, CEC 2005, when employing SelectBest as parent selection and muPerPeak=1.
* This class should also cover "Dynamic niching in evolution strategies with
* covariance matrix adaptation" by Shir & Bäck, CEC 2005, when employing
* SelectBest as parent selection and muPerPeak=1.
*
* Some notes:
*
* If strictNiching is deactivated, niches are disappearing because they are sometimes
* assigned the global opt. and in that niche are very bad so they get thrown away due to the maximum niche count
* if strictNiching is activated, niches are very small - or even empty. Why is that? This can hardly be sensible
* esp. with a very small niche radius for F8. This would mean that in the beginning, nearly all offspring
* are created from very few pairs of peaks.
* If strictNiching is deactivated, niches are disappearing because they are
* sometimes assigned the global opt. and in that niche are very bad so they get
* thrown away due to the maximum niche count if strictNiching is activated,
* niches are very small - or even empty. Why is that? This can hardly be
* sensible esp. with a very small niche radius for F8. This would mean that in
* the beginning, nearly all offspring are created from very few pairs of peaks.
*
* The mu/lambda information was lost on the way to the MutateESRankMuCMA class... I added it now as additional pop.data
* which is only loaded if the mu/lambda ratio deduced from the orig/selected population sizes does not make sense.
* The mu/lambda information was lost on the way to the MutateESRankMuCMA
* class... I added it now as additional pop.data which is only loaded if the
* mu/lambda ratio deduced from the orig/selected population sizes does not make
* sense.
*
* With the explorer peaks reinited every 100 generations or so, the course of the MPR for a *single* run
* will not be a clear logistic function, because "finding" additional peaks produces small steps in the MPR.
* With the explorer peaks reinited every 100 generations or so, the course of
* the MPR for a *single* run will not be a clear logistic function, because
* "finding" additional peaks produces small steps in the MPR.
*
* The Niching ES is now using the Population to catch the generational events, not producing it itself, similar
* to Tribes, ScatterSearch or IPOP-ES. Thus it could be used with a dynamic population size without too much
* hassle.
* The Niching ES is now using the Population to catch the generational events,
* not producing it itself, similar to Tribes, ScatterSearch or IPOP-ES. Thus it
* could be used with a dynamic population size without too much hassle.
*
* TODO
* Add adaptive niche radius. Add parameter to every indy which is adapted after all new peaks have been found.
* TODO Add adaptive niche radius. Add parameter to every indy which is adapted
* after all new peaks have been found.
*
*
* @author mkron
*
*/
public class EsDpiNiching implements InterfaceOptimizer, Serializable, InterfaceAdditionalPopulationInformer, InterfacePopulationChangedEventListener {
private static final boolean TRACE = false, TRACE_DEMES = false;
private double nicheRadius = 0.3;
private int expectedPeaks = 5;
@ -96,9 +108,7 @@ public class EsDpiNiching implements InterfaceOptimizer, Serializable, Interface
private boolean reinitAlreadyFound = true; // check if current species have converged to already archived solutions - if so, deactivate them
private transient Population archive = new Population(); // collect deactivated optima
protected ParameterControlManager paramControl = new ParameterControlManager();
private transient EvolutionStrategies[] peakOpts = null;
Population population = new Population();
private InterfaceOptimizationProblem problem;
private transient InterfacePopulationChangedEventListener m_Listener;
@ -119,14 +129,14 @@ public class EsDpiNiching implements InterfaceOptimizer, Serializable, Interface
private boolean doNumPeakAdaption = false;
private double collisionDetNicheRadius = 0.001; // distance below which collision between active species and archived solutios is assumed
private static final String origPeakIndyKey = "originalPeakIndividualKey";
public static final String originalPeakPop = "originalPeakPopulationID";
public EsDpiNiching() {
}
/**
* Use the given parameters, the maximal estimation for the niche radius, no preselection and no explorers.
* Use the given parameters, the maximal estimation for the niche radius, no
* preselection and no explorers.
*
* @param muPerPeak
* @param lambdaPerPeak
@ -151,8 +161,9 @@ public class EsDpiNiching implements InterfaceOptimizer, Serializable, Interface
}
/**
* If the niche radius is zero or negative, the automatic estimation is used. Otherwise the given radius is used.
* If etaPresel is positive, eta-preselection is activated, otherwise it is inactive.
* If the niche radius is zero or negative, the automatic estimation is
* used. Otherwise the given radius is used. If etaPresel is positive,
* eta-preselection is activated, otherwise it is inactive.
*
* @param nicheRadius
* @param muPerPeak
@ -168,7 +179,9 @@ public class EsDpiNiching implements InterfaceOptimizer, Serializable, Interface
if (nicheRadius > 0) {
setNicheRadius(nicheRadius);
setUseNicheRadiusEstimation(false);
} else setUseNicheRadiusEstimation(true);
} else {
setUseNicheRadiusEstimation(true);
}
this.eta = etaPresel;
this.muPerPeak = muPerPeak;
this.lambdaPerPeak = lambdaPerPeak;
@ -191,8 +204,12 @@ public class EsDpiNiching implements InterfaceOptimizer, Serializable, Interface
this.useNicheRadiusEstimation = o.useNicheRadiusEstimation;
this.setAllowSingularPeakPops(o.isAllowSingularPeakPops());
if (o.population!=null) this.population = (Population)o.population.clone();
if (o.problem!=null) this.problem = (InterfaceOptimizationProblem)o.problem.clone();
if (o.population != null) {
this.population = (Population) o.population.clone();
}
if (o.problem != null) {
this.problem = (InterfaceOptimizationProblem) o.problem.clone();
}
this.identifier = o.identifier;
this.plotInterval = o.plotInterval;
}
@ -247,21 +264,26 @@ public class EsDpiNiching implements InterfaceOptimizer, Serializable, Interface
population.addPopulationChangedEventListener(this);
population.setNotifyEvalInterval(50);
if (isUseNicheRadiusEstimation()) updateNicheRadius();
if (isUseNicheRadiusEstimation()) {
updateNicheRadius();
}
}
private void updateNicheRadius() {
AbstractEAIndividual indy = population.getEAIndividual(0);
if (indy instanceof InterfaceDataTypeDouble) {
setEstimatedNicheRadius(((InterfaceDataTypeDouble) indy).getDoubleRange());
} else System.err.println("Error, default niche radius can only be estimated for individuals of type InterfaceDataTypeDouble!");
} else {
System.err.println("Error, default niche radius can only be estimated for individuals of type InterfaceDataTypeDouble!");
}
}
/**
* Use the deactivation of converged species, storing them to an archive,
* with the given parameters. If windowLen <= 0, the deactivation
* mechanism is disabled.
* This provides for semi-sequential niching with DPI-ES
* with the given parameters. If windowLen <= 0, the deactivation mechanism
* is disabled. This provides for semi-sequential niching with DPI-ES
*
*
* @param threshold
* @param windowLen
@ -277,9 +299,9 @@ public class EsDpiNiching implements InterfaceOptimizer, Serializable, Interface
}
/**
* Calculate the estimated maximal niche radius for a given problem range. This
* is an estimate on the q-th part of the volume transfered to the radius of a hypersphere,
* where q is the number of expected peaks.
* Calculate the estimated maximal niche radius for a given problem range.
* This is an estimate on the q-th part of the volume transfered to the
* radius of a hypersphere, where q is the number of expected peaks.
*
* @param range
* @param numExpectedOptima
@ -293,8 +315,11 @@ public class EsDpiNiching implements InterfaceOptimizer, Serializable, Interface
r = Mathematics.getAvgRangeL2(range);
} else { //if (metric instanceof PhenotypeMetric) { // r can be assumed to be 0.5*sqrt(dim)
if (!(metric instanceof PhenotypeMetric)) {
if ((metric instanceof IndividualDataMetric) && (((IndividualDataMetric)metric).getBaseMetric() instanceof EuclideanMetric)) {} // this is ok as well
else System.err.println("Warning, unexpected metric in EsDpiNiching! Estimated niche radius may fail...");
if ((metric instanceof IndividualDataMetric) && (((IndividualDataMetric) metric).getBaseMetric() instanceof EuclideanMetric)) {
} // this is ok as well
else {
System.err.println("Warning, unexpected metric in EsDpiNiching! Estimated niche radius may fail...");
}
}
r = 0.5 * Math.sqrt(dim);
}
@ -307,12 +332,17 @@ public class EsDpiNiching implements InterfaceOptimizer, Serializable, Interface
// inc. expected peaks, allocate new optimizers, possibly adapt clustering distance
// this must happen to a specific time, namely before or after one iteration.
if (k<=0) System.err.println("Invalid k in addExpectedPeaks (" + k + ").");
if (k <= 0) {
System.err.println("Invalid k in addExpectedPeaks (" + k + ").");
}
setExpectedPeaks(getExpectedPeaks() + k);
EvolutionStrategies[] newPeakOpts = new EvolutionStrategies[getExpectedPeaks() + getExplorerPeaks()];
for (int i = 0; i < newPeakOpts.length; i++) { // allocate new peak optimizers
if (i<peakOpts.length) newPeakOpts[i]=peakOpts[i];
else newPeakOpts[i] = new EvolutionStrategies(peakOpts[0]);
if (i < peakOpts.length) {
newPeakOpts[i] = peakOpts[i];
} else {
newPeakOpts[i] = new EvolutionStrategies(peakOpts[0]);
}
}
peakOpts = newPeakOpts;
if (isUseNicheRadiusEstimation()) {
@ -325,15 +355,19 @@ public class EsDpiNiching implements InterfaceOptimizer, Serializable, Interface
// else return 0;
if (isDoNumPeakAdaption() && (archive.size() >= getExpectedPeaks())) {
return (int) Math.max(((double) getExpectedPeaks()) * 1.2, 2.);
} else return 0;
} else {
return 0;
}
}
public boolean isDoNumPeakAdaption() {
return doNumPeakAdaption;
}
public void setDoNumPeakAdaption(boolean doApt) {
doNumPeakAdaption = doApt;
}
public String doNumPeakAdaptionTipText() {
return "Activate online adaption of the number of expected peaks";
}
@ -343,15 +377,21 @@ public class EsDpiNiching implements InterfaceOptimizer, Serializable, Interface
if (increaseExpectedPeaksCriterion() > 0) {
addExpectedPeaks(increaseExpectedPeaksCriterion());
}
if (TRACE) System.out.println("--- FULL POP SIZE: " + population.size() + " , funcalls: " + population.getFunctionCalls() + ", gen " + population.getGeneration());
if (TRACE) {
System.out.println("--- FULL POP SIZE: " + population.size() + " , funcalls: " + population.getFunctionCalls() + ", gen " + population.getGeneration());
}
ClusteringDynPeakIdent dpiClustering = new ClusteringDynPeakIdent(getExpectedPeaks(), getLambdaPerPeak(), nicheRadius, true, metric);
// perform dynamic peak identification resulting in the dynamic peak set dps
dpiClustering.initClustering(population);
peakPopSet = dpiClustering.cluster(population, population);
// remove this instance as listener because we only want to "hear" events of the main population
for (int i=0; i<peakPopSet.length; i++) peakPopSet[i].removePopulationChangedEventListener(this);
for (int i = 0; i < peakPopSet.length; i++) {
peakPopSet[i].removePopulationChangedEventListener(this);
}
setGeneration(population.getGeneration(), peakPopSet);
if (TRACE_DEMES) printDemes("After clustering: ", peakPopSet);
if (TRACE_DEMES) {
printDemes("After clustering: ", peakPopSet);
}
int curNumPeaks = peakPopSet.length - 1;
@ -365,7 +405,9 @@ public class EsDpiNiching implements InterfaceOptimizer, Serializable, Interface
// }
int reqNewPeaks = 0;
if (curNumPeaks<getExpectedPeaks()) reqNewPeaks = getExpectedPeaks()-curNumPeaks; // not enough desired peaks were found
if (curNumPeaks < getExpectedPeaks()) {
reqNewPeaks = getExpectedPeaks() - curNumPeaks; // not enough desired peaks were found
}
if (getExplorerPeaks() > 0) {
if ((getPopulation().getGeneration() % resetExplorerInterval == 0)) {
// reset the explorers
@ -375,9 +417,12 @@ public class EsDpiNiching implements InterfaceOptimizer, Serializable, Interface
// TODO only if they have not made it to the desired peak populations?
Population[] clustersWithExplorers = new Population[peakPopSet.length + getExplorerPeaks()];
for (int i = 0; i < clustersWithExplorers.length; i++) {
if (i<peakPopSet.length) clustersWithExplorers[i]=peakPopSet[i];
// index i-1 because unclustered indies do not have an optimizer
else clustersWithExplorers[i] = peakOpts[i-1].getPopulation();
if (i < peakPopSet.length) {
clustersWithExplorers[i] = peakPopSet[i];
} // index i-1 because unclustered indies do not have an optimizer
else {
clustersWithExplorers[i] = peakOpts[i - 1].getPopulation();
}
}
peakPopSet = clustersWithExplorers;
}
@ -385,7 +430,9 @@ public class EsDpiNiching implements InterfaceOptimizer, Serializable, Interface
// add missing and explorer peaks as new random individuals (or old unclustered ones)
peakPopSet = generateMissingSpecies(peakPopSet, getMuPerPeak(), reqNewPeaks, false);
if (TRACE_DEMES) printDemes("After expansion: ", peakPopSet);
if (TRACE_DEMES) {
printDemes("After expansion: ", peakPopSet);
}
if (archive != null && (archive.size() > 0) && isReinitOnCollision()) {
double origNicheRad = dpiClustering.getNicheRadius();
@ -399,15 +446,20 @@ public class EsDpiNiching implements InterfaceOptimizer, Serializable, Interface
// the new found species is actually better than the archived solution
archive.set(i, peakPopSet[assoc[i]].getBestEAIndividual().clone()); // replace archived indy
}
if (TRACE) System.out.println(" Converged on archived solution.. resetting peak pop " + assoc[i]);
if (TRACE) {
System.out.println(" Converged on archived solution.. resetting peak pop " + assoc[i]);
}
peakPopSet[assoc[i]] = initRandomPeakPop(getMuPerPeak());
}
}
dpiClustering.setNicheRadius(origNicheRad);
if (TRACE_DEMES) printDemes("After archivie-merge: ", peakPopSet);
if (TRACE_DEMES) {
printDemes("After archivie-merge: ", peakPopSet);
}
}
if (TRACE) for (int k=0; k<peakPopSet.length-1; k++) {
if (TRACE) {
for (int k = 0; k < peakPopSet.length - 1; k++) {
for (int j = k + 1; j < peakPopSet.length; j++) {
Population cut = peakPopSet[k].setCut(peakPopSet[j]);
if (cut.size() > 0) {
@ -415,6 +467,7 @@ public class EsDpiNiching implements InterfaceOptimizer, Serializable, Interface
}
}
}
}
plot = null;
// now generate the lambda offsprings
// nextGeneration = this.generateEvalChildren(dps); // create lambda new ones from mu parents
@ -425,7 +478,9 @@ public class EsDpiNiching implements InterfaceOptimizer, Serializable, Interface
if (curSpecies.size() == 1 && (!isAllowSingularPeakPops())) {
// Quoting SB05: "In case that the niche only contains one individual, the second parent will be the best indidivual of another niche."
AbstractEAIndividual bestOther = (AbstractEAIndividual) selectBestFromOtherSpecies(clustIndex, peakPopSet).clone();
if (TRACE) System.out.println("Adding best from other species: " + bestOther);
if (TRACE) {
System.out.println("Adding best from other species: " + bestOther);
}
curSpecies.add(bestOther);
} else if (curSpecies.size() == 0) {
System.err.println("Warning, empty niche population in EsDpiNiching!");
@ -442,15 +497,21 @@ public class EsDpiNiching implements InterfaceOptimizer, Serializable, Interface
}
Population optimizedSpecies = peakOpts[clustIndex - 1].getPopulation();
if (doDraw(population.getGeneration())) drawPeakPop(""+clustIndex, curSpecies);
if (TRACE) System.out.println("Optimizing cluster index " + (clustIndex) + ", size " + curSpecies.size());
if (doDraw(population.getGeneration())) {
drawPeakPop("" + clustIndex, curSpecies);
}
if (TRACE) {
System.out.println("Optimizing cluster index " + (clustIndex) + ", size " + curSpecies.size());
}
peakOpts[clustIndex - 1].optimize(); // !!!!!!!! Actual optimization step
optimizedSpecies = peakOpts[clustIndex - 1].getPopulation();
optimizedSpecies.putData(origPeakIndyKey, curPeak);
population.incrFunctionCallsBy(optimizedSpecies.size());
// optimizedSpecies.incrGeneration(); // is already done in the .optimize() call above
// optimizedSpecies.incrFunctionCallsBy(optimizedSpecies.size());
if (TRACE) System.out.println(" ..." + optimizedSpecies.size() + " more funcalls... ");
if (TRACE) {
System.out.println(" ..." + optimizedSpecies.size() + " more funcalls... ");
}
}
@ -460,7 +521,8 @@ public class EsDpiNiching implements InterfaceOptimizer, Serializable, Interface
peakOpts[0].getPopulation().addPopulation(initRandomPeakPop(getMuPerPeak()));
}
if (TRACE) for (int k=0; k<peakPopSet.length-1; k++) {
if (TRACE) {
for (int k = 0; k < peakPopSet.length - 1; k++) {
for (int j = k + 1; j < peakPopSet.length; j++) {
Population cut = peakPopSet[k].setCut(peakPopSet[j]);
if (cut.size() > 1) {
@ -473,6 +535,7 @@ public class EsDpiNiching implements InterfaceOptimizer, Serializable, Interface
}
}
}
}
if (doEtaPreselection) { // this basically replaces ES-environment selection
// select the eta best from the offspring per peak population
// fill up to muPerPeak by adding from the old peak population
@ -485,7 +548,9 @@ public class EsDpiNiching implements InterfaceOptimizer, Serializable, Interface
System.err.println("Warning: fewer clusters than expected peaks in EsDpiNiching!");
offspring.clear(); // empty set to avoid duplicates!
} else {
if (TRACE) System.out.println("EtaPresel: from " + offspring.size() + " offspring selecting "+ eta);
if (TRACE) {
System.out.println("EtaPresel: from " + offspring.size() + " offspring selecting " + eta);
}
Population selected = selBest.selectFrom(offspring, eta);
if (!selected.isSubSet(offspring)) {
System.err.println("fatal problem in EsDpiNiching!!!");
@ -496,13 +561,17 @@ public class EsDpiNiching implements InterfaceOptimizer, Serializable, Interface
int delta = muPerPeak - eta;
if (delta > 0) {
Population filterPeakPop = peakPopSet[i + 1].filter(selected);
if (TRACE) System.out.println("Adding " + Math.min(delta, filterPeakPop.size()) + " from peak population.");
if (TRACE) {
System.out.println("Adding " + Math.min(delta, filterPeakPop.size()) + " from peak population.");
}
// (few) duplicates may happen because parents are copied to another peak population
// if a cluster had a size of 1 AND parents may survive due to elitism.
selected.addPopulation(selBest.selectFrom(filterPeakPop, Math.min(delta, filterPeakPop.size())), false);
if (selected.size() < muPerPeak && (addLonersToPeaks)) {
delta = Math.min(muPerPeak - selected.size(), loners.size());
if (TRACE) System.out.println("filling up with lucky loners: "+ delta);
if (TRACE) {
System.out.println("filling up with lucky loners: " + delta);
}
// fill up with loner indies
SelectRandom selRnd = new SelectRandom(false); // no duplicates wanted!
Population luckyLosers = selRnd.selectFrom(loners, delta);
@ -514,12 +583,18 @@ public class EsDpiNiching implements InterfaceOptimizer, Serializable, Interface
// selected.addAll(randomNewIndies);
}
}
if (TRACE) for (int k=0; k<i; k++) if (selected.setCut(peakOpts[k].getPopulation()).size()>2) { //one may happen after a cluster had size one (see above)
if (TRACE) {
for (int k = 0; k < i; k++) {
if (selected.setCut(peakOpts[k].getPopulation()).size() > 2) { //one may happen after a cluster had size one (see above)
System.err.println("Warning, nonempty set cut between " + k + " and " + i + " !");
}
peakOpts[i].m_Population.clear();
peakOpts[i].m_Population.addAll(selected);
if (doDraw(population.getGeneration())) drawPeakPop(""+i, selected);
}
}
peakOpts[i].population.clear();
peakOpts[i].population.addAll(selected);
if (doDraw(population.getGeneration())) {
drawPeakPop("" + i, selected);
}
}
}
}
@ -529,15 +604,15 @@ public class EsDpiNiching implements InterfaceOptimizer, Serializable, Interface
ClusterBasedNichingEA.plotIndy(plot, 'x', (InterfaceDataTypeDouble) archive.get(i));
}
}
if (getNumRndImmigrants()>0) generateEvalImmigrants(getNumRndImmigrants());
if (getNumRndImmigrants() > 0) {
generateEvalImmigrants(getNumRndImmigrants());
}
collectPopulationIncGen(population, peakOpts, randomNewIndies);
//this.firePropertyChangedEvent(Population.nextGenerationPerformed); // moved this to registerPopulationStateChanged which is called from the population
}
private Population deactivateSpecies(int clustIndex, boolean resetRandomly) {
Population optimizedSpecies = peakOpts[clustIndex - 1].getPopulation();
if (TRACE) System.out.println("Terminated species: " + clustIndex + ", optimizer " + (clustIndex-1));
if (TRACE) System.out.println(optimizedSpecies.getHistory());
convCount++;
// get best indy, add it to archive, clear population of the optimizer for a reset
archive.add(optimizedSpecies.getBestIndividual());
@ -564,7 +639,9 @@ public class EsDpiNiching implements InterfaceOptimizer, Serializable, Interface
clusteredPeakPops[i].SetHistory(origPop.getHistory()); // copy the history for deactivation!
// System.out.println("Copied hash for peak " + clusteredPeakPops[i].getBestEAIndividual() + ", cluster " + i + " from " + origEsPop);
} else { // ok in the first iteration of if the indy was a random immigrant
if (population.getGeneration()>1 && (getNumRndImmigrants()==0)) System.err.println("Error, empty original es pop ID!");
if (population.getGeneration() > 1 && (getNumRndImmigrants() == 0)) {
System.err.println("Error, empty original es pop ID!");
}
}
}
}
@ -593,7 +670,6 @@ public class EsDpiNiching implements InterfaceOptimizer, Serializable, Interface
// clusteredPeakPops[i].copyHashData(closestPop);
// }
// }
private void printDemes(String prefix, Population[] peakPops) {
System.out.print(prefix + " demes: ");
for (int i = 0; i < peakPops.length; i++) {
@ -609,7 +685,9 @@ public class EsDpiNiching implements InterfaceOptimizer, Serializable, Interface
System.out.println();
for (int i = 0; i < peakPops.length; i++) {
try {
if (peakPops[i].size()>0) System.out.print(format(peakPops[i].getBestEAIndividual().getFitness(0), 3, 3));
if (peakPops[i].size() > 0) {
System.out.print(format(peakPops[i].getBestEAIndividual().getFitness(0), 3, 3));
}
} catch (Exception e) {
System.err.println("NARG!");
}
@ -621,8 +699,11 @@ public class EsDpiNiching implements InterfaceOptimizer, Serializable, Interface
public static String format(double d, int len, int prec) {
StringBuffer sb = new StringBuffer();
Formatter fm = new Formatter(sb);
if (Math.abs(d)>1e6) fm.format("%"+prec+"."+len+"e ", d);
else fm.format("%"+prec+"."+len+"f ", d);
if (Math.abs(d) > 1e6) {
fm.format("%" + prec + "." + len + "e ", d);
} else {
fm.format("%" + prec + "." + len + "f ", d);
}
return sb.toString();
}
@ -633,19 +714,24 @@ public class EsDpiNiching implements InterfaceOptimizer, Serializable, Interface
}
/**
* Generate additional pseudo peak populations (species) by either moving unclustered ones
* or by creating new ones randomly. If unclustered indies are to be used, there must
* be enough of them available.
* The new peaks are appended to the given cluster list and returned (as a new array instance).
* Generate additional pseudo peak populations (species) by either moving
* unclustered ones or by creating new ones randomly. If unclustered indies
* are to be used, there must be enough of them available. The new peaks are
* appended to the given cluster list and returned (as a new array
* instance).
*
* @param origClusters the original clusters, where index 0 is the unclustered rest
* @param cntPerNewSpecies the number of indies to use per new peak population
* @param fromUnclusteredOrRandomly if true, use unclustered indies as new pops, otherwise create them randomly
* @param origClusters the original clusters, where index 0 is the
* unclustered rest
* @param cntPerNewSpecies the number of indies to use per new peak
* population
* @param fromUnclusteredOrRandomly if true, use unclustered indies as new
* pops, otherwise create them randomly
* @return
*/
private Population[] generateMissingSpecies(Population[] origClusters, int cntPerNewSpecies, int newPops, boolean fromUnclusteredOrRandomly) {
if (newPops==0) return origClusters;
else {
if (newPops == 0) {
return origClusters;
} else {
Population[] newClusters = new Population[origClusters.length + newPops];
if (fromUnclusteredOrRandomly) {
// int missingPeaks = newClusters.length-origClusters.length;
@ -657,16 +743,20 @@ public class EsDpiNiching implements InterfaceOptimizer, Serializable, Interface
newClusters[i] = initRandomPeakPop(cntPerNewSpecies);
}
}
for (int i=0; i<origClusters.length; i++) newClusters[i]=origClusters[i];
if (TRACE) System.out.println("Generated missing peak species...");
for (int i = 0; i < origClusters.length; i++) {
newClusters[i] = origClusters[i];
}
if (TRACE) {
System.out.println("Generated missing peak species...");
}
return newClusters;
}
}
/**
* Initialize a new peak population with the given number of indies,
* which are initialized randomly (using the problem instance) and assigned
* a maximally bad fitness.
* Initialize a new peak population with the given number of indies, which
* are initialized randomly (using the problem instance) and assigned a
* maximally bad fitness.
*
* @param cntPerNewSpecies
* @return
@ -689,37 +779,55 @@ public class EsDpiNiching implements InterfaceOptimizer, Serializable, Interface
problem.initPopulation(randomNewIndies);
problem.evaluate(randomNewIndies);
population.incrFunctionCallsBy(cnt);
if (TRACE) System.out.println("evaluated immigrants: " + randomNewIndies.size());
} else randomNewIndies = null;
if (TRACE) {
System.out.println("evaluated immigrants: " + randomNewIndies.size());
}
} else {
randomNewIndies = null;
}
}
/** Something has changed
/**
* Something has changed
*/
protected void firePropertyChangedEvent(String name) {
if (this.m_Listener != null) this.m_Listener.registerPopulationStateChanged(this, name);
if (this.m_Listener != null) {
this.m_Listener.registerPopulationStateChanged(this, name);
}
}
private AbstractEAIndividual selectBestFromOtherSpecies(int i, Population[] clusteredSpecies) {
// the index must be >0 and != i:
int rndIndex = RNG.randomInt(clusteredSpecies.length - 2);
if (rndIndex==0) rndIndex++;
if (rndIndex==i) rndIndex++;
if (TRACE) System.out.println("selected spec index " + rndIndex);
if (rndIndex == 0) {
rndIndex++;
}
if (rndIndex == i) {
rndIndex++;
}
if (TRACE) {
System.out.println("selected spec index " + rndIndex);
}
return clusteredSpecies[rndIndex].getBestEAIndividual();
}
private Population[] getOptPops() {
Population pops[] = new Population[peakOpts.length];
for (int i=0; i<peakOpts.length; i++) pops[i] = peakOpts[i].getPopulation();
for (int i = 0; i < peakOpts.length; i++) {
pops[i] = peakOpts[i].getPopulation();
}
return pops;
}
private void drawPeakPop(String prefix, Population npop) {
if (npop!=null && (npop.size()>0)) try {
if (npop != null && (npop.size() > 0)) {
try {
if (plot == null) {
plot = new TopoPlot("Niching-ES " + npop.getGeneration(), "x", "y");
plot.setParams(50, 50);
if (problem instanceof Interface2DBorderProblem) plot.setTopology((Interface2DBorderProblem)problem);
if (problem instanceof Interface2DBorderProblem) {
plot.setTopology((Interface2DBorderProblem) problem);
}
}
ClusterBasedNichingEA.plotPopConnected(plot, npop);
plot.drawIndividual(1, 0, "", npop.getBestEAIndividual());
@ -728,6 +836,7 @@ public class EsDpiNiching implements InterfaceOptimizer, Serializable, Interface
plot = null;
}
}
}
private boolean doDraw(int gen) {
return (plotInterval > 0) && ((gen % plotInterval) == 0);
@ -758,9 +867,9 @@ public class EsDpiNiching implements InterfaceOptimizer, Serializable, Interface
/**
* Perform mutation adaption for instances of InterfaceMutationGenerational.
* Specifically, the original population of each dps-member is cloned and the method
* adaptAfterSelection is called which may modify the population. The vector of these
* new populations is returned.
* Specifically, the original population of each dps-member is cloned and
* the method adaptAfterSelection is called which may modify the population.
* The vector of these new populations is returned.
*
* @param collectedPop
* @param dps
@ -789,6 +898,7 @@ public class EsDpiNiching implements InterfaceOptimizer, Serializable, Interface
/**
* Collect clones of the original populations for each peak.
*
* @param dps
* @param opts
* @return
@ -803,11 +913,10 @@ public class EsDpiNiching implements InterfaceOptimizer, Serializable, Interface
}
/**
* Update the collected population pop from the ESes. The function calls
* of one last iteration are added up, so this method is expected to be
* called exactly once per niching iteration.
* Immigrants are added as well - and the number of immigrants is added to the pop's
* function calls.
* Update the collected population pop from the ESes. The function calls of
* one last iteration are added up, so this method is expected to be called
* exactly once per niching iteration. Immigrants are added as well - and
* the number of immigrants is added to the pop's function calls.
*
* @param pop
* @param esses
@ -829,13 +938,15 @@ public class EsDpiNiching implements InterfaceOptimizer, Serializable, Interface
}
pop.incrGeneration();
pop.synchSize();
if (TRACE) System.out.println("Collected " + pop.size() + " indies in pop.");
if (TRACE) {
System.out.println("Collected " + pop.size() + " indies in pop.");
}
}
/**
* Calculate the dynamic population size, which is the number of individuals that
* are currently "alive" in the peak set.
* This must be implemented in analogy to {@link #collectPopulationIncGen(Population, EvolutionStrategies[], Population)}
* Calculate the dynamic population size, which is the number of individuals
* that are currently "alive" in the peak set. This must be implemented in
* analogy to {@link #collectPopulationIncGen(Population, EvolutionStrategies[], Population)}
*
* @return
*/
@ -854,9 +965,11 @@ public class EsDpiNiching implements InterfaceOptimizer, Serializable, Interface
public double getNicheRadius() {
return nicheRadius;
}
public void setNicheRadius(double nicheRadius) {
this.nicheRadius = nicheRadius;
}
public String nicheRadiusTipText() {
return "The niche radius to be used.";
}
@ -864,9 +977,11 @@ public class EsDpiNiching implements InterfaceOptimizer, Serializable, Interface
public int getLambdaPerPeak() {
return lambdaPerPeak;
}
public void setLambdaPerPeak(int lambdaPP) {
lambdaPerPeak = lambdaPP;
}
public String lambdaPerPeakTipText() {
return "The number of descendants created for each peak.";
}
@ -874,10 +989,15 @@ public class EsDpiNiching implements InterfaceOptimizer, Serializable, Interface
public int getExpectedPeaks() {
return expectedPeaks;
}
public void setExpectedPeaks(int ep) {
if (ep>0) expectedPeaks = ep;
else System.err.println("Error, expecting positive number of peaks!");
if (ep > 0) {
expectedPeaks = ep;
} else {
System.err.println("Error, expecting positive number of peaks!");
}
}
public String expectedPeaksTipText() {
return "The number of expected peaks on the problem.";
}
@ -885,10 +1005,15 @@ public class EsDpiNiching implements InterfaceOptimizer, Serializable, Interface
public int getExplorerPeaks() {
return explorerPeaks;
}
public void setExplorerPeaks(int ep) {
if (ep>=0) explorerPeaks = ep;
else System.err.println("Error, expecting nonzero number of explorer peaks!");
if (ep >= 0) {
explorerPeaks = ep;
} else {
System.err.println("Error, expecting nonzero number of explorer peaks!");
}
}
public String explorerPeaksTipText() {
return "The number of additional explorer peaks.";
}
@ -898,29 +1023,37 @@ public class EsDpiNiching implements InterfaceOptimizer, Serializable, Interface
}
public static String globalInfo() {
return "A niching ES with dynamic peak identification, after Shir and Bäck: Niching in Evolution Strategies, " +
"GECCO 2005. Basically, there are several variants of a (mu,lambda)-ES performed " +
"in parallel, which are reclustered in each iteration based on the dynamic peak set.";
return "A niching ES with dynamic peak identification, after Shir and Bäck: Niching in Evolution Strategies, "
+ "GECCO 2005. Basically, there are several variants of a (mu,lambda)-ES performed "
+ "in parallel, which are reclustered in each iteration based on the dynamic peak set.";
}
public void addPopulationChangedEventListener(
InterfacePopulationChangedEventListener ea) {
m_Listener = ea;
}
public boolean removePopulationChangedEventListener(
InterfacePopulationChangedEventListener ea) {
if (ea.equals(m_Listener)) {
m_Listener = null;
return true;
} else return false;
} else {
return false;
}
}
public void freeWilly() {}
public void freeWilly() {
}
public InterfaceSolutionSet getAllSolutions() {
Population peaks = new Population(peakOpts.length);
for (int i=0; i<peakOpts.length; i++) peaks.add(peakOpts[i].getPopulation().getBestEAIndividual());
if (archive!=null) peaks.addPopulation(archive); // add stored indies
for (int i = 0; i < peakOpts.length; i++) {
peaks.add(peakOpts[i].getPopulation().getBestEAIndividual());
}
if (archive != null) {
peaks.addPopulation(archive); // add stored indies
}
peaks.synchSize();
return new SolutionSet(getPopulation(), peaks);
}
@ -928,6 +1061,7 @@ public class EsDpiNiching implements InterfaceOptimizer, Serializable, Interface
public String getIdentifier() {
return identifier;
}
public void SetIdentifier(String name) {
identifier = name;
}
@ -936,6 +1070,7 @@ public class EsDpiNiching implements InterfaceOptimizer, Serializable, Interface
// this might cause problems if the pop.size() does not fit the EsDpiNiching parameters mu/lamba per peak
this.population = pop;
}
public Population getPopulation() {
return population;
}
@ -943,6 +1078,7 @@ public class EsDpiNiching implements InterfaceOptimizer, Serializable, Interface
public InterfaceOptimizationProblem getProblem() {
return problem;
}
public void SetProblem(InterfaceOptimizationProblem prob) {
this.problem = prob;
}
@ -969,9 +1105,11 @@ public class EsDpiNiching implements InterfaceOptimizer, Serializable, Interface
public int getPlotInterval() {
return plotInterval;
}
public void setPlotInterval(int plotInterval) {
this.plotInterval = plotInterval;
}
public String plotIntervalTipText() {
return "If > 0, show debug visualization at indicated iterations.";
}
@ -979,9 +1117,11 @@ public class EsDpiNiching implements InterfaceOptimizer, Serializable, Interface
public int getEta() {
return eta;
}
public void setEta(int eta) {
this.eta = eta;
}
public String etaTipText() {
return "The number of offspring individuals per peak which will be preselected.";
}
@ -989,10 +1129,12 @@ public class EsDpiNiching implements InterfaceOptimizer, Serializable, Interface
public boolean isDoEtaPreselection() {
return doEtaPreselection;
}
public void setDoEtaPreselection(boolean doEtaPreselection) {
this.doEtaPreselection = doEtaPreselection;
GenericObjectEditor.setShowProperty(this.getClass(), "eta", doEtaPreselection);
}
public String doEtaPreselectionTipText() {
return "Replace ES environmental selection by choosing some individuals from the offspring within a niche and some from the former niche population.";
}
@ -1000,9 +1142,11 @@ public class EsDpiNiching implements InterfaceOptimizer, Serializable, Interface
public void setNumRndImmigrants(int numRndImmigrants) {
this.numRndImmigrants = numRndImmigrants;
}
public int getNumRndImmigrants() {
return numRndImmigrants;
}
public String numRndImmigrantsTipText() {
return "A number of individuals will be randomly created in every iteration.";
}
@ -1010,9 +1154,11 @@ public class EsDpiNiching implements InterfaceOptimizer, Serializable, Interface
public int getMuPerPeak() {
return muPerPeak;
}
public void setMuPerPeak(int muPerPeak) {
this.muPerPeak = muPerPeak;
}
public String muPerPeakTipText() {
return "Number of parent individuals per niche.";
}
@ -1021,9 +1167,11 @@ public class EsDpiNiching implements InterfaceOptimizer, Serializable, Interface
this.useNicheRadiusEstimation = useNicheRadiusEstimation;
GenericObjectEditor.setHideProperty(this.getClass(), "nicheRadius", useNicheRadiusEstimation);
}
public boolean isUseNicheRadiusEstimation() {
return useNicheRadiusEstimation;
}
public String useNicheRadiusEstimationTipText() {
return "Activate to use a niche radius corresponding to the q-th part of the search space (q number of peaks expected) - often niche radii should be smaller since this is close to the upper bound.";
}
@ -1031,9 +1179,11 @@ public class EsDpiNiching implements InterfaceOptimizer, Serializable, Interface
public InterfaceSelection getParentSelection() {
return parentSel;
}
public void setParentSelection(InterfaceSelection parentSel) {
this.parentSel = parentSel;
}
public String parentSelectionTipText() {
return "Set the parent selection method for the underlying ES.";
}
@ -1041,9 +1191,11 @@ public class EsDpiNiching implements InterfaceOptimizer, Serializable, Interface
public void setAllowSingularPeakPops(boolean allowSingularPeakPops) {
this.allowSingularPeakPops = allowSingularPeakPops;
}
public boolean isAllowSingularPeakPops() {
return allowSingularPeakPops;
}
public String allowSingularPeakPopsTipText() {
return "Allow peak populations of size 1 or force a randomly selected other peak as second indy.";
}
@ -1051,10 +1203,15 @@ public class EsDpiNiching implements InterfaceOptimizer, Serializable, Interface
public int getResetExplorerInterval() {
return resetExplorerInterval;
}
public void setResetExplorerInterval(int resInt) {
if (resInt>0) this.resetExplorerInterval = resInt;
else System.err.println("The explorer reset interval should be positive!");
if (resInt > 0) {
this.resetExplorerInterval = resInt;
} else {
System.err.println("The explorer reset interval should be positive!");
}
}
public String resetExplorerIntervalTipText() {
return "The explorer peaks are reset in intervals of iterations (generations).";
}
@ -1062,9 +1219,11 @@ public class EsDpiNiching implements InterfaceOptimizer, Serializable, Interface
public int getHaltingWindow() {
return haltingWindowLen;
}
public void setHaltingWindow(int hw) {
haltingWindowLen = hw;
}
public String haltingWindowTipText() {
return "Number of generations after which a species without improvement is seen as converged and deactivated; set to zero to disable.";
}
@ -1072,9 +1231,11 @@ public class EsDpiNiching implements InterfaceOptimizer, Serializable, Interface
public double getEpsilonBound() {
return deactConvThresh;
}
public void setEpsilonBound(double epsilonBound) {
this.deactConvThresh = epsilonBound;
}
public String epsilonBoundTipText() {
return "If fitness std. dev. changes less than this value within the halting window, convergence is assumed.";
}
@ -1095,6 +1256,7 @@ public class EsDpiNiching implements InterfaceOptimizer, Serializable, Interface
/**
* This method is necessary to allow access from the Processor.
*
* @return
*/
public ParameterControlManager getParamControl() {
@ -1104,9 +1266,11 @@ public class EsDpiNiching implements InterfaceOptimizer, Serializable, Interface
public ParamAdaption[] getParameterControl() {
return paramControl.getSingleAdapters();
}
public void setParameterControl(ParamAdaption[] paramControl) {
this.paramControl.setSingleAdapters(paramControl);
}
public String parameterControlTipText() {
return "You may define dynamic paramter control strategies using the parameter name.";
}
@ -1114,9 +1278,11 @@ public class EsDpiNiching implements InterfaceOptimizer, Serializable, Interface
public void setReinitOnCollision(boolean reinitAlreadyFound) {
this.reinitAlreadyFound = reinitAlreadyFound;
}
public boolean isReinitOnCollision() {
return reinitAlreadyFound;
}
public String reinitOnCollisionTipText() {
return "Indicate whether already known (archived) peaks should trigger a reset of close-by species (corresp. to niche radius).";
}

View File

@ -27,31 +27,26 @@ import eva2.server.go.problems.InterfaceOptimizationProblem;
* $Date: 2007-12-04 14:31:47 +0100 (Tue, 04 Dec 2007) $
* $Author: mkron $
*/
public class EvolutionStrategies implements InterfaceOptimizer, java.io.Serializable {
//private double m_MyuRatio = 6;
protected int m_Mu = 5;
protected int m_Lambda = 20;
protected boolean m_UsePlusStrategy = false;
protected Population m_Population = new Population();
protected InterfaceOptimizationProblem m_Problem = new B1Problem();
private InterfaceSelection m_ParentSelection = new SelectRandom();
private InterfaceSelection m_PartnerSelection = new SelectRandom();
private InterfaceSelection m_EnvironmentSelection = new SelectBestIndividuals();
private int m_NumberOfPartners = 1;
protected int mu = 5;
protected int lambda = 20;
protected boolean usePlusStrategy = false;
protected Population population = new Population();
protected InterfaceOptimizationProblem optimizationProblem = new B1Problem();
private InterfaceSelection parentSelection = new SelectRandom();
private InterfaceSelection partnerSelection = new SelectRandom();
private InterfaceSelection environmentSelection = new SelectBestIndividuals();
private int numberOfPartners = 1;
protected int origPopSize = -1; // especially for CBN
// private double[] m_FitnessOfParents = null;
private boolean forceOrigPopSize = true;// especially for CBN
transient private String m_Identifier = "";
transient private InterfacePopulationChangedEventListener m_Listener;
private static final boolean TRACE = false;
transient private String identifier = "";
transient private InterfacePopulationChangedEventListener changeListener;
public static final String esMuParam = "EvolutionStrategyMuParameter";
public static final String esLambdaParam = "EvolutionStrategyLambdaParameter";
public EvolutionStrategies() {
this.m_Population.setTargetSize(this.m_Lambda);
this.population.setTargetSize(this.lambda);
}
public EvolutionStrategies(int mu, int lambda, boolean usePlus) {
@ -61,23 +56,25 @@ public class EvolutionStrategies implements InterfaceOptimizer, java.io.Serializ
this.checkPopulationConstraints();
}
public EvolutionStrategies(EvolutionStrategies a) {
this.m_Mu = a.m_Mu;
this.m_Lambda = a.m_Lambda;
this.m_UsePlusStrategy = a.m_UsePlusStrategy;
this.m_Population = (Population)a.m_Population.clone();
this.m_Problem = (InterfaceOptimizationProblem)a.m_Problem.clone();
this.m_NumberOfPartners = a.m_NumberOfPartners;
this.m_ParentSelection = (InterfaceSelection)a.m_ParentSelection.clone();
this.m_PartnerSelection = (InterfaceSelection)a.m_PartnerSelection.clone();
this.m_EnvironmentSelection = (InterfaceSelection)a.m_EnvironmentSelection.clone();
this.m_NumberOfPartners = a.m_NumberOfPartners;
this.origPopSize = a.origPopSize;
this.forceOrigPopSize = a.forceOrigPopSize;
public EvolutionStrategies(EvolutionStrategies evStrategies) {
this.mu = evStrategies.mu;
this.lambda = evStrategies.lambda;
this.usePlusStrategy = evStrategies.usePlusStrategy;
this.population = (Population) evStrategies.population.clone();
this.optimizationProblem = (InterfaceOptimizationProblem) evStrategies.optimizationProblem.clone();
this.numberOfPartners = evStrategies.numberOfPartners;
this.parentSelection = (InterfaceSelection) evStrategies.parentSelection.clone();
this.partnerSelection = (InterfaceSelection) evStrategies.partnerSelection.clone();
this.environmentSelection = (InterfaceSelection) evStrategies.environmentSelection.clone();
this.numberOfPartners = evStrategies.numberOfPartners;
this.origPopSize = evStrategies.origPopSize;
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
*/
public void setForceOrigPopSize(boolean force) {
@ -93,91 +90,68 @@ public class EvolutionStrategies implements InterfaceOptimizer, java.io.Serializ
}
public void init() {
// @todo In case of CBN-ES i need to read the population size!?
// int orgPopSize = this.m_Population.getPopulationSize();
// if (this.m_InitialPopulationSize > orgPopSize) {
// this.m_Population.setPopulationSize(this.m_InitialPopulationSize);
// }
//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
population.putData(esMuParam, getMu());
population.putData(esLambdaParam, getLambda());
this.optimizationProblem.initPopulation(this.population);
this.evaluatePopulation(this.population);
}
/** 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.
*/
public void initByPopulation(Population pop, boolean reset) {
origPopSize = pop.getTargetSize();
// System.out.println("ES: orig popsize is " + origPopSize);
this.m_Population = (Population)pop.clone();
this.population = (Population) pop.clone();
if (reset) {
this.m_Population.init();
this.evaluatePopulation(this.m_Population);
// this.firePropertyChangedEvent(Population.nextGenerationPerformed); // not necessary if incrGeneration is called
this.population.init();
this.evaluatePopulation(this.population);
}
}
/** 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
*/
protected void evaluatePopulation(Population population) {
this.m_Problem.evaluate(population);
this.optimizationProblem.evaluate(population);
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
* given population of evaluated individuals.
* This method will generate the offspring population from the given
* population of evaluated individuals.
*/
protected Population generateEvalChildren(Population fromPopulation) {
Population result = m_Population.cloneWithoutInds(), parents;
Population result = population.cloneWithoutInds(), parents;
result.clear();
parents = generateChildren(fromPopulation, result, this.m_Lambda);
parents = generateChildren(fromPopulation, result, this.lambda);
this.evaluatePopulation(result);
if (result.getEAIndividual(0).getMutationOperator() instanceof InterfaceAdaptOperatorGenerational) {
// this seems to be the right moment for the 1/5-success rule
// 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) {
((InterfaceAdaptOperatorGenerational)parents.getEAIndividual(0).getCrossoverOperator()).adaptGenerational(fromPopulation, parents, result, m_UsePlusStrategy);
((InterfaceAdaptOperatorGenerational) parents.getEAIndividual(0).getCrossoverOperator()).adaptGenerational(fromPopulation, parents, result, usePlusStrategy);
}
return result;
}
/**
* Create a new population by parent selection, partner selection, recombination and crossover.
* The new population is added to the result population, while the selected parent population (after
* selection but before recombination/crossover) is returned.
* Returned parents and result population are to have the same size and correspond per individual.
* Create a new population by parent selection, partner selection,
* recombination and crossover. The new population is added to the result
* population, while the selected parent population (after selection but
* before recombination/crossover) is returned. Returned parents and result
* population are to have the same size and correspond per individual.
*
* @param fromPopulation
* @param result
@ -188,14 +162,13 @@ public class EvolutionStrategies implements InterfaceOptimizer, java.io.Serializ
AbstractEAIndividual tmpIndy;
AbstractEAIndividual[] offSprings;
Population parents;
if (TRACE ) System.out.println("ES From pop size " + fromPopulation.size() + " selecting parents/creating children: " + lambda);
this.m_ParentSelection.prepareSelection(fromPopulation);
this.m_PartnerSelection.prepareSelection(fromPopulation);
parents = this.m_ParentSelection.selectFrom(fromPopulation, lambda);
this.parentSelection.prepareSelection(fromPopulation);
this.partnerSelection.prepareSelection(fromPopulation);
parents = this.parentSelection.selectFrom(fromPopulation, lambda);
for (int i = 0; i < parents.size(); 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();
result.add(i, offSprings[0]);
}
@ -203,25 +176,21 @@ public class EvolutionStrategies implements InterfaceOptimizer, java.io.Serializ
}
protected Population selectParents(Population fromPop, int mu) {
if (TRACE) System.out.println("ES env selecting parents: " + mu + " of " + fromPop.size());
this.m_EnvironmentSelection.prepareSelection(fromPop);
return this.m_EnvironmentSelection.selectFrom(fromPop, mu);
this.environmentSelection.prepareSelection(fromPop);
return this.environmentSelection.selectFrom(fromPop, mu);
}
/**
* The optimize method will compute an improved and evaluated population.
*/
@Override
public void optimize() {
Population nextGeneration, parents;
//System.out.println("optimize");
// 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()));
// m_Population / parents are of sizes lambda / mu
// population / parents are of sizes lambda / mu
if (parents.getEAIndividual(0).getMutationOperator() instanceof InterfaceAdaptOperatorGenerational) {
((InterfaceAdaptOperatorGenerational) parents.getEAIndividual(0).getMutationOperator()).adaptAfterSelection(getPopulation(), parents);
}
@ -230,20 +199,22 @@ public class EvolutionStrategies implements InterfaceOptimizer, java.io.Serializ
}
// 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));
// 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.
* However, in case of CBN this method prepares the next generation according to the species size.
* Usually, this just returns the given population. However, in case of CBN
* this method prepares the next generation according to the species size.
*
* @param nextGeneration
* @return
@ -251,11 +222,10 @@ public class EvolutionStrategies implements InterfaceOptimizer, java.io.Serializ
protected Population getReplacePop(Population nextGeneration) {
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.m_EnvironmentSelection.prepareSelection(nextGeneration);
this.environmentSelection.prepareSelection(nextGeneration);
Population tmpPop = (Population) nextGeneration.clone();
nextGeneration.clear();
nextGeneration.addPopulation(this.m_EnvironmentSelection.selectFrom(tmpPop, origPopSize));
// System.out.println("ES post selection! " + origPopSize + " from " + tmpPop.size());
nextGeneration.addPopulation(this.environmentSelection.selectFrom(tmpPop, origPopSize));
} else {
if ((origPopSize > 0) && (origPopSize != nextGeneration.size())) {
System.err.println("Warning in ES! orig: " + origPopSize + " / " + nextGeneration.size());
@ -264,147 +234,117 @@ public class EvolutionStrategies implements InterfaceOptimizer, java.io.Serializ
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 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
/**
* This method allows you to add the LectureGUI as listener to the Optimizer
*
* @param ea
*/
@Override
public void addPopulationChangedEventListener(InterfacePopulationChangedEventListener ea) {
this.m_Listener = ea;
}
public boolean removePopulationChangedEventListener(
InterfacePopulationChangedEventListener ea) {
if (m_Listener==ea) {
m_Listener=null;
return true;
} else return false;
}
/** Something has changed
*/
protected void firePropertyChangedEvent(String name) {
if (this.m_Listener != null) this.m_Listener.registerPopulationStateChanged(this, name);
this.changeListener = ea;
}
/** This method will set the problem that is to be optimized
@Override
public boolean removePopulationChangedEventListener(InterfacePopulationChangedEventListener ea) {
if (changeListener == ea) {
changeListener = null;
return true;
} else {
return false;
}
}
/**
* Something has changed
*/
protected void firePropertyChangedEvent(String name) {
if (this.changeListener != null) {
this.changeListener.registerPopulationStateChanged(this, name);
}
}
/**
* This method will set the problem that is to be optimized
*
* @param problem
*/
public void SetProblem(InterfaceOptimizationProblem problem) {
this.m_Problem = problem;
}
public InterfaceOptimizationProblem getProblem () {
return this.m_Problem;
this.optimizationProblem = problem;
}
/** This method will return a string describing all properties of the optimizer
* and the applied methods.
public InterfaceOptimizationProblem getProblem() {
return this.optimizationProblem;
}
/**
* This method will return a string describing all properties of the
* optimizer and the applied methods.
*
* @return A descriptive string
*/
public String getStringRepresentation() {
String result = "";
result += "Evolution Strategies:\n";
result += "Optimization Problem: ";
result += this.m_Problem.getStringRepresentationForProblem(this) +"\n";
result += this.m_Population.getStringRepresentation();
result += this.optimizationProblem.getStringRepresentationForProblem(this) + "\n";
result += this.population.getStringRepresentation();
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 lambda
* @param plus True if plus, false if comma strategy
*/
public void setGenerationStrategy(int myu, int lambda, boolean plus) {
this.m_Mu = myu;
this.m_Lambda = lambda;
this.m_UsePlusStrategy = plus;
this.mu = myu;
this.lambda = lambda;
this.usePlusStrategy = plus;
this.checkPopulationConstraints();
}
/**
* This method will check the population constraints
* myu <= lambda and will calculate the population size
* accordingly.
* This method will check the population constraints myu <= lambda and will
* calculate the population size accordingly.
*/
protected void checkPopulationConstraints() {
if (this.m_Lambda < this.m_Mu) {
System.err.println("Invalid mu/lambda ratio! Setting mu=lambda="+m_Mu);
this.m_Lambda = this.m_Mu;
if (this.lambda < this.mu) {
System.err.println("Invalid mu/lambda ratio! Setting mu=lambda=" + mu);
this.lambda = this.mu;
}
// if (this.m_UsePlusStrategy) this.m_Population.setTargetSize(this.m_Mu + this.m_Lambda);
// else this.m_Population.setTargetSize(this.m_Lambda);
this.m_Population.setTargetSize(this.m_Lambda);
origPopSize=m_Population.getTargetSize();
this.population.setTargetSize(this.lambda);
origPopSize = population.getTargetSize();
}
/** This method allows you to set an identifier for the algorithm
/**
* This method allows you to set an identifier for the algorithm
*
* @param name The indenifier
*/
public void SetIdentifier(String name) {
this.m_Identifier = name;
}
public String getIdentifier() {
return this.m_Identifier;
this.identifier = name;
}
/** This method is required to free the memory on a RMIServer,
* but there is nothing to implement.
public String getIdentifier() {
return this.identifier;
}
/**
* This method is required to free the memory on a RMIServer, but there is
* nothing to implement.
*/
public void freeWilly() {
}
/**********************************************************************************************************************
/**
* These are for GUI
*/
/** This method returns a global info string
/**
* This method returns a global info string
*
* @return description
*/
public static String globalInfo() {
@ -415,7 +355,9 @@ public class EvolutionStrategies implements InterfaceOptimizer, java.io.Serializ
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
*/
public String getName() {
@ -423,27 +365,26 @@ public class EvolutionStrategies implements InterfaceOptimizer, java.io.Serializ
}
/**
* Assuming that all optimizer will store their data in a population
* we will allow access to this population to query to current state
* of the optimizer.
* Assuming that all optimizer will store their data in a population we will
* allow access to this population to query to current state of the
* optimizer.
*
* @return The population of current solutions to a given problem.
*/
public Population getPopulation() {
return this.m_Population;
return this.population;
}
// for internal usage
protected void setPop(Population pop) {
if (TRACE) System.out.println("ES Setting pop of " + pop.size());
m_Population = pop;
this.population = pop;
}
public void setPopulation(Population pop) {
if (TRACE) System.out.println("ES Setting pop of " + pop.size());
origPopSize = pop.size();
// System.err.println("In ES: orig popsize is " + origPopSize);
this.m_Population = pop;
this.population = pop;
}
public String populationTipText() {
return "Edit the properties of the population used.";
}
@ -451,138 +392,128 @@ public class EvolutionStrategies implements InterfaceOptimizer, java.io.Serializ
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
/**
* This method will set the selection method that is to be used
*
* @param selection
*/
public void setEnvironmentSelection(InterfaceSelection selection) {
this.m_EnvironmentSelection = selection;
this.environmentSelection = selection;
}
public InterfaceSelection getEnvironmentSelection() {
return this.m_EnvironmentSelection;
return this.environmentSelection;
}
public String environmentSelectionTipText() {
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
*/
public void setPartnerSelection(InterfaceSelection selection) {
this.m_PartnerSelection = selection;
this.partnerSelection = selection;
}
public InterfaceSelection getPartnerSelection() {
return this.m_PartnerSelection;
return this.partnerSelection;
}
public String partnerSelectionTipText() {
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
*/
public void setParentSelection(InterfaceSelection selection) {
this.m_ParentSelection = selection;
this.parentSelection = selection;
}
public InterfaceSelection getParentSelection() {
return this.m_ParentSelection;
return this.parentSelection;
}
public String parentSelectionTipText() {
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
*/
public void setPlusStrategy(boolean elitism) {
this.m_UsePlusStrategy = elitism;
// this.checkPopulationConstraints(); // do this on init only
this.usePlusStrategy = elitism;
}
public boolean isPlusStrategy() {
return this.m_UsePlusStrategy;
return this.usePlusStrategy;
}
public String plusStrategyTipText() {
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
*
* @param partners
*/
public void setNumberOfPartners(int partners) {
if (partners < 0) partners = 0;
this.m_NumberOfPartners = partners;
if (partners < 0) {
partners = 0;
}
this.numberOfPartners = partners;
}
public int getNumberOfPartners() {
return this.m_NumberOfPartners;
return this.numberOfPartners;
}
public String numberOfPartnersTipText() {
return "The number of mating partners needed to create offsprings.";
}
// /** This method will set the ratio between myu and lambda
// * @param lambdaratio
// */
// public void setLambdaRatio(int lambdaratio) {
// 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
/**
* This method allows you to set parent population size myu
*
* @param myu The parent population size.
*/
public void setMu(int mu) {
this.m_Mu = mu;
// this.checkPopulationConstraints(); // do this on init only
this.mu = mu;
}
public int getMu() {
return this.m_Mu;
return this.mu;
}
public String muTipText() {
return "This is the parent population size.";
}
/** This is the children population size lambda
/**
* This is the children population size lambda
*
* @param lambda The children population size.
*/
public void setLambda(int lambda) {
this.m_Lambda = lambda;
// this.checkPopulationConstraints(); // do this on init only
this.lambda = lambda;
}
public int getLambda() {
return this.m_Lambda;
return this.lambda;
}
public String lambdaTipText() {
return "This is the children population size.";
}

View File

@ -1,18 +1,8 @@
package eva2.server.modules;
import eva2.EvAInfo;
import java.util.List;
import java.util.Vector;
import javax.swing.JOptionPane;
import eva2.gui.BeanInspector;
import eva2.server.go.InterfaceGOParameters;
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.*;
import eva2.server.go.operators.paramcontrol.ConstantParameters;
import eva2.server.go.operators.paramcontrol.InterfaceParameterControl;
import eva2.server.go.operators.postprocess.PostProcess;
@ -32,8 +22,11 @@ import eva2.tools.EVAHELP;
import eva2.tools.StringTools;
import eva2.tools.jproxy.RemoteStateListener;
import eva2.tools.math.RNG;
import java.util.ArrayList;
import java.util.List;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.JOptionPane;
/**
* 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() {
Vector<InterfaceAdditionalPopulationInformer> informerList = new Vector<InterfaceAdditionalPopulationInformer>(2);
List<InterfaceAdditionalPopulationInformer> informerList = new ArrayList<InterfaceAdditionalPopulationInformer>(2);
informerList.add(this.goParams.getProblem());
if (this.goParams.getOptimizer() instanceof InterfaceAdditionalPopulationInformer) {
informerList.add((InterfaceAdditionalPopulationInformer) this.goParams.getOptimizer());