Last RMI occurences have been removed. Free Willy is officially dead. Hooray!

Also, code formatting :)
This commit is contained in:
2013-01-31 13:42:59 +00:00
parent b0ab7aba0c
commit d474eebfa2
35 changed files with 10532 additions and 10157 deletions

View File

@@ -772,15 +772,15 @@ public class EvAClient extends JFrame implements OptimizationStateListener {
menuBar = new JMenuBar(); menuBar = new JMenuBar();
setJMenuBar(menuBar); setJMenuBar(menuBar);
menuModule = new JExtMenu("&Module"); menuModule = new JExtMenu("&Module");
menuModule.add(actModuleLoad); //menuModule.add(actModuleLoad);
menuSelHosts = new JExtMenu("&Select Hosts"); menuSelHosts = new JExtMenu("&Select Hosts");
menuSelHosts.setToolTipText("Select a host for the server application"); //menuSelHosts.setToolTipText("Select a host for the server application");
menuSelHosts.add(actHost); //menuSelHosts.add(actHost);
menuSelHosts.add(actAvailableHost); //menuSelHosts.add(actAvailableHost);
menuSelHosts.addSeparator(); //menuSelHosts.addSeparator();
menuSelHosts.add(actKillHost); //menuSelHosts.add(actKillHost);
menuSelHosts.add(actKillAllHosts); //menuSelHosts.add(actKillAllHosts);
menuHelp = new JExtMenu("&Help"); menuHelp = new JExtMenu("&Help");
menuHelp.add(actHelp); menuHelp.add(actHelp);
@@ -790,13 +790,13 @@ public class EvAClient extends JFrame implements OptimizationStateListener {
menuOptions = new JExtMenu("&Options"); menuOptions = new JExtMenu("&Options");
menuOptions.add(actPreferences); menuOptions.add(actPreferences);
menuOptions.add(menuSelHosts); //menuOptions.add(menuSelHosts);
menuOptions.addSeparator(); menuOptions.addSeparator();
menuOptions.add(actQuit); menuOptions.add(actQuit);
// this is accessible if no default module is given // this is accessible if no default module is given
if (showLoadModules) { //if (showLoadModules) {
menuBar.add(menuModule); // menuBar.add(menuModule);
} //}
menuBar.add(menuOptions); menuBar.add(menuOptions);
menuBar.add(((JExtDesktopPane) desktopPane).getWindowMenu()); menuBar.add(((JExtDesktopPane) desktopPane).getWindowMenu());

View File

@@ -8,6 +8,6 @@ package eva2.server.go;
* To change this template use Options | File Templates. * To change this template use Options | File Templates.
*/ */
public interface InterfaceGOStandalone { public interface InterfaceGOStandalone {
public void startExperiment(); void startExperiment();
public void setShow(boolean t); void setShow(boolean t);
} }

View File

@@ -14,5 +14,5 @@ public interface InterfacePopulationChangedEventListener {
* @param source The source of the event. * @param source The source of the event.
* @param name Could be used to indicate the nature of the event. * @param name Could be used to indicate the nature of the event.
*/ */
public void registerPopulationStateChanged(Object source, String name); void registerPopulationStateChanged(Object source, String name);
} }

View File

@@ -47,7 +47,6 @@ public class BOA implements InterfaceOptimizer, java.io.Serializable {
private static final Logger LOGGER = Logger.getLogger(BOA.class.getName()); private static final Logger LOGGER = Logger.getLogger(BOA.class.getName());
transient private InterfacePopulationChangedEventListener m_Listener = null; transient private InterfacePopulationChangedEventListener m_Listener = null;
private String m_Identifier = "BOA"; private String m_Identifier = "BOA";
private int probDim = 8; private int probDim = 8;
private int fitCrit = -1; private int fitCrit = -1;
private int PopSize = 50; private int PopSize = 50;
@@ -63,7 +62,6 @@ public class BOA implements InterfaceOptimizer, java.io.Serializable {
private int count = 0; private int count = 0;
private String netFolder = "BOAOutput"; private String netFolder = "BOAOutput";
private int[][] edgeRate = null; private int[][] edgeRate = null;
private BOAScoringMethods scoringMethod = BOAScoringMethods.BDM; private BOAScoringMethods scoringMethod = BOAScoringMethods.BDM;
private boolean printNetworks = false; private boolean printNetworks = false;
private boolean printEdgeRate = false; private boolean printEdgeRate = false;
@@ -72,7 +70,6 @@ public class BOA implements InterfaceOptimizer, java.io.Serializable {
// private boolean printExtraOutput = false; // private boolean printExtraOutput = false;
public BOA() { public BOA() {
} }
public BOA(int numberOfParents, int popSize, BOAScoringMethods method, public BOA(int numberOfParents, int popSize, BOAScoringMethods method,
@@ -166,7 +163,7 @@ public class BOA implements InterfaceOptimizer, java.io.Serializable {
File theDir = new File(directoryName); File theDir = new File(directoryName);
// if the directory does not exist, create it // if the directory does not exist, create it
if (!theDir.exists()) { if (!theDir.exists()) {
LOGGER.log(Level.INFO, "creating directory: "+directoryName); LOGGER.log(Level.INFO, "creating directory: " + directoryName);
theDir.mkdir(); theDir.mkdir();
} }
} }
@@ -185,11 +182,9 @@ public class BOA implements InterfaceOptimizer, java.io.Serializable {
private static BitSet getBinaryData(AbstractEAIndividual indy) { private static BitSet getBinaryData(AbstractEAIndividual indy) {
if (indy instanceof InterfaceGAIndividual) { if (indy instanceof InterfaceGAIndividual) {
return ((InterfaceGAIndividual) indy).getBGenotype(); return ((InterfaceGAIndividual) indy).getBGenotype();
} } else if (indy instanceof InterfaceDataTypeBinary) {
else if (indy instanceof InterfaceDataTypeBinary) {
return ((InterfaceDataTypeBinary) indy).getBinaryData(); return ((InterfaceDataTypeBinary) indy).getBinaryData();
} } else {
else {
throw new RuntimeException( throw new RuntimeException(
"Unable to get binary representation for " "Unable to get binary representation for "
+ indy.getClass()); + indy.getClass());
@@ -200,8 +195,7 @@ public class BOA implements InterfaceOptimizer, java.io.Serializable {
* evaluate the given Individual and increments the counter. if the * evaluate the given Individual and increments the counter. if the
* individual is null, only the counter is incremented * individual is null, only the counter is incremented
* *
* @param indy * @param indy the individual you want to evaluate
* the individual you want to evaluate
*/ */
private void evaluate(AbstractEAIndividual indy) { private void evaluate(AbstractEAIndividual indy) {
// evaluate the given individual if it is not null // evaluate the given individual if it is not null
@@ -343,8 +337,7 @@ public class BOA implements InterfaceOptimizer, java.io.Serializable {
* Generate a Bayesian network with the individuals of the population as a * Generate a Bayesian network with the individuals of the population as a
* reference Point * reference Point
* *
* @param pop * @param pop the individuals the network is based on
* the individuals the network is based on
*/ */
private void constructNetwork(Population pop) { private void constructNetwork(Population pop) {
generateGreedy(pop); generateGreedy(pop);
@@ -394,6 +387,7 @@ public class BOA implements InterfaceOptimizer, java.io.Serializable {
/** /**
* remove the individuals in pop from the population * remove the individuals in pop from the population
*
* @param pop * @param pop
*/ */
public void remove(Population pop) { public void remove(Population pop) {
@@ -546,7 +540,7 @@ public class BOA implements InterfaceOptimizer, java.io.Serializable {
// generate the network with these individuals // generate the network with these individuals
constructNetwork(best); constructNetwork(best);
// if(this.printExtraOutput && this.printEdgeRate){ // if(this.printExtraOutput && this.printEdgeRate){
if(this.printEdgeRate){ if (this.printEdgeRate) {
this.edgeRate = this.network.adaptEdgeRate(this.edgeRate); this.edgeRate = this.network.adaptEdgeRate(this.edgeRate);
} }
// sample new individuals from the network // sample new individuals from the network
@@ -627,15 +621,9 @@ public class BOA implements InterfaceOptimizer, java.io.Serializable {
return "Bayesian Network"; return "Bayesian Network";
} }
@Override
public void freeWilly() {
}
// ------------------------------- // -------------------------------
// -------------GUI--------------- // -------------GUI---------------
// ------------------------------- // -------------------------------
public int getNumberOfParents() { public int getNumberOfParents() {
return this.numberOfParents; return this.numberOfParents;
} }
@@ -725,13 +713,12 @@ public class BOA implements InterfaceOptimizer, java.io.Serializable {
} }
public String[] customPropertyOrder() { public String[] customPropertyOrder() {
return new String[] { "learningRatio", "resamplingRatio" }; return new String[]{"learningRatio", "resamplingRatio"};
} }
// public boolean isPrintExtraOutput() { // public boolean isPrintExtraOutput() {
// return this.printExtraOutput; // return this.printExtraOutput;
// } // }
// public void setPrintExtraOutput(boolean b) { // public void setPrintExtraOutput(boolean b) {
// this.printExtraOutput = b; // this.printExtraOutput = b;
// GenericObjectEditor.setHideProperty(getClass(), "printNetworks", // GenericObjectEditor.setHideProperty(getClass(), "printNetworks",
@@ -743,11 +730,9 @@ public class BOA implements InterfaceOptimizer, java.io.Serializable {
// GenericObjectEditor.setHideProperty(getClass(), "printTimestamps", // GenericObjectEditor.setHideProperty(getClass(), "printTimestamps",
// !printExtraOutput); // !printExtraOutput);
// } // }
// public String printExtraOutputTipText() { // public String printExtraOutputTipText() {
// return "do you want to print extra output files"; // return "do you want to print extra output files";
// } // }
public boolean isPrintNetworks() { public boolean isPrintNetworks() {
return this.printNetworks; return this.printNetworks;
} }
@@ -796,7 +781,6 @@ public class BOA implements InterfaceOptimizer, java.io.Serializable {
return "Print the time starting time and a timestamp after each generation"; return "Print the time starting time and a timestamp after each generation";
} }
public static void main(String[] args) { public static void main(String[] args) {
Population pop = new Population(); Population pop = new Population();
GAIndividualBinaryData indy1 = new GAIndividualBinaryData(); GAIndividualBinaryData indy1 = new GAIndividualBinaryData();
@@ -980,5 +964,4 @@ public class BOA implements InterfaceOptimizer, java.io.Serializable {
// b.print(); // b.print();
// b.printNetworkToFile("test"); // b.printNetworkToFile("test");
} }
} }

View File

@@ -30,15 +30,15 @@ import java.util.BitSet;
* *
* @author Alex * @author Alex
* *
* F. Gortazar, A. Duarte, M. Laguna and R. Marti: Black Box Scatter Search for General Classes of Binary Optimization Problems * F. Gortazar, A. Duarte, M. Laguna and R. Marti: Black Box Scatter Search for
* Computers and Operations research, vol. 37, no. 11, pp. 1977-1986 (2010) * General Classes of Binary Optimization Problems Computers and Operations
* research, vol. 37, no. 11, pp. 1977-1986 (2010)
*/ */
public class BinaryScatterSearch implements InterfaceOptimizer, java.io.Serializable, InterfacePopulationChangedEventListener { public class BinaryScatterSearch implements InterfaceOptimizer, java.io.Serializable, InterfacePopulationChangedEventListener {
private static boolean TRACE = false; private static boolean TRACE = false;
transient private InterfacePopulationChangedEventListener m_Listener = null; transient private InterfacePopulationChangedEventListener m_Listener = null;
private String m_Identifier = "BinaryScatterSearch"; private String m_Identifier = "BinaryScatterSearch";
private int MaxImpIter = 5; private int MaxImpIter = 5;
private int poolSize = 100; private int poolSize = 100;
private int refSetSize = 10; private int refSetSize = 10;
@@ -47,8 +47,8 @@ public class BinaryScatterSearch implements InterfaceOptimizer, java.io.Serializ
private int generationCycle = 500; private int generationCycle = 500;
private double th1 = 0.5; private double th1 = 0.5;
private double th2 = 0.5; private double th2 = 0.5;
private double g1 = 1.0/3.0; private double g1 = 1.0 / 3.0;
private double g2 = 1.0/3.0; private double g2 = 1.0 / 3.0;
private boolean firstTime = true; private boolean firstTime = true;
private AbstractEAIndividual template = null; private AbstractEAIndividual template = null;
private AbstractOptimizationProblem problem = new B1Problem(); private AbstractOptimizationProblem problem = new B1Problem();
@@ -59,14 +59,16 @@ public class BinaryScatterSearch implements InterfaceOptimizer, java.io.Serializ
/** /**
* Create a new BinaryScatterSearch with default values * Create a new BinaryScatterSearch with default values
*/ */
public BinaryScatterSearch(){ public BinaryScatterSearch() {
} }
/** /**
* Create a new BinaryScatterSearch with the same parameters as the given BinaryScatterSearch * Create a new BinaryScatterSearch with the same parameters as the given
* BinaryScatterSearch
*
* @param b * @param b
*/ */
public BinaryScatterSearch(BinaryScatterSearch b){ public BinaryScatterSearch(BinaryScatterSearch b) {
this.m_Listener = b.m_Listener; this.m_Listener = b.m_Listener;
this.m_Identifier = b.m_Identifier; this.m_Identifier = b.m_Identifier;
this.MaxImpIter = b.MaxImpIter; this.MaxImpIter = b.MaxImpIter;
@@ -74,7 +76,7 @@ public class BinaryScatterSearch implements InterfaceOptimizer, java.io.Serializ
this.refSetSize = b.refSetSize; this.refSetSize = b.refSetSize;
this.fitCrit = b.fitCrit; this.fitCrit = b.fitCrit;
this.probDim = b.probDim; this.probDim = b.probDim;
this.generationCycle= b.generationCycle; this.generationCycle = b.generationCycle;
this.th1 = b.th1; this.th1 = b.th1;
this.th2 = b.th2; this.th2 = b.th2;
this.g1 = b.g1; this.g1 = b.g1;
@@ -89,19 +91,22 @@ public class BinaryScatterSearch implements InterfaceOptimizer, java.io.Serializ
/** /**
* Create a new BinaryScatterSearch with the given Parameters * Create a new BinaryScatterSearch with the given Parameters
*
* @param refSetS the refSetSize * @param refSetS the refSetSize
* @param poolS the poolSize * @param poolS the poolSize
* @param lowerThreshold the lower Boundary for the local Search * @param lowerThreshold the lower Boundary for the local Search
* @param upperThreshold the upper Boundary for the local Search * @param upperThreshold the upper Boundary for the local Search
* @param perCentFirstIndGenerator how many individuals (in prospect of the poolSize) are generated through the first Generator * @param perCentFirstIndGenerator how many individuals (in prospect of the
* @param perCentSecondIndGenerator how many individuals (in prospect of the poolSize) are generated through the second Generator * poolSize) are generated through the first Generator
* @param perCentSecondIndGenerator how many individuals (in prospect of the
* poolSize) are generated through the second Generator
* @param prob the Problem * @param prob the Problem
*/ */
public BinaryScatterSearch( public BinaryScatterSearch(
int refSetS, int poolS, double lowerThreshold, double upperThreshold, int refSetS, int poolS, double lowerThreshold, double upperThreshold,
double perCentFirstIndGenerator, double perCentSecondIndGenerator, AbstractOptimizationProblem prob) { double perCentFirstIndGenerator, double perCentSecondIndGenerator, AbstractOptimizationProblem prob) {
this.refSetSize = refSetS; this.refSetSize = refSetS;
this.poolSize= poolS; this.poolSize = poolS;
this.th1 = lowerThreshold; this.th1 = lowerThreshold;
this.th2 = upperThreshold; this.th2 = upperThreshold;
this.g1 = perCentFirstIndGenerator; this.g1 = perCentFirstIndGenerator;
@@ -111,12 +116,15 @@ public class BinaryScatterSearch implements InterfaceOptimizer, java.io.Serializ
/** /**
* Create a new BinaryScatterSearch with the given Parameters * Create a new BinaryScatterSearch with the given Parameters
*
* @param refSetS the refSetSize * @param refSetS the refSetSize
* @param poolS the poolSize * @param poolS the poolSize
* @param lowerThreshold the lower Boundary for the local Search * @param lowerThreshold the lower Boundary for the local Search
* @param upperThreshold the upper Boundary for the local Search * @param upperThreshold the upper Boundary for the local Search
* @param perCentFirstIndGenerator how many individuals (in prospect of the poolSize) are generated through the first Generator * @param perCentFirstIndGenerator how many individuals (in prospect of the
* @param perCentSecondIndGenerator how many individuals (in prospect of the poolSize) are generated through the second Generator * poolSize) are generated through the first Generator
* @param perCentSecondIndGenerator how many individuals (in prospect of the
* poolSize) are generated through the second Generator
* @param prob the Problem * @param prob the Problem
* @param cross the Crossover-Operators * @param cross the Crossover-Operators
*/ */
@@ -125,7 +133,7 @@ public class BinaryScatterSearch implements InterfaceOptimizer, java.io.Serializ
double perCentFirstIndGenerator, double perCentSecondIndGenerator, double perCentFirstIndGenerator, double perCentSecondIndGenerator,
AbstractOptimizationProblem prob, AdaptiveCrossoverEAMixer cross) { AbstractOptimizationProblem prob, AdaptiveCrossoverEAMixer cross) {
this.refSetSize = refSetS; this.refSetSize = refSetS;
this.poolSize= poolS; this.poolSize = poolS;
this.th1 = lowerThreshold; this.th1 = lowerThreshold;
this.th2 = upperThreshold; this.th2 = upperThreshold;
this.g1 = perCentFirstIndGenerator; this.g1 = perCentFirstIndGenerator;
@@ -138,7 +146,7 @@ public class BinaryScatterSearch implements InterfaceOptimizer, java.io.Serializ
* @return a copy of the current BinaryScatterSearch * @return a copy of the current BinaryScatterSearch
*/ */
@Override @Override
public Object clone(){ public Object clone() {
return new BinaryScatterSearch(this); return new BinaryScatterSearch(this);
} }
@@ -156,8 +164,8 @@ public class BinaryScatterSearch implements InterfaceOptimizer, java.io.Serializ
@Override @Override
public boolean removePopulationChangedEventListener( public boolean removePopulationChangedEventListener(
InterfacePopulationChangedEventListener ea) { InterfacePopulationChangedEventListener ea) {
if (m_Listener==ea) { if (m_Listener == ea) {
m_Listener=null; m_Listener = null;
return true; return true;
} else { } else {
return false; return false;
@@ -165,12 +173,14 @@ public class BinaryScatterSearch implements InterfaceOptimizer, java.io.Serializ
} }
/** /**
* evaluate the given Individual and increments the counter. if the individual is null, only the counter is incremented * evaluate the given Individual and increments the counter. if the
* individual is null, only the counter is incremented
*
* @param indy the individual you want to evaluate * @param indy the individual you want to evaluate
*/ */
private void evaluate(AbstractEAIndividual indy){ private void evaluate(AbstractEAIndividual indy) {
// evaluate the given individual if it is not null // evaluate the given individual if it is not null
if(indy == null){ if (indy == null) {
System.err.println("tried to evaluate null"); System.err.println("tried to evaluate null");
return; return;
} }
@@ -182,18 +192,18 @@ public class BinaryScatterSearch implements InterfaceOptimizer, java.io.Serializ
/** /**
* Default initialization * Default initialization
*/ */
private void defaultInit(){ private void defaultInit() {
this.refSet = new Population(); this.refSet = new Population();
this.template = this.problem.getIndividualTemplate(); this.template = this.problem.getIndividualTemplate();
if (!(template instanceof InterfaceDataTypeBinary)){ if (!(template instanceof InterfaceDataTypeBinary)) {
System.err.println("Requiring binary data!"); System.err.println("Requiring binary data!");
}else{ } else {
Object dim = BeanInspector.callIfAvailable(problem, "getProblemDimension", null); Object dim = BeanInspector.callIfAvailable(problem, "getProblemDimension", null);
if (dim==null) { if (dim == null) {
System.err.println("Couldnt get problem dimension!"); System.err.println("Couldnt get problem dimension!");
} }
probDim = (Integer)dim; probDim = (Integer) dim;
((InterfaceDataTypeBinary)this.template).SetBinaryGenotype(new BitSet(probDim)); ((InterfaceDataTypeBinary) this.template).SetBinaryGenotype(new BitSet(probDim));
} }
this.firstTime = true; this.firstTime = true;
this.cross.init(this.template, problem, refSet, Double.MAX_VALUE); this.cross.init(this.template, problem, refSet, Double.MAX_VALUE);
@@ -219,27 +229,28 @@ public class BinaryScatterSearch implements InterfaceOptimizer, java.io.Serializ
* *
* @return a new diversified Population * @return a new diversified Population
*/ */
private Population diversify(){ private Population diversify() {
return diversify(new Population()); return diversify(new Population());
} }
/** /**
* *
* @param pop the initial Population * @param pop the initial Population
* @return a diversified Population with all the Individuals in the initial Population * @return a diversified Population with all the Individuals in the initial
* Population
*/ */
private Population diversify(Population pop){ private Population diversify(Population pop) {
int numToInit = this.poolSize - pop.size(); int numToInit = this.poolSize - pop.size();
if (numToInit>0) { if (numToInit > 0) {
pop.addAll(generateG1((int)(numToInit * this.g1))); pop.addAll(generateG1((int) (numToInit * this.g1)));
if (TRACE) { if (TRACE) {
System.out.println("s1: " + pop.size()); System.out.println("s1: " + pop.size());
} }
generateG2(pop, (int)(numToInit * this.g2)); generateG2(pop, (int) (numToInit * this.g2));
if (TRACE) { if (TRACE) {
System.out.println("s2: " + pop.size()); System.out.println("s2: " + pop.size());
} }
generateG3(pop, poolSize-pop.size()); generateG3(pop, poolSize - pop.size());
if (TRACE) { if (TRACE) {
System.out.println("s3: " + pop.size()); System.out.println("s3: " + pop.size());
} }
@@ -248,49 +259,52 @@ public class BinaryScatterSearch implements InterfaceOptimizer, java.io.Serializ
} }
/** /**
* Generate a new Population with diverse Individuals starting with 000...000, * Generate a new Population with diverse Individuals starting with
* then 010101...01, 101010...10, 001001001...001, 110110110...110 and so on * 000...000, then 010101...01, 101010...10, 001001001...001,
* The returned population is evaluated. * 110110110...110 and so on The returned population is evaluated.
*
* @param pop the initial Population * @param pop the initial Population
* @return the new Population * @return the new Population
*/ */
private Population generateG1(int numToInit){ private Population generateG1(int numToInit) {
Population pop = generateG1Pop(numToInit, this.template); Population pop = generateG1Pop(numToInit, this.template);
for (int i=0; i<pop.size(); i++) { for (int i = 0; i < pop.size(); i++) {
evaluate(pop.getEAIndividual(i)); evaluate(pop.getEAIndividual(i));
} }
return pop; return pop;
} }
/** /**
* Generate a new Population with diverse Individuals starting with 000...000, then 010101...01, * Generate a new Population with diverse Individuals starting with
* 101010...10, 001001001...001, 110110110...110 and so on * 000...000, then 010101...01, 101010...10, 001001001...001,
* 110110110...110 and so on
*
* @param pop the initial Population * @param pop the initial Population
* @return the new Population * @return the new Population
*/ */
public static Population generateG1Pop(int targetSize, AbstractEAIndividual template){ public static Population generateG1Pop(int targetSize, AbstractEAIndividual template) {
boolean method1 = true; boolean method1 = true;
int i=1; int i = 1;
Population pop = new Population(targetSize); Population pop = new Population(targetSize);
while(pop.size() < targetSize) { while (pop.size() < targetSize) {
AbstractEAIndividual indy = (AbstractEAIndividual) template.clone(); AbstractEAIndividual indy = (AbstractEAIndividual) template.clone();
BitSet data = getBinaryData(indy); BitSet data = getBinaryData(indy);
if(method1){ if (method1) {
method1 = !method1; method1 = !method1;
data.set(0, data.size(), true); data.set(0, data.size(), true);
for(int j=0; j<data.size(); j += i){ for (int j = 0; j < data.size(); j += i) {
data.flip(j); data.flip(j);
} }
((InterfaceDataTypeBinary) indy).SetBinaryGenotype(data); ((InterfaceDataTypeBinary) indy).SetBinaryGenotype(data);
if(i==1){ if (i == 1) {
i++; i++;
method1 = !method1; method1 = !method1;
} }
}else{ } else {
method1 = !method1; method1 = !method1;
if(i!=1){ if (i != 1) {
data.set(0, data.size(), false); data.set(0, data.size(), false);
for(int j=0; j<data.size(); j += i){ for (int j = 0; j < data.size(); j += i) {
data.flip(j); data.flip(j);
} }
((InterfaceDataTypeBinary) indy).SetBinaryGenotype(data); ((InterfaceDataTypeBinary) indy).SetBinaryGenotype(data);
@@ -303,24 +317,26 @@ public class BinaryScatterSearch implements InterfaceOptimizer, java.io.Serializ
} }
/** /**
* Generate new Individuals that have the individuals of the given Population as a base * Generate new Individuals that have the individuals of the given
* Population as a base
*
* @param pop the population * @param pop the population
* @return the new Population * @return the new Population
*/ */
private Population generateG2(Population pop, int numToInit){ private Population generateG2(Population pop, int numToInit) {
int origSize = pop.size(); int origSize = pop.size();
while(pop.size() < origSize+numToInit){ while (pop.size() < origSize + numToInit) {
AbstractEAIndividual indy = (AbstractEAIndividual)template.clone(); AbstractEAIndividual indy = (AbstractEAIndividual) template.clone();
InterfaceDataTypeBinary dblIndy = (InterfaceDataTypeBinary) indy; InterfaceDataTypeBinary dblIndy = (InterfaceDataTypeBinary) indy;
BitSet data = dblIndy.getBinaryData(); BitSet data = dblIndy.getBinaryData();
data.set(0, data.size(), false); data.set(0, data.size(), false);
for(int i=0; i<data.size(); i++){ for (int i = 0; i < data.size(); i++) {
if(RNG.flipCoin(Math.min(0.1+score(i, pop),1))){ if (RNG.flipCoin(Math.min(0.1 + score(i, pop), 1))) {
data.set(i, true); data.set(i, true);
} }
} }
dblIndy.SetBinaryGenotype(data); dblIndy.SetBinaryGenotype(data);
if(!contains(dblIndy, pop)){ if (!contains(dblIndy, pop)) {
pop.add(dblIndy); pop.add(dblIndy);
evaluate(indy); evaluate(indy);
} }
@@ -329,24 +345,26 @@ public class BinaryScatterSearch implements InterfaceOptimizer, java.io.Serializ
} }
/** /**
* Generate new Individuals that have the individuals of the given Population as a base * Generate new Individuals that have the individuals of the given
* Population as a base
*
* @param pop the population * @param pop the population
* @return the new Population * @return the new Population
*/ */
private Population generateG3(Population pop, int numToInit){ private Population generateG3(Population pop, int numToInit) {
int origSize = pop.size(); int origSize = pop.size();
while(pop.size() < origSize+numToInit){ while (pop.size() < origSize + numToInit) {
AbstractEAIndividual indy = (AbstractEAIndividual)template.clone(); AbstractEAIndividual indy = (AbstractEAIndividual) template.clone();
InterfaceDataTypeBinary dblIndy = (InterfaceDataTypeBinary)indy; InterfaceDataTypeBinary dblIndy = (InterfaceDataTypeBinary) indy;
BitSet data = dblIndy.getBinaryData(); BitSet data = dblIndy.getBinaryData();
data.set(0, data.size(), true); data.set(0, data.size(), true);
for(int i=0; i<data.size(); i++){ for (int i = 0; i < data.size(); i++) {
if(RNG.flipCoin(Math.max(0, 1-score(i, pop)))){//??? if (RNG.flipCoin(Math.max(0, 1 - score(i, pop)))) {//???
data.set(i, false); data.set(i, false);
} }
} }
dblIndy.SetBinaryGenotype(data); dblIndy.SetBinaryGenotype(data);
if(!contains(dblIndy, pop)){ if (!contains(dblIndy, pop)) {
pop.add(dblIndy); pop.add(dblIndy);
evaluate(indy); evaluate(indy);
} }
@@ -355,17 +373,19 @@ public class BinaryScatterSearch implements InterfaceOptimizer, java.io.Serializ
} }
/** /**
* calculate the number of individuals in the given Population that have a 1 at the i-th position * calculate the number of individuals in the given Population that have a 1
* at the i-th position
*
* @param i the position * @param i the position
* @param pop the population * @param pop the population
* @return The number of individuals that have a '1' on the i-th position * @return The number of individuals that have a '1' on the i-th position
*/ */
private static double calculateNumberOFPI1(int i, Population pop){ private static double calculateNumberOFPI1(int i, Population pop) {
int result = 0; int result = 0;
for(int j=0; j<pop.size(); j++){ for (int j = 0; j < pop.size(); j++) {
AbstractEAIndividual indy = pop.getEAIndividual(j); AbstractEAIndividual indy = pop.getEAIndividual(j);
BitSet binData = getBinaryData(indy); BitSet binData = getBinaryData(indy);
if(binData.get(i)){ if (binData.get(i)) {
result++; result++;
} }
} }
@@ -373,17 +393,19 @@ public class BinaryScatterSearch implements InterfaceOptimizer, java.io.Serializ
} }
/** /**
* calculate the number of individuals in the given Population that have a 0 at the i-th position * calculate the number of individuals in the given Population that have a 0
* at the i-th position
*
* @param i the position * @param i the position
* @param pop the population * @param pop the population
* @return The number of individuals that have a '0' on the i-th position * @return The number of individuals that have a '0' on the i-th position
*/ */
private static double calculateNumberOFPI0(int i, Population pop){ private static double calculateNumberOFPI0(int i, Population pop) {
int result = 0; int result = 0;
for(int j=0; j<pop.size(); j++){ for (int j = 0; j < pop.size(); j++) {
AbstractEAIndividual indy = pop.getEAIndividual(j); AbstractEAIndividual indy = pop.getEAIndividual(j);
BitSet binData = getBinaryData(indy); BitSet binData = getBinaryData(indy);
if(!binData.get(i)){ if (!binData.get(i)) {
result++; result++;
} }
} }
@@ -392,28 +414,28 @@ public class BinaryScatterSearch implements InterfaceOptimizer, java.io.Serializ
private static BitSet getBinaryData(AbstractEAIndividual indy) { private static BitSet getBinaryData(AbstractEAIndividual indy) {
if (indy instanceof InterfaceGAIndividual) { if (indy instanceof InterfaceGAIndividual) {
return ((InterfaceGAIndividual)indy).getBGenotype(); return ((InterfaceGAIndividual) indy).getBGenotype();
} } else if (indy instanceof InterfaceDataTypeBinary) {
else if (indy instanceof InterfaceDataTypeBinary) { return ((InterfaceDataTypeBinary) indy).getBinaryData();
return ((InterfaceDataTypeBinary)indy).getBinaryData(); } else {
}
else {
throw new RuntimeException("Unable to get binary representation for " + indy.getClass()); throw new RuntimeException("Unable to get binary representation for " + indy.getClass());
} }
} }
/** /**
* calculate the sum of all the FitnessValues of the individuals that have a '0' at the i-th position * calculate the sum of all the FitnessValues of the individuals that have a
* '0' at the i-th position
*
* @param i the position * @param i the position
* @param pop the population * @param pop the population
* @return the sum * @return the sum
*/ */
private static double calculateSumPI0(int i, Population pop){ private static double calculateSumPI0(int i, Population pop) {
double result = 0; double result = 0;
for(int j=0; j<pop.size(); j++){ for (int j = 0; j < pop.size(); j++) {
AbstractEAIndividual indy = pop.getEAIndividual(j); AbstractEAIndividual indy = pop.getEAIndividual(j);
BitSet binData = getBinaryData(indy); BitSet binData = getBinaryData(indy);
if(binData.get(i)){ if (binData.get(i)) {
result += indy.getFitness(0); result += indy.getFitness(0);
} }
} }
@@ -421,17 +443,19 @@ public class BinaryScatterSearch implements InterfaceOptimizer, java.io.Serializ
} }
/** /**
* calculate the sum of all the FitnessValues of the individuals that have a '0' at the i-th position * calculate the sum of all the FitnessValues of the individuals that have a
* '0' at the i-th position
*
* @param i the position * @param i the position
* @param pop the population * @param pop the population
* @return the sum * @return the sum
*/ */
private static double calculateSumPI1(int i, Population pop){ private static double calculateSumPI1(int i, Population pop) {
double result = 0; double result = 0;
for(int j=0; j<pop.size(); j++){ for (int j = 0; j < pop.size(); j++) {
AbstractEAIndividual indy = pop.getEAIndividual(j); AbstractEAIndividual indy = pop.getEAIndividual(j);
BitSet binData = getBinaryData(indy); BitSet binData = getBinaryData(indy);
if(binData.get(i)){ if (binData.get(i)) {
result += indy.getFitness(0); result += indy.getFitness(0);
} }
} }
@@ -439,37 +463,39 @@ public class BinaryScatterSearch implements InterfaceOptimizer, java.io.Serializ
} }
/** /**
* calculates a score that gives a reference Point if the Bit on the i-th position is right. * calculates a score that gives a reference Point if the Bit on the i-th
* If the bit is set to '1' and you get a high score then the Bit is probably set correct. * position is right. If the bit is set to '1' and you get a high score then
* If the bit is set to '0' and you get a low score then the Bit is probably set correct. * the Bit is probably set correct. If the bit is set to '0' and you get a
* low score then the Bit is probably set correct.
*
* @param i the position * @param i the position
* @param pop the population * @param pop the population
* @return the score * @return the score
*/ */
public static double score(int i, Population pop){ public static double score(int i, Population pop) {
double sumPI1 = calculateSumPI1(i, pop); double sumPI1 = calculateSumPI1(i, pop);
double sumPI0 = calculateSumPI0(i, pop); double sumPI0 = calculateSumPI0(i, pop);
double numberOfPI1 = calculateNumberOFPI1(i, pop); double numberOfPI1 = calculateNumberOFPI1(i, pop);
double numberOfPI0 = calculateNumberOFPI0(i, pop); double numberOfPI0 = calculateNumberOFPI0(i, pop);
double v= (sumPI1/numberOfPI1)/((sumPI1/numberOfPI1)+(sumPI0/numberOfPI0)); double v = (sumPI1 / numberOfPI1) / ((sumPI1 / numberOfPI1) + (sumPI0 / numberOfPI0));
return v; return v;
} }
/** /**
* calculate the first RefSet with the given Population as a reference Point * calculate the first RefSet with the given Population as a reference Point
*
* @param pop the generated Pool * @param pop the generated Pool
*/ */
private void initRefSet(Population pop){ private void initRefSet(Population pop) {
this.problem.evaluatePopulationStart(this.refSet); this.problem.evaluatePopulationStart(this.refSet);
this.pool = pop; this.pool = pop;
refSetUpdate(true); refSetUpdate(true);
Population best = this.refSet.getBestNIndividuals(this.refSetSize/2, fitCrit); Population best = this.refSet.getBestNIndividuals(this.refSetSize / 2, fitCrit);
for(int i=0; i<best.size(); i++){ for (int i = 0; i < best.size(); i++) {
//improve(best.getEAIndividual(i)); //improve(best.getEAIndividual(i));
AbstractEAIndividual indy = best.getEAIndividual(i); AbstractEAIndividual indy = best.getEAIndividual(i);
AbstractEAIndividual x = improve((AbstractEAIndividual)indy.clone()); AbstractEAIndividual x = improve((AbstractEAIndividual) indy.clone());
if(x.getFitness(0)<indy.getFitness(0) && !contains((InterfaceDataTypeBinary)x, this.refSet)){ if (x.getFitness(0) < indy.getFitness(0) && !contains((InterfaceDataTypeBinary) x, this.refSet)) {
this.refSet.remove(indy); this.refSet.remove(indy);
this.refSet.add(x); this.refSet.add(x);
} }
@@ -479,45 +505,46 @@ public class BinaryScatterSearch implements InterfaceOptimizer, java.io.Serializ
/** /**
* Update the reference Set * Update the reference Set
*
* @param replaceWorstHalf replaces the worst half of the RefSet if set * @param replaceWorstHalf replaces the worst half of the RefSet if set
* @return has the Population changed * @return has the Population changed
*/ */
private boolean refSetUpdate(boolean replaceWorstHalf){ private boolean refSetUpdate(boolean replaceWorstHalf) {
boolean refSetChanged = false; boolean refSetChanged = false;
Population rest = (Population) this.pool.clone(); Population rest = (Population) this.pool.clone();
if(this.firstTime){ if (this.firstTime) {
Population tmp = this.pool.getBestNIndividuals(this.pool.size(), this.fitCrit); Population tmp = this.pool.getBestNIndividuals(this.pool.size(), this.fitCrit);
int i=0; int i = 0;
while(this.refSet.size() < this.refSetSize){ while (this.refSet.size() < this.refSetSize) {
this.refSet.add(tmp.get(i)); this.refSet.add(tmp.get(i));
i++; i++;
} }
rest = this.pool.getWorstNIndividuals(this.poolSize-i, this.fitCrit); rest = this.pool.getWorstNIndividuals(this.poolSize - i, this.fitCrit);
refSetChanged = true; refSetChanged = true;
} }
if(replaceWorstHalf){ if (replaceWorstHalf) {
refSetChanged = true; refSetChanged = true;
// delete the worst half of refSet // delete the worst half of refSet
this.refSet.removeMembers(this.refSet.getWorstNIndividuals(this.refSet.size()-this.refSetSize/2, this.fitCrit), false); this.refSet.removeMembers(this.refSet.getWorstNIndividuals(this.refSet.size() - this.refSetSize / 2, this.fitCrit), false);
while(this.refSet.size()<this.refSetSize){ while (this.refSet.size() < this.refSetSize) {
ArrayList<Pair<Integer,Double>> list = new ArrayList<Pair<Integer,Double>>(); ArrayList<Pair<Integer, Double>> list = new ArrayList<Pair<Integer, Double>>();
for(int i=0; i< this.refSet.size(); i++){ for (int i = 0; i < this.refSet.size(); i++) {
AbstractEAIndividual indy = this.refSet.getEAIndividual(i); AbstractEAIndividual indy = this.refSet.getEAIndividual(i);
list.add(Population.getClosestFarthestIndy(indy, rest, new GenotypeMetricBitSet(), false)); list.add(Population.getClosestFarthestIndy(indy, rest, new GenotypeMetricBitSet(), false));
} }
Pair<Integer,Double> pair = list.get(0); Pair<Integer, Double> pair = list.get(0);
for(Pair<Integer,Double> p: list){ for (Pair<Integer, Double> p : list) {
if(p.getTail()<pair.getTail()){ if (p.getTail() < pair.getTail()) {
pair=p; pair = p;
} }
} }
this.refSet.add(rest.getEAIndividual(pair.getHead())); this.refSet.add(rest.getEAIndividual(pair.getHead()));
rest.remove(pair.getHead()); rest.remove(pair.getHead());
} }
}else{ } else {
Population best = this.pool.getBestNIndividuals(this.refSetSize, this.fitCrit); Population best = this.pool.getBestNIndividuals(this.refSetSize, this.fitCrit);
while(best.size()>0 && best.getBestEAIndividual().getFitness(0)<this.refSet.getWorstEAIndividual().getFitness(0)){ while (best.size() > 0 && best.getBestEAIndividual().getFitness(0) < this.refSet.getWorstEAIndividual().getFitness(0)) {
if(!contains((InterfaceDataTypeBinary)best.getBestIndividual(), this.refSet)){ if (!contains((InterfaceDataTypeBinary) best.getBestIndividual(), this.refSet)) {
refSetChanged = true; refSetChanged = true;
this.refSet.remove(this.refSet.getWorstEAIndividual()); this.refSet.remove(this.refSet.getWorstEAIndividual());
this.refSet.add(best.getBestIndividual()); this.refSet.add(best.getBestIndividual());
@@ -531,23 +558,24 @@ public class BinaryScatterSearch implements InterfaceOptimizer, java.io.Serializ
/** /**
* Order the given List according to the score of the given values * Order the given List according to the score of the given values
*
* @param list the initial List * @param list the initial List
* @return the ordered List * @return the ordered List
*/ */
private ArrayList<Integer> order(ArrayList<Integer> list){ private ArrayList<Integer> order(ArrayList<Integer> list) {
ArrayList<Integer> result = new ArrayList<Integer>(); ArrayList<Integer> result = new ArrayList<Integer>();
for(Integer s: list){ for (Integer s : list) {
boolean done = false; boolean done = false;
if(result.isEmpty()){ if (result.isEmpty()) {
result.add(s); result.add(s);
}else{ } else {
for(int i=0; i<result.size(); i++){ for (int i = 0; i < result.size(); i++) {
if(score(s, this.refSet)>score(result.get(i), this.refSet)&&!done){ if (score(s, this.refSet) > score(result.get(i), this.refSet) && !done) {
result.add(i,s); result.add(i, s);
done = true; done = true;
} }
} }
if(!done){ if (!done) {
result.add(s); result.add(s);
} }
} }
@@ -557,58 +585,59 @@ public class BinaryScatterSearch implements InterfaceOptimizer, java.io.Serializ
/** /**
* Do a local search * Do a local search
*
* @param indy the individual that will be improved * @param indy the individual that will be improved
* @return the new improved individual * @return the new improved individual
*/ */
private AbstractEAIndividual improve(AbstractEAIndividual indy){ private AbstractEAIndividual improve(AbstractEAIndividual indy) {
AbstractEAIndividual tmpIndy = (AbstractEAIndividual) indy.clone(); AbstractEAIndividual tmpIndy = (AbstractEAIndividual) indy.clone();
BitSet data = ((InterfaceDataTypeBinary)tmpIndy).getBinaryData(); BitSet data = ((InterfaceDataTypeBinary) tmpIndy).getBinaryData();
ArrayList<Integer> cl = new ArrayList<Integer>(); ArrayList<Integer> cl = new ArrayList<Integer>();
int localIter = 0; int localIter = 0;
for(int i=0; i<data.size(); i++){ for (int i = 0; i < data.size(); i++) {
if(data.get(i)){ if (data.get(i)) {
if(score(i, this.refSet)<=this.th2){ if (score(i, this.refSet) <= this.th2) {
cl.add(i); cl.add(i);
} }
}else{ } else {
if(score(i, this.refSet)>=this.th1){ if (score(i, this.refSet) >= this.th1) {
cl.add(i); cl.add(i);
} }
} }
} }
cl = order(cl); cl = order(cl);
boolean improvement = true; boolean improvement = true;
while(improvement && localIter < this.MaxImpIter){ while (improvement && localIter < this.MaxImpIter) {
improvement = false; improvement = false;
for(int i:cl){ for (int i : cl) {
data.flip(i); data.flip(i);
((InterfaceDataTypeBinary) tmpIndy).SetBinaryGenotype(data); ((InterfaceDataTypeBinary) tmpIndy).SetBinaryGenotype(data);
evaluate(tmpIndy); evaluate(tmpIndy);
if(tmpIndy.getFitness(0)<indy.getFitness(0)){ if (tmpIndy.getFitness(0) < indy.getFitness(0)) {
improvement = true; improvement = true;
indy = (AbstractEAIndividual) tmpIndy.clone(); indy = (AbstractEAIndividual) tmpIndy.clone();
data = ((InterfaceDataTypeBinary)tmpIndy).getBinaryData(); data = ((InterfaceDataTypeBinary) tmpIndy).getBinaryData();
}else{ } else {
tmpIndy = (AbstractEAIndividual) indy.clone(); tmpIndy = (AbstractEAIndividual) indy.clone();
} }
} }
cl = order(cl); cl = order(cl);
for(int i=0; i<cl.size()-1; i++){ for (int i = 0; i < cl.size() - 1; i++) {
boolean valI = ((InterfaceDataTypeBinary) tmpIndy).getBinaryData().get(i); boolean valI = ((InterfaceDataTypeBinary) tmpIndy).getBinaryData().get(i);
for(int j=i+1; j<cl.size(); j++){ for (int j = i + 1; j < cl.size(); j++) {
boolean valJ = ((InterfaceDataTypeBinary) tmpIndy).getBinaryData().get(i); boolean valJ = ((InterfaceDataTypeBinary) tmpIndy).getBinaryData().get(i);
if(valJ != valI){ if (valJ != valI) {
data.set(i, valJ); data.set(i, valJ);
data.set(j, valI); data.set(j, valI);
((InterfaceDataTypeBinary) tmpIndy).SetBinaryGenotype(data); ((InterfaceDataTypeBinary) tmpIndy).SetBinaryGenotype(data);
evaluate(tmpIndy); evaluate(tmpIndy);
if(tmpIndy.getFitness(0)<indy.getFitness(0)){ if (tmpIndy.getFitness(0) < indy.getFitness(0)) {
improvement = true; improvement = true;
indy = (AbstractEAIndividual) tmpIndy.clone(); indy = (AbstractEAIndividual) tmpIndy.clone();
data = ((InterfaceDataTypeBinary)tmpIndy).getBinaryData(); data = ((InterfaceDataTypeBinary) tmpIndy).getBinaryData();
i=cl.size(); i = cl.size();
j=cl.size(); j = cl.size();
}else{ } else {
tmpIndy = (AbstractEAIndividual) indy.clone(); tmpIndy = (AbstractEAIndividual) indy.clone();
} }
} }
@@ -621,12 +650,13 @@ public class BinaryScatterSearch implements InterfaceOptimizer, java.io.Serializ
/** /**
* Combine all the individuals in the reference Set (always 2) * Combine all the individuals in the reference Set (always 2)
*
* @return the List with all the combinations * @return the List with all the combinations
*/ */
public ArrayList<Population> generateSubsets(){ public ArrayList<Population> generateSubsets() {
ArrayList<Population> result = new ArrayList<Population>(); ArrayList<Population> result = new ArrayList<Population>();
for(int i=0; i<this.refSet.size(); i++){ for (int i = 0; i < this.refSet.size(); i++) {
for(int j=i+1; j<this.refSet.size(); j++){ for (int j = i + 1; j < this.refSet.size(); j++) {
Population tmp = new Population(); Population tmp = new Population();
tmp.add(this.refSet.getIndividual(i)); tmp.add(this.refSet.getIndividual(i));
tmp.add(this.refSet.getIndividual(j)); tmp.add(this.refSet.getIndividual(j));
@@ -638,24 +668,25 @@ public class BinaryScatterSearch implements InterfaceOptimizer, java.io.Serializ
/** /**
* combine the first individual with the second one * combine the first individual with the second one
*
* @param pop the Population * @param pop the Population
* @return the new Individual * @return the new Individual
*/ */
public AbstractEAIndividual combineSolution(Population pop){ public AbstractEAIndividual combineSolution(Population pop) {
AbstractEAIndividual result = (AbstractEAIndividual) template.clone(); AbstractEAIndividual result = (AbstractEAIndividual) template.clone();
if(pop.size()>=2){ if (pop.size() >= 2) {
AbstractEAIndividual indy1 = pop.getEAIndividual(0); AbstractEAIndividual indy1 = pop.getEAIndividual(0);
pop.remove(0); pop.remove(0);
// Because some Crossover-Methods need the score, we need to give them the RefSet // Because some Crossover-Methods need the score, we need to give them the RefSet
for(int i=0; i<this.refSet.size(); i++){ for (int i = 0; i < this.refSet.size(); i++) {
pop.add(this.refSet.getEAIndividual(i)); pop.add(this.refSet.getEAIndividual(i));
} }
this.cross.update(indy1, problem, refSet, indy1.getFitness(0)); this.cross.update(indy1, problem, refSet, indy1.getFitness(0));
result = this.cross.mate(indy1, pop)[0]; result = this.cross.mate(indy1, pop)[0];
//result = indy1.mateWith(s)[0]; //result = indy1.mateWith(s)[0];
}else if(pop.size()>0){ } else if (pop.size() > 0) {
result = pop.getBestEAIndividual(); result = pop.getBestEAIndividual();
}else{ } else {
System.err.println("Population empty"); System.err.println("Population empty");
//return null; //return null;
} }
@@ -664,18 +695,19 @@ public class BinaryScatterSearch implements InterfaceOptimizer, java.io.Serializ
/** /**
* look if the individual is already in the population * look if the individual is already in the population
*
* @param indy the Individual to be tested * @param indy the Individual to be tested
* @param pop the population in where to search * @param pop the population in where to search
* @return is the individual already in the Population * @return is the individual already in the Population
*/ */
private boolean contains(InterfaceDataTypeBinary indy, Population pop){ private boolean contains(InterfaceDataTypeBinary indy, Population pop) {
if(pop.size()<=0){ if (pop.size() <= 0) {
return false; return false;
}else{ } else {
BitSet data = indy.getBinaryData(); BitSet data = indy.getBinaryData();
for(int i=0; i<pop.size(); i++){ for (int i = 0; i < pop.size(); i++) {
BitSet tmpData = ((InterfaceDataTypeBinary) pop.getEAIndividual(i)).getBinaryData(); BitSet tmpData = ((InterfaceDataTypeBinary) pop.getEAIndividual(i)).getBinaryData();
if(tmpData.equals(data)){ if (tmpData.equals(data)) {
return true; return true;
} }
} }
@@ -691,27 +723,27 @@ public class BinaryScatterSearch implements InterfaceOptimizer, java.io.Serializ
// generate a new Pool // generate a new Pool
this.pool = new Population(); this.pool = new Population();
ArrayList<Population> newSubsets = generateSubsets(); ArrayList<Population> newSubsets = generateSubsets();
for(int i=0; i<newSubsets.size(); i++){ for (int i = 0; i < newSubsets.size(); i++) {
Population s = newSubsets.get(i); Population s = newSubsets.get(i);
AbstractEAIndividual x = combineSolution(s); AbstractEAIndividual x = combineSolution(s);
if(!contains((InterfaceDataTypeBinary)x,this.pool)&&this.pool.size()<=this.poolSize){ if (!contains((InterfaceDataTypeBinary) x, this.pool) && this.pool.size() <= this.poolSize) {
this.pool.add(x); this.pool.add(x);
} }
} }
this.refSet.incrFunctionCallsBy(this.pool.size()); this.refSet.incrFunctionCallsBy(this.pool.size());
// increase the number of evaluations by the number of evaluations that are performed in the crossover-step // increase the number of evaluations by the number of evaluations that are performed in the crossover-step
for(int i=0; i<this.cross.getEvaluations(); i++){ for (int i = 0; i < this.cross.getEvaluations(); i++) {
this.refSet.incrFunctionCalls(); this.refSet.incrFunctionCalls();
} }
// reset the extra evaluations // reset the extra evaluations
this.cross.resetEvaluations(); this.cross.resetEvaluations();
// get the best half of the Populations // get the best half of the Populations
Population best = this.refSet.getBestNIndividuals(this.refSetSize/2, fitCrit); Population best = this.refSet.getBestNIndividuals(this.refSetSize / 2, fitCrit);
// do a local search on the better half of the reference Set // do a local search on the better half of the reference Set
for(int i=0; i<best.size(); i++){ for (int i = 0; i < best.size(); i++) {
AbstractEAIndividual indy = best.getEAIndividual(i); AbstractEAIndividual indy = best.getEAIndividual(i);
AbstractEAIndividual x = improve((AbstractEAIndividual)indy.clone()); AbstractEAIndividual x = improve((AbstractEAIndividual) indy.clone());
if(x.getFitness(0)<indy.getFitness(0) && !contains((InterfaceDataTypeBinary)x, this.refSet)){ if (x.getFitness(0) < indy.getFitness(0) && !contains((InterfaceDataTypeBinary) x, this.refSet)) {
this.refSet.remove(indy); this.refSet.remove(indy);
this.refSet.add(x); this.refSet.add(x);
} }
@@ -719,10 +751,10 @@ public class BinaryScatterSearch implements InterfaceOptimizer, java.io.Serializ
// update the referenceSet // update the referenceSet
boolean changed = refSetUpdate(false); boolean changed = refSetUpdate(false);
// if no change occurred, replace the worst half of the referenceSet // if no change occurred, replace the worst half of the referenceSet
if(!changed){ if (!changed) {
refSetUpdate(true); refSetUpdate(true);
} }
} while (refSet.getFunctionCalls()-funCallsStart < generationCycle); } while (refSet.getFunctionCalls() - funCallsStart < generationCycle);
problem.evaluatePopulationEnd(refSet); problem.evaluatePopulationEnd(refSet);
} }
@@ -737,7 +769,7 @@ public class BinaryScatterSearch implements InterfaceOptimizer, java.io.Serializ
this.refSetSize = pop.getTargetSize(); this.refSetSize = pop.getTargetSize();
} }
public String populationTipText(){ public String populationTipText() {
return "The Population"; return "The Population";
} }
@@ -771,13 +803,7 @@ public class BinaryScatterSearch implements InterfaceOptimizer, java.io.Serializ
return "BinaryScatterSearch"; return "BinaryScatterSearch";
} }
@Override protected void firePropertyChangedEvent(String name) {
public void freeWilly() {
// TODO Auto-generated method stub
}
protected void firePropertyChangedEvent (String name) {
if (this.m_Listener != null) { if (this.m_Listener != null) {
this.m_Listener.registerPopulationStateChanged(this, name); this.m_Listener.registerPopulationStateChanged(this, name);
} }
@@ -788,7 +814,7 @@ public class BinaryScatterSearch implements InterfaceOptimizer, java.io.Serializ
// The events of the interim hill climbing population will be caught here // The events of the interim hill climbing population will be caught here
if (name.compareTo(Population.funCallIntervalReached) == 0) { if (name.compareTo(Population.funCallIntervalReached) == 0) {
// set funcalls to real value // set funcalls to real value
refSet.SetFunctionCalls(((Population)source).getFunctionCalls()); refSet.SetFunctionCalls(((Population) source).getFunctionCalls());
// System.out.println("FunCallIntervalReached at " + (((Population)source).getFunctionCalls())); // System.out.println("FunCallIntervalReached at " + (((Population)source).getFunctionCalls()));
@@ -797,105 +823,103 @@ public class BinaryScatterSearch implements InterfaceOptimizer, java.io.Serializ
} }
//----------GUI---------- //----------GUI----------
public int getPoolSize() {
public int getPoolSize(){
return this.poolSize; return this.poolSize;
} }
public void setPoolSize(int i){ public void setPoolSize(int i) {
this.poolSize = i; this.poolSize = i;
} }
public String poolSizeTipText(){ public String poolSizeTipText() {
return "The number of individuals created in the diversification step"; return "The number of individuals created in the diversification step";
} }
public double getThresholdHigh(){ public double getThresholdHigh() {
return th2; return th2;
} }
public void setThresholdHigh(double t){ public void setThresholdHigh(double t) {
this.th2 = t; this.th2 = t;
} }
public String thresholdHighTipText(){ public String thresholdHighTipText() {
return "Only scores set to 0 with a value below this value will be improved"; return "Only scores set to 0 with a value below this value will be improved";
} }
public double getThresholdLow(){ public double getThresholdLow() {
return th1; return th1;
} }
public void setThresholdLow(double t){ public void setThresholdLow(double t) {
this.th1 = t; this.th1 = t;
} }
public String thresholdLowTipText(){ public String thresholdLowTipText() {
return "Only scores set to 1 with a value above this value will be improved"; return "Only scores set to 1 with a value above this value will be improved";
} }
public int getLocalSearchSteps(){ public int getLocalSearchSteps() {
return this.MaxImpIter; return this.MaxImpIter;
} }
public void setLocalSearchSteps(int i){ public void setLocalSearchSteps(int i) {
this.MaxImpIter = i; this.MaxImpIter = i;
} }
public String localSearchStepsTipText(){ public String localSearchStepsTipText() {
return "Maximum number of local search iterations"; return "Maximum number of local search iterations";
} }
public AdaptiveCrossoverEAMixer getCrossoverMethods(){ public AdaptiveCrossoverEAMixer getCrossoverMethods() {
return this.cross; return this.cross;
} }
public void setCrossoverMethods(AdaptiveCrossoverEAMixer c) {
public void setCrossoverMethods(AdaptiveCrossoverEAMixer c){
this.cross = c; this.cross = c;
} }
public String crossoverMethodsTipText(){ public String crossoverMethodsTipText() {
return "The crossover Methods used to create the pool"; return "The crossover Methods used to create the pool";
} }
public int getGenerationCycle(){ public int getGenerationCycle() {
return this.generationCycle; return this.generationCycle;
} }
public void setGenerationCycle(int i){ public void setGenerationCycle(int i) {
this.generationCycle = i; this.generationCycle = i;
} }
public String generationCycleTipText(){ public String generationCycleTipText() {
return "The number of evaluations done in every generation Cycle"; return "The number of evaluations done in every generation Cycle";
} }
public double getPerCentFirstGenMethod(){ public double getPerCentFirstGenMethod() {
return this.g1; return this.g1;
} }
public void setPerCentFirstGenMethod(double d){ public void setPerCentFirstGenMethod(double d) {
this.g1 = d; this.g1 = d;
} }
public String perCentFirstGenMethodTipText(){ public String perCentFirstGenMethodTipText() {
return "The number of individuals generated with the first Generation Method. The percentage, that is not covered with the first and the second method will be covered with a third method"; return "The number of individuals generated with the first Generation Method. The percentage, that is not covered with the first and the second method will be covered with a third method";
} }
public double getPerCentSecondGenMethod(){ public double getPerCentSecondGenMethod() {
return this.g2; return this.g2;
} }
public void setPerCentSecondGenMethod(double d){ public void setPerCentSecondGenMethod(double d) {
this.g2 = d; this.g2 = d;
} }
public String perCentSecondGenMethodTipText(){ public String perCentSecondGenMethodTipText() {
return "The number of individuals generated with the second Generation Method. The percentage, that is not covered with the first and the second method will be covered with a third method"; return "The number of individuals generated with the second Generation Method. The percentage, that is not covered with the first and the second method will be covered with a third method";
} }
public static String globalInfo(){ public static String globalInfo() {
return "A basic implementation of a Binary ScatterSearch"; return "A basic implementation of a Binary ScatterSearch";
} }
} }

View File

@@ -1,6 +1,5 @@
package eva2.server.go.strategies; package eva2.server.go.strategies;
import eva2.server.go.InterfacePopulationChangedEventListener; import eva2.server.go.InterfacePopulationChangedEventListener;
import eva2.server.go.individuals.AbstractEAIndividual; import eva2.server.go.individuals.AbstractEAIndividual;
import eva2.server.go.individuals.InterfaceGAIndividual; import eva2.server.go.individuals.InterfaceGAIndividual;
@@ -15,22 +14,22 @@ import eva2.server.go.problems.InterfaceOptimizationProblem;
import eva2.tools.math.RNG; import eva2.tools.math.RNG;
import java.util.BitSet; import java.util.BitSet;
/** This is an implementation of the CHC Adaptive Search Algorithm by Eshelman. It is /**
* limited to binary data and is based on massively disruptive crossover. I'm not * This is an implementation of the CHC Adaptive Search Algorithm by Eshelman.
* sure whether i've implemented this correctly, but i definitely wasn't able to make * It is limited to binary data and is based on massively disruptive crossover.
* it competitive to a standard GA.. *sigh* * I'm not sure whether i've implemented this correctly, but i definitely wasn't
* This is a implementation of the CHC Adaptive Search Algorithm (Cross generational * able to make it competitive to a standard GA.. *sigh* This is a
* implementation of the CHC Adaptive Search Algorithm (Cross generational
* elitist selection, Heterogeneous recombination and Cataclysmic mutation). * elitist selection, Heterogeneous recombination and Cataclysmic mutation).
* Citation: * Citation:
* *
* Copyright: Copyright (c) 2003 * Copyright: Copyright (c) 2003 Company: University of Tuebingen, Computer
* Company: University of Tuebingen, Computer Architecture * Architecture
*
* @author Felix Streichert * @author Felix Streichert
* @version: $Revision: 307 $ * @version: $Revision: 307 $ $Date: 2007-12-04 14:31:47 +0100 (Tue, 04 Dec
* $Date: 2007-12-04 14:31:47 +0100 (Tue, 04 Dec 2007) $ * 2007) $ $Author: mkron $
* $Author: mkron $
*/ */
public class CHCAdaptiveSearchAlgorithm implements InterfaceOptimizer, java.io.Serializable { public class CHCAdaptiveSearchAlgorithm implements InterfaceOptimizer, java.io.Serializable {
private double m_InitialDifferenceThreshold = 0.25; private double m_InitialDifferenceThreshold = 0.25;
@@ -42,7 +41,6 @@ public class CHCAdaptiveSearchAlgorithm implements InterfaceOptimizer, java.io.S
private InterfaceOptimizationProblem m_Problem = new B1Problem(); private InterfaceOptimizationProblem m_Problem = new B1Problem();
private InterfaceSelection m_RecombSelectionOperator = new SelectRandom(); private InterfaceSelection m_RecombSelectionOperator = new SelectRandom();
private InterfaceSelection m_PopulSelectionOperator = new SelectBestSingle(); private InterfaceSelection m_PopulSelectionOperator = new SelectBestSingle();
transient private String m_Identifier = ""; transient private String m_Identifier = "";
transient private InterfacePopulationChangedEventListener m_Listener; transient private InterfacePopulationChangedEventListener m_Listener;
@@ -50,15 +48,15 @@ public class CHCAdaptiveSearchAlgorithm implements InterfaceOptimizer, java.io.S
} }
public CHCAdaptiveSearchAlgorithm(CHCAdaptiveSearchAlgorithm a) { public CHCAdaptiveSearchAlgorithm(CHCAdaptiveSearchAlgorithm a) {
this.m_Population = (Population)a.m_Population.clone(); this.m_Population = (Population) a.m_Population.clone();
this.m_Problem = (InterfaceOptimizationProblem)a.m_Problem.clone(); this.m_Problem = (InterfaceOptimizationProblem) a.m_Problem.clone();
this.m_InitialDifferenceThreshold = a.m_InitialDifferenceThreshold; this.m_InitialDifferenceThreshold = a.m_InitialDifferenceThreshold;
this.m_DifferenceThreshold = a.m_DifferenceThreshold; this.m_DifferenceThreshold = a.m_DifferenceThreshold;
this.m_DivergenceRate = a.m_DivergenceRate; this.m_DivergenceRate = a.m_DivergenceRate;
this.m_NumberOfPartners = a.m_NumberOfPartners; this.m_NumberOfPartners = a.m_NumberOfPartners;
this.m_UseElitism = a.m_UseElitism; this.m_UseElitism = a.m_UseElitism;
this.m_RecombSelectionOperator = (InterfaceSelection)a.m_RecombSelectionOperator.clone(); this.m_RecombSelectionOperator = (InterfaceSelection) a.m_RecombSelectionOperator.clone();
this.m_PopulSelectionOperator = (InterfaceSelection)a.m_PopulSelectionOperator.clone(); this.m_PopulSelectionOperator = (InterfaceSelection) a.m_PopulSelectionOperator.clone();
} }
@Override @Override
@@ -69,9 +67,9 @@ public class CHCAdaptiveSearchAlgorithm implements InterfaceOptimizer, java.io.S
@Override @Override
public void init() { public void init() {
this.m_Problem.initPopulation(this.m_Population); this.m_Problem.initPopulation(this.m_Population);
AbstractEAIndividual tmpIndy = ((AbstractEAIndividual)(this.m_Population.get(0))); AbstractEAIndividual tmpIndy = ((AbstractEAIndividual) (this.m_Population.get(0)));
if (tmpIndy instanceof InterfaceGAIndividual) { if (tmpIndy instanceof InterfaceGAIndividual) {
this.m_DifferenceThreshold = (int)(((InterfaceGAIndividual)tmpIndy).getGenotypeLength()*this.m_InitialDifferenceThreshold); this.m_DifferenceThreshold = (int) (((InterfaceGAIndividual) tmpIndy).getGenotypeLength() * this.m_InitialDifferenceThreshold);
} else { } else {
System.out.println("Problem does not apply InterfaceGAIndividual, which is the only individual type valid for CHC!"); System.out.println("Problem does not apply InterfaceGAIndividual, which is the only individual type valid for CHC!");
} }
@@ -80,19 +78,21 @@ public class CHCAdaptiveSearchAlgorithm implements InterfaceOptimizer, java.io.S
this.firePropertyChangedEvent(Population.nextGenerationPerformed); this.firePropertyChangedEvent(Population.nextGenerationPerformed);
} }
/** 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 pop The initial population
* @param reset If true the population is reset. * @param reset If true the population is reset.
*/ */
@Override @Override
public void initByPopulation(Population pop, boolean reset) { public void initByPopulation(Population pop, boolean reset) {
this.m_Population = (Population)pop.clone(); this.m_Population = (Population) pop.clone();
if (reset) { if (reset) {
this.m_Population.init(); this.m_Population.init();
} }
AbstractEAIndividual tmpIndy = ((AbstractEAIndividual)(this.m_Population.get(0))); AbstractEAIndividual tmpIndy = ((AbstractEAIndividual) (this.m_Population.get(0)));
if (tmpIndy instanceof InterfaceGAIndividual) { if (tmpIndy instanceof InterfaceGAIndividual) {
this.m_DifferenceThreshold = (int)(((InterfaceGAIndividual)tmpIndy).getGenotypeLength()*this.m_InitialDifferenceThreshold); this.m_DifferenceThreshold = (int) (((InterfaceGAIndividual) tmpIndy).getGenotypeLength() * this.m_InitialDifferenceThreshold);
} else { } else {
System.out.println("Problem does not apply InterfaceGAIndividual, which is the only individual type valid for CHC!"); System.out.println("Problem does not apply InterfaceGAIndividual, which is the only individual type valid for CHC!");
} }
@@ -103,8 +103,9 @@ public class CHCAdaptiveSearchAlgorithm implements InterfaceOptimizer, java.io.S
} }
} }
/** This method will evaluate the current population using the /**
* given problem. * This method will evaluate the current population using the given problem.
*
* @param population The population that is to be evaluated * @param population The population that is to be evaluated
*/ */
private void evaluatePopulation(Population population) { private void evaluatePopulation(Population population) {
@@ -112,8 +113,9 @@ public class CHCAdaptiveSearchAlgorithm implements InterfaceOptimizer, java.io.S
population.incrGeneration(); population.incrGeneration();
} }
/** 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.
*/ */
private Population generateChildren() { private Population generateChildren() {
Population result = this.m_Population.cloneWithoutInds(), parents, partners; Population result = this.m_Population.cloneWithoutInds(), parents, partners;
@@ -129,12 +131,12 @@ public class CHCAdaptiveSearchAlgorithm implements InterfaceOptimizer, java.io.S
//System.out.println("Parents:"+parents.getSolutionRepresentationFor()); //System.out.println("Parents:"+parents.getSolutionRepresentationFor());
for (int i = 0; i < parents.size(); i++) { for (int i = 0; i < parents.size(); i++) {
tmpIndy = ((AbstractEAIndividual)parents.get(i)); tmpIndy = ((AbstractEAIndividual) parents.get(i));
if (tmpIndy == null) { if (tmpIndy == null) {
System.out.println("Individual null "+i); System.out.println("Individual null " + i);
} }
if (this.m_Population == null) { if (this.m_Population == null) {
System.out.println("population null "+i); System.out.println("population null " + i);
} }
partners = this.m_RecombSelectionOperator.findPartnerFor(tmpIndy, this.m_Population, this.m_NumberOfPartners); partners = this.m_RecombSelectionOperator.findPartnerFor(tmpIndy, this.m_Population, this.m_NumberOfPartners);
@@ -149,7 +151,9 @@ public class CHCAdaptiveSearchAlgorithm implements InterfaceOptimizer, java.io.S
return result; return result;
} }
/** This method computes the Hamming Distance between n-Individuals /**
* This method computes the Hamming Distance between n-Individuals
*
* @param dad * @param dad
* @param partners * @param partners
* @return The maximal Hamming Distance between dad and the partners * @return The maximal Hamming Distance between dad and the partners
@@ -158,11 +162,11 @@ public class CHCAdaptiveSearchAlgorithm implements InterfaceOptimizer, java.io.S
int result = 0, tmpDist; int result = 0, tmpDist;
BitSet tmpB1, tmpB2; BitSet tmpB1, tmpB2;
tmpB1 = ((InterfaceGAIndividual)dad).getBGenotype(); tmpB1 = ((InterfaceGAIndividual) dad).getBGenotype();
for (int i = 0; i < partners.size(); i++) { for (int i = 0; i < partners.size(); i++) {
tmpB2 = ((InterfaceGAIndividual) partners.get(i)).getBGenotype(); tmpB2 = ((InterfaceGAIndividual) partners.get(i)).getBGenotype();
tmpDist = 0; tmpDist = 0;
for (int j = 0; j < ((InterfaceGAIndividual)dad).getGenotypeLength(); j++) { for (int j = 0; j < ((InterfaceGAIndividual) dad).getGenotypeLength(); j++) {
if (tmpB1.get(j) == tmpB2.get(j)) { if (tmpB1.get(j) == tmpB2.get(j)) {
tmpDist++; tmpDist++;
} }
@@ -172,8 +176,10 @@ public class CHCAdaptiveSearchAlgorithm implements InterfaceOptimizer, java.io.S
return result; return result;
} }
/** This method method replaces the current population with copies of the current /**
* best individual but all but one are randomized with a very high mutation rate. * This method method replaces the current population with copies of the
* current best individual but all but one are randomized with a very high
* mutation rate.
*/ */
private void diverge() { private void diverge() {
AbstractEAIndividual best = this.m_Population.getBestEAIndividual(); AbstractEAIndividual best = this.m_Population.getBestEAIndividual();
@@ -183,14 +189,13 @@ public class CHCAdaptiveSearchAlgorithm implements InterfaceOptimizer, java.io.S
this.m_Population.clear(); this.m_Population.clear();
this.m_Population.add(best); this.m_Population.add(best);
for (int i = 1; i < this.m_Population.getTargetSize(); i++) { for (int i = 1; i < this.m_Population.getTargetSize(); i++) {
mutant = (InterfaceGAIndividual)best.clone(); mutant = (InterfaceGAIndividual) best.clone();
tmpBitSet = mutant.getBGenotype(); tmpBitSet = mutant.getBGenotype();
for (int j = 0; j < mutant.getGenotypeLength(); j++) { for (int j = 0; j < mutant.getGenotypeLength(); j++) {
if (RNG.flipCoin(this.m_DivergenceRate)) { if (RNG.flipCoin(this.m_DivergenceRate)) {
if (tmpBitSet.get(j)) { if (tmpBitSet.get(j)) {
tmpBitSet.clear(j); tmpBitSet.clear(j);
} } else {
else {
tmpBitSet.set(j); tmpBitSet.set(j);
} }
} }
@@ -199,7 +204,7 @@ public class CHCAdaptiveSearchAlgorithm implements InterfaceOptimizer, java.io.S
this.m_Population.add(mutant); this.m_Population.add(mutant);
} }
if (best instanceof InterfaceGAIndividual) { if (best instanceof InterfaceGAIndividual) {
this.m_DifferenceThreshold = (int)(this.m_DivergenceRate* (1-this.m_DivergenceRate) * ((InterfaceGAIndividual)best).getGenotypeLength()); this.m_DifferenceThreshold = (int) (this.m_DivergenceRate * (1 - this.m_DivergenceRate) * ((InterfaceGAIndividual) best).getGenotypeLength());
} }
this.evaluatePopulation(this.m_Population); this.evaluatePopulation(this.m_Population);
@@ -237,39 +242,46 @@ public class CHCAdaptiveSearchAlgorithm implements InterfaceOptimizer, java.io.S
public void addPopulationChangedEventListener(InterfacePopulationChangedEventListener ea) { public void addPopulationChangedEventListener(InterfacePopulationChangedEventListener ea) {
this.m_Listener = ea; this.m_Listener = ea;
} }
@Override @Override
public boolean removePopulationChangedEventListener( public boolean removePopulationChangedEventListener(
InterfacePopulationChangedEventListener ea) { InterfacePopulationChangedEventListener ea) {
if (m_Listener==ea) { if (m_Listener == ea) {
m_Listener=null; m_Listener = null;
return true; return true;
} else { } else {
return false; return false;
} }
} }
/** Something has changed /**
* Something has changed
*/ */
protected void firePropertyChangedEvent (String name) { protected void firePropertyChangedEvent(String name) {
if (this.m_Listener != null) { if (this.m_Listener != null) {
this.m_Listener.registerPopulationStateChanged(this, name); this.m_Listener.registerPopulationStateChanged(this, name);
} }
} }
/** This method will set the problem that is to be optimized /**
* This method will set the problem that is to be optimized
*
* @param problem * @param problem
*/ */
@Override @Override
public void setProblem (InterfaceOptimizationProblem problem) { public void setProblem(InterfaceOptimizationProblem problem) {
this.m_Problem = problem; this.m_Problem = problem;
} }
@Override @Override
public InterfaceOptimizationProblem getProblem () { public InterfaceOptimizationProblem getProblem() {
return this.m_Problem; return this.m_Problem;
} }
/** This method will return a string describing all properties of the optimizer /**
* and the applied methods. * This method will return a string describing all properties of the
* optimizer and the applied methods.
*
* @return A descriptive string * @return A descriptive string
*/ */
@Override @Override
@@ -277,41 +289,42 @@ public class CHCAdaptiveSearchAlgorithm implements InterfaceOptimizer, java.io.S
String result = ""; String result = "";
result += "CHC Adaptive Search Algorithm:\n"; result += "CHC Adaptive Search Algorithm:\n";
result += "Optimization Problem: "; result += "Optimization Problem: ";
result += this.m_Problem.getStringRepresentationForProblem(this) +"\n"; result += this.m_Problem.getStringRepresentationForProblem(this) + "\n";
result += this.m_Population.getStringRepresentation(); result += this.m_Population.getStringRepresentation();
return result; return result;
} }
/** 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 * @param name The indenifier
*/ */
@Override @Override
public void setIdentifier(String name) { public void setIdentifier(String name) {
this.m_Identifier = name; this.m_Identifier = name;
} }
@Override @Override
public String getIdentifier() { public String getIdentifier() {
return this.m_Identifier; return this.m_Identifier;
} }
/** This method is required to free the memory on a RMIServer, /**
* but there is nothing to implement. * ********************************************************************************************************************
*/
@Override
public void freeWilly() {
}
/**********************************************************************************************************************
* These are for GUI * These are for GUI
*/ */
/** This method returns a global info string /**
* This method returns a global info string
*
* @return description * @return description
*/ */
public static String globalInfo() { public static String globalInfo() {
return "This is an implementation of the CHC Adaptive Search Algorithm by Eselman."; return "This is an implementation of the CHC Adaptive Search Algorithm by Eselman.";
} }
/** This method will return a naming String
/**
* This method will return a naming String
*
* @return The name of the algorithm * @return The name of the algorithm
*/ */
@Override @Override
@@ -319,19 +332,23 @@ public class CHCAdaptiveSearchAlgorithm implements InterfaceOptimizer, java.io.S
return "CHC"; return "CHC";
} }
/** Assuming that all optimizer will store thier data in a population /**
* we will allow acess to this population to query to current state * Assuming that all optimizer will store thier data in a population we will
* of the optimizer. * allow acess to this population to query to current state of the
* optimizer.
*
* @return The population of current solutions to a given problem. * @return The population of current solutions to a given problem.
*/ */
@Override @Override
public Population getPopulation() { public Population getPopulation() {
return this.m_Population; return this.m_Population;
} }
@Override @Override
public void setPopulation(Population pop){ public void setPopulation(Population pop) {
this.m_Population = pop; this.m_Population = pop;
} }
public String populationTipText() { public String populationTipText() {
return "Edit the properties of the population used."; return "Edit the properties of the population used.";
} }
@@ -353,21 +370,26 @@ public class CHCAdaptiveSearchAlgorithm implements InterfaceOptimizer, java.io.S
// public String normationMethodTipText() { // public String normationMethodTipText() {
// return "Select the normation method."; // return "Select the normation method.";
// } // }
/**
/** Enable/disable elitism. * Enable/disable elitism.
*
* @param elitism * @param elitism
*/ */
public void setElitism (boolean elitism) { public void setElitism(boolean elitism) {
this.m_UseElitism = elitism; this.m_UseElitism = elitism;
} }
public boolean getElitism() { public boolean getElitism() {
return this.m_UseElitism; return this.m_UseElitism;
} }
public String elitismTipText() { public String elitismTipText() {
return "Enable/disable elitism."; return "Enable/disable elitism.";
} }
/** The number of mating partners needed to create offsprings. /**
* The number of mating partners needed to create offsprings.
*
* @param partners * @param partners
*/ */
public void setNumberOfPartners(int partners) { public void setNumberOfPartners(int partners) {
@@ -376,9 +398,11 @@ public class CHCAdaptiveSearchAlgorithm implements InterfaceOptimizer, java.io.S
} }
this.m_NumberOfPartners = partners; this.m_NumberOfPartners = partners;
} }
public int getNumberOfPartners() { public int getNumberOfPartners() {
return this.m_NumberOfPartners; return this.m_NumberOfPartners;
} }
public String numberOfPartnersTipText() { public String numberOfPartnersTipText() {
return "The number of mating partners needed to create offsprings."; return "The number of mating partners needed to create offsprings.";
} }

File diff suppressed because it is too large Load Diff

View File

@@ -16,27 +16,29 @@ import eva2.server.go.problems.InterfaceOptimizationProblem;
import eva2.tools.Pair; import eva2.tools.Pair;
import java.io.Serializable; import java.io.Serializable;
/** /**
* The clustering hill climber is similar to a multi-start hill climber. In addition so optimizing * The clustering hill climber is similar to a multi-start hill climber. In
* a set of individuals in parallel using a (1+1) strategy, the population is clustered in regular * addition so optimizing a set of individuals in parallel using a (1+1)
* intervals. If several individuals have gathered together in the sense that they are interpreted * strategy, the population is clustered in regular intervals. If several
* as a cluster, only a subset of representatives of the cluster is taken over to the next HC step * individuals have gathered together in the sense that they are interpreted as
* while the rest is discarded. This means that the population size may be reduced. * a cluster, only a subset of representatives of the cluster is taken over to
* the next HC step while the rest is discarded. This means that the population
* size may be reduced.
* *
* As soon as the improvement by HC lies below a threshold, the mutation step size is decreased. * As soon as the improvement by HC lies below a threshold, the mutation step
* If the step size is decreased below a certain threshold, the current population is stored to * size is decreased. If the step size is decreased below a certain threshold,
* an archive and reinitialized. Thus, the number of optima that may be found and returned by * the current population is stored to an archive and reinitialized. Thus, the
* getAllSolutions is higher than the population size. * number of optima that may be found and returned by getAllSolutions is higher
* than the population size.
* *
* @author mkron * @author mkron
* *
*/ */
public class ClusteringHillClimbing implements InterfacePopulationChangedEventListener, public class ClusteringHillClimbing implements InterfacePopulationChangedEventListener,
InterfaceOptimizer, Serializable, InterfaceAdditionalPopulationInformer { InterfaceOptimizer, Serializable, InterfaceAdditionalPopulationInformer {
transient private InterfacePopulationChangedEventListener m_Listener; transient private InterfacePopulationChangedEventListener m_Listener;
public static final boolean TRACE = false; public static final boolean TRACE = false;
transient private String m_Identifier = ""; transient private String m_Identifier = "";
private Population m_Population = new Population(); private Population m_Population = new Population();
private transient Population archive = new Population(); private transient Population archive = new Population();
@@ -68,8 +70,8 @@ InterfaceOptimizer, Serializable, InterfaceAdditionalPopulationInformer {
public ClusteringHillClimbing(ClusteringHillClimbing other) { public ClusteringHillClimbing(ClusteringHillClimbing other) {
hideHideable(); hideHideable();
m_Population = (Population)other.m_Population.clone(); m_Population = (Population) other.m_Population.clone();
m_Problem = (InterfaceOptimizationProblem)other.m_Problem.clone(); m_Problem = (InterfaceOptimizationProblem) other.m_Problem.clone();
hcEvalCycle = other.hcEvalCycle; hcEvalCycle = other.hcEvalCycle;
initialPopSize = other.initialPopSize; initialPopSize = other.initialPopSize;
@@ -79,7 +81,7 @@ InterfaceOptimizer, Serializable, InterfaceAdditionalPopulationInformer {
stepSizeThreshold = other.stepSizeThreshold; stepSizeThreshold = other.stepSizeThreshold;
initialStepSize = other.initialStepSize; initialStepSize = other.initialStepSize;
reduceFactor = other.reduceFactor; reduceFactor = other.reduceFactor;
mutator = (MutateESFixedStepSize)other.mutator.clone(); mutator = (MutateESFixedStepSize) other.mutator.clone();
loopCnt = 0; loopCnt = 0;
} }
@@ -101,20 +103,24 @@ InterfaceOptimizer, Serializable, InterfaceAdditionalPopulationInformer {
public void setIdentifier(String name) { public void setIdentifier(String name) {
this.m_Identifier = name; this.m_Identifier = name;
} }
@Override @Override
public String getIdentifier() { public String getIdentifier() {
return this.m_Identifier; return this.m_Identifier;
} }
/** This method will set the problem that is to be optimized /**
* This method will set the problem that is to be optimized
*
* @param problem * @param problem
*/ */
@Override @Override
public void setProblem (InterfaceOptimizationProblem problem) { public void setProblem(InterfaceOptimizationProblem problem) {
this.m_Problem = problem; this.m_Problem = problem;
} }
@Override @Override
public InterfaceOptimizationProblem getProblem () { public InterfaceOptimizationProblem getProblem() {
return this.m_Problem; return this.m_Problem;
} }
@@ -122,16 +128,18 @@ InterfaceOptimizer, Serializable, InterfaceAdditionalPopulationInformer {
public void addPopulationChangedEventListener(InterfacePopulationChangedEventListener ea) { public void addPopulationChangedEventListener(InterfacePopulationChangedEventListener ea) {
this.m_Listener = ea; this.m_Listener = ea;
} }
@Override @Override
public boolean removePopulationChangedEventListener( public boolean removePopulationChangedEventListener(
InterfacePopulationChangedEventListener ea) { InterfacePopulationChangedEventListener ea) {
if (m_Listener==ea) { if (m_Listener == ea) {
m_Listener=null; m_Listener = null;
return true; return true;
} else { } else {
return false; return false;
} }
} }
@Override @Override
public void init() { public void init() {
loopCnt = 0; loopCnt = 0;
@@ -145,14 +153,16 @@ InterfaceOptimizer, Serializable, InterfaceAdditionalPopulationInformer {
this.firePropertyChangedEvent(Population.nextGenerationPerformed); this.firePropertyChangedEvent(Population.nextGenerationPerformed);
} }
/** 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 pop The initial population
* @param reset If true the population is reset. * @param reset If true the population is reset.
*/ */
@Override @Override
public void initByPopulation(Population pop, boolean reset) { public void initByPopulation(Population pop, boolean reset) {
loopCnt = 0; loopCnt = 0;
this.m_Population = (Population)pop.clone(); this.m_Population = (Population) pop.clone();
m_Population.addPopulationChangedEventListener(null); m_Population.addPopulationChangedEventListener(null);
if (reset) { if (reset) {
this.m_Population.init(); this.m_Population.init();
@@ -161,9 +171,10 @@ InterfaceOptimizer, Serializable, InterfaceAdditionalPopulationInformer {
} }
} }
/** Something has changed /**
* Something has changed
*/ */
protected void firePropertyChangedEvent (String name) { protected void firePropertyChangedEvent(String name) {
if (this.m_Listener != null) { if (this.m_Listener != null) {
this.m_Listener.registerPopulationStateChanged(this, name); this.m_Listener.registerPopulationStateChanged(this, name);
} }
@@ -177,32 +188,31 @@ InterfaceOptimizer, Serializable, InterfaceAdditionalPopulationInformer {
m_Population.addPopulationChangedEventListener(this); m_Population.addPopulationChangedEventListener(this);
m_Population.setNotifyEvalInterval(notifyGuiEvery); m_Population.setNotifyEvalInterval(notifyGuiEvery);
Pair<Population, Double> popD; Pair<Population, Double> popD;
int funCallsBefore=m_Population.getFunctionCalls(); int funCallsBefore = m_Population.getFunctionCalls();
int evalsNow, lastOverhead = (m_Population.getFunctionCalls() % hcEvalCycle); int evalsNow, lastOverhead = (m_Population.getFunctionCalls() % hcEvalCycle);
if (lastOverhead>0) { if (lastOverhead > 0) {
evalsNow = (2*hcEvalCycle - (m_Population.getFunctionCalls() % hcEvalCycle)); evalsNow = (2 * hcEvalCycle - (m_Population.getFunctionCalls() % hcEvalCycle));
} } else {
else {
evalsNow = hcEvalCycle; evalsNow = hcEvalCycle;
} }
do { do {
if (TRACE) { if (TRACE) {
System.out.println("evalCycle: " + hcEvalCycle + ", evals now: " + evalsNow); System.out.println("evalCycle: " + hcEvalCycle + ", evals now: " + evalsNow);
} }
popD = PostProcess.clusterLocalSearch(localSearchMethod, m_Population, (AbstractOptimizationProblem)m_Problem, sigmaClust, evalsNow, 0.5, mutator); popD = PostProcess.clusterLocalSearch(localSearchMethod, m_Population, (AbstractOptimizationProblem) m_Problem, sigmaClust, evalsNow, 0.5, mutator);
// (m_Population, (AbstractOptimizationProblem)m_Problem, sigmaClust, hcEvalCycle - (m_Population.getFunctionCalls() % hcEvalCycle), 0.5); // (m_Population, (AbstractOptimizationProblem)m_Problem, sigmaClust, hcEvalCycle - (m_Population.getFunctionCalls() % hcEvalCycle), 0.5);
if (popD.head().getFunctionCalls()==funCallsBefore) { if (popD.head().getFunctionCalls() == funCallsBefore) {
System.err.println("Bad case, increasing allowed evaluations!"); System.err.println("Bad case, increasing allowed evaluations!");
evalsNow=Math.max(evalsNow++, (int)(evalsNow*1.2)); evalsNow = Math.max(evalsNow++, (int) (evalsNow * 1.2));
} }
} while (popD.head().getFunctionCalls()==funCallsBefore); } while (popD.head().getFunctionCalls() == funCallsBefore);
improvement = popD.tail(); improvement = popD.tail();
m_Population = popD.head(); m_Population = popD.head();
if (TRACE) { if (TRACE) {
System.out.println("num inds after clusterLS: " + m_Population.size()); System.out.println("num inds after clusterLS: " + m_Population.size());
} }
popD.head().setGenerationTo(m_Population.getGeneration()+1); popD.head().setGenerationTo(m_Population.getGeneration() + 1);
if (doReinitialization && (improvement < minImprovement)) { if (doReinitialization && (improvement < minImprovement)) {
if (TRACE) { if (TRACE) {
@@ -239,7 +249,7 @@ InterfaceOptimizer, Serializable, InterfaceAdditionalPopulationInformer {
if (localSearchMethod != PostProcessMethod.hillClimber) { if (localSearchMethod != PostProcessMethod.hillClimber) {
System.err.println("Invalid case in ClusteringHillClimbing!"); System.err.println("Invalid case in ClusteringHillClimbing!");
} }
mutator.setSigma(mutator.getSigma()*reduceFactor); mutator.setSigma(mutator.getSigma() * reduceFactor);
if (TRACE) { if (TRACE) {
System.out.println("mutation stepsize reduced to " + mutator.getSigma()); System.out.println("mutation stepsize reduced to " + mutator.getSigma());
} }
@@ -258,7 +268,7 @@ InterfaceOptimizer, Serializable, InterfaceAdditionalPopulationInformer {
// System.out.println("bla"); // System.out.println("bla");
// } // }
// set funcalls to real value // set funcalls to real value
m_Population.SetFunctionCalls(((Population)source).getFunctionCalls()); m_Population.SetFunctionCalls(((Population) source).getFunctionCalls());
// System.out.println("FunCallIntervalReached at " + (((Population)source).getFunctionCalls())); // System.out.println("FunCallIntervalReached at " + (((Population)source).getFunctionCalls()));
this.firePropertyChangedEvent(Population.nextGenerationPerformed); this.firePropertyChangedEvent(Population.nextGenerationPerformed);
} }
@@ -267,19 +277,23 @@ InterfaceOptimizer, Serializable, InterfaceAdditionalPopulationInformer {
} }
/** Assuming that all optimizer will store thier data in a population /**
* we will allow acess to this population to query to current state * Assuming that all optimizer will store thier data in a population we will
* of the optimizer. * allow acess to this population to query to current state of the
* optimizer.
*
* @return The population of current solutions to a given problem. * @return The population of current solutions to a given problem.
*/ */
@Override @Override
public Population getPopulation() { public Population getPopulation() {
return this.m_Population; return this.m_Population;
} }
@Override @Override
public void setPopulation(Population pop){ public void setPopulation(Population pop) {
this.m_Population = pop; this.m_Population = pop;
} }
public String populationTipText() { public String populationTipText() {
return "Change the number of starting individuals stored (Cluster-HC)."; return "Change the number of starting individuals stored (Cluster-HC).";
} }
@@ -295,8 +309,10 @@ InterfaceOptimizer, Serializable, InterfaceAdditionalPopulationInformer {
return new SolutionSet(m_Population, tmp); return new SolutionSet(m_Population, tmp);
} }
/** This method will return a string describing all properties of the optimizer /**
* and the applied methods. * This method will return a string describing all properties of the
* optimizer and the applied methods.
*
* @return A descriptive string * @return A descriptive string
*/ */
@Override @Override
@@ -310,17 +326,14 @@ InterfaceOptimizer, Serializable, InterfaceAdditionalPopulationInformer {
return sbuf.toString(); return sbuf.toString();
} }
@Override
public void freeWilly() {}
@Override @Override
public String getName() { public String getName() {
return "ClustHC-"+initialPopSize+"-"+localSearchMethod; return "ClustHC-" + initialPopSize + "-" + localSearchMethod;
} }
public static String globalInfo() { public static String globalInfo() {
return "Similar to multi-start HC, but clusters the population during optimization to remove redundant individuals for efficiency." + return "Similar to multi-start HC, but clusters the population during optimization to remove redundant individuals for efficiency."
"If the local search step does not achieve a minimum improvement, the population may be reinitialized."; + "If the local search step does not achieve a minimum improvement, the population may be reinitialized.";
} }
/** /**
@@ -455,8 +468,8 @@ InterfaceOptimizer, Serializable, InterfaceAdditionalPopulationInformer {
public void setLocalSearchMethod(PostProcessMethod localSearchMethod) { public void setLocalSearchMethod(PostProcessMethod localSearchMethod) {
this.localSearchMethod = localSearchMethod; this.localSearchMethod = localSearchMethod;
GenericObjectEditor.setShowProperty(this.getClass(), "stepSizeInitial", localSearchMethod==PostProcessMethod.hillClimber); GenericObjectEditor.setShowProperty(this.getClass(), "stepSizeInitial", localSearchMethod == PostProcessMethod.hillClimber);
GenericObjectEditor.setShowProperty(this.getClass(), "stepSizeThreshold", localSearchMethod==PostProcessMethod.hillClimber); GenericObjectEditor.setShowProperty(this.getClass(), "stepSizeThreshold", localSearchMethod == PostProcessMethod.hillClimber);
} }
public String localSearchMethodTipText() { public String localSearchMethodTipText() {

View File

@@ -21,12 +21,12 @@ import eva2.tools.math.RNG;
import java.util.Vector; import java.util.Vector;
/** /**
* Differential evolution implementing DE1 and DE2 following the paper of Storm and * Differential evolution implementing DE1 and DE2 following the paper of Storm
* Price and the Trigonometric DE published recently. * and Price and the Trigonometric DE published recently. Please note that DE
* Please note that DE will only work on real-valued genotypes and will ignore * will only work on real-valued genotypes and will ignore all mutation and
* all mutation and crossover operators selected. * crossover operators selected. Added aging mechanism to provide for
* Added aging mechanism to provide for dynamically changing problems. If an individual * dynamically changing problems. If an individual reaches the age limit, it is
* reaches the age limit, it is doomed and replaced by the next challenge vector, even if its worse. * doomed and replaced by the next challenge vector, even if its worse.
* *
*/ */
public class DifferentialEvolution implements InterfaceOptimizer, java.io.Serializable { public class DifferentialEvolution implements InterfaceOptimizer, java.io.Serializable {
@@ -44,11 +44,10 @@ public class DifferentialEvolution implements InterfaceOptimizer, java.io.Serial
// to log the parents of a newly created indy. // to log the parents of a newly created indy.
public boolean doLogParents = false; // deactivate for better performance public boolean doLogParents = false; // deactivate for better performance
private transient Vector<AbstractEAIndividual> parents = null; private transient Vector<AbstractEAIndividual> parents = null;
private boolean randomizeFKLambda = false; private boolean randomizeFKLambda = false;
private boolean generational = true; private boolean generational = true;
private String m_Identifier = ""; private String m_Identifier = "";
transient private Vector<InterfacePopulationChangedEventListener> m_Listener=new Vector<InterfacePopulationChangedEventListener>(); transient private Vector<InterfacePopulationChangedEventListener> m_Listener = new Vector<InterfacePopulationChangedEventListener>();
private boolean forceRange = true; private boolean forceRange = true;
private boolean cyclePop = false; // if true, individuals are used as parents in a cyclic sequence - otherwise randomly private boolean cyclePop = false; // if true, individuals are used as parents in a cyclic sequence - otherwise randomly
private boolean compareToParent = true; // if true, the challenge indy is compared to its parent, otherwise to a random individual private boolean compareToParent = true; // if true, the challenge indy is compared to its parent, otherwise to a random individual
@@ -63,7 +62,7 @@ public class DifferentialEvolution implements InterfaceOptimizer, java.io.Serial
} }
public DifferentialEvolution(int popSize, DETypeEnum type, double f, double k, double lambda, double mt) { public DifferentialEvolution(int popSize, DETypeEnum type, double f, double k, double lambda, double mt) {
m_Population=new Population(popSize); m_Population = new Population(popSize);
m_DEType = type; m_DEType = type;
m_F = f; m_F = f;
m_k = k; m_k = k;
@@ -78,8 +77,8 @@ public class DifferentialEvolution implements InterfaceOptimizer, java.io.Serial
*/ */
public DifferentialEvolution(DifferentialEvolution a) { public DifferentialEvolution(DifferentialEvolution a) {
this.m_DEType = a.m_DEType; this.m_DEType = a.m_DEType;
this.m_Population = (Population)a.m_Population.clone(); this.m_Population = (Population) a.m_Population.clone();
this.m_Problem = (AbstractOptimizationProblem)a.m_Problem.clone(); this.m_Problem = (AbstractOptimizationProblem) a.m_Problem.clone();
this.m_Identifier = a.m_Identifier; this.m_Identifier = a.m_Identifier;
this.m_F = a.m_F; this.m_F = a.m_F;
this.m_k = a.m_k; this.m_k = a.m_k;
@@ -110,13 +109,15 @@ public class DifferentialEvolution implements InterfaceOptimizer, java.io.Serial
setDEType(getDEType()); setDEType(getDEType());
} }
/** 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 pop The initial population
* @param reset If true the population is reset. * @param reset If true the population is reset.
*/ */
@Override @Override
public void initByPopulation(Population pop, boolean reset) { public void initByPopulation(Population pop, boolean reset) {
this.m_Population = (Population)pop.clone(); this.m_Population = (Population) pop.clone();
if (reset) { if (reset) {
this.m_Population.init(); this.m_Population.init();
this.evaluatePopulation(this.m_Population); this.evaluatePopulation(this.m_Population);
@@ -126,8 +127,9 @@ public class DifferentialEvolution implements InterfaceOptimizer, java.io.Serial
// else children = new Population(m_Population.size()); // else children = new Population(m_Population.size());
} }
/** This method will evaluate the current population using the /**
* given problem. * This method will evaluate the current population using the given problem.
*
* @param population The population that is to be evaluated * @param population The population that is to be evaluated
*/ */
private void evaluatePopulation(Population population) { private void evaluatePopulation(Population population) {
@@ -136,8 +138,8 @@ public class DifferentialEvolution implements InterfaceOptimizer, java.io.Serial
} }
/** /**
* This method returns a difference vector between two random individuals from the population. * This method returns a difference vector between two random individuals
* This method should make sure that delta is not zero. * from the population. This method should make sure that delta is not zero.
* *
* @param pop The population to choose from * @param pop The population to choose from
* @return The delta vector * @return The delta vector
@@ -164,7 +166,7 @@ public class DifferentialEvolution implements InterfaceOptimizer, java.io.Serial
for (int i = 0; i < x1.length; i++) { for (int i = 0; i < x1.length; i++) {
result[i] = x1[i] - x2[i]; result[i] = x1[i] - x2[i];
isEmpty = (isEmpty && (result[i]==0)); isEmpty = (isEmpty && (result[i] == 0));
} }
iterations++; iterations++;
} }
@@ -176,13 +178,12 @@ public class DifferentialEvolution implements InterfaceOptimizer, java.io.Serial
// for n (popSize) iterations there were only zero vectors found // for n (popSize) iterations there were only zero vectors found
// so now the hard way: construct a random vector // so now the hard way: construct a random vector
for (int i = 0; i < x1.length; i++) { for (int i = 0; i < x1.length; i++) {
if (RNG.flipCoin(1/(double)x1.length)) { if (RNG.flipCoin(1 / (double) x1.length)) {
result[i] = 0.01*RNG.gaussianDouble(0.1); result[i] = 0.01 * RNG.gaussianDouble(0.1);
} } else {
else {
result[i] = 0; result[i] = 0;
} }
isEmpty = (isEmpty && (result[i]==0)); isEmpty = (isEmpty && (result[i] == 0));
} }
// single parent! dont add another one // single parent! dont add another one
} }
@@ -191,13 +192,13 @@ public class DifferentialEvolution implements InterfaceOptimizer, java.io.Serial
} }
/** /**
* This method returns a difference vector between two random individuals from the population. * This method returns a difference vector between two random individuals
* This method should make sure that delta is not zero. * from the population. This method should make sure that delta is not zero.
* *
* @param pop The population to choose from * @param pop The population to choose from
* @return The delta vector * @return The delta vector
*/ */
private double[] fetchDeltaCurrentRandom(Population pop,InterfaceDataTypeDouble indy) { private double[] fetchDeltaCurrentRandom(Population pop, InterfaceDataTypeDouble indy) {
double[] x1, x2; double[] x1, x2;
double[] result; double[] result;
boolean isEmpty; boolean isEmpty;
@@ -208,7 +209,7 @@ public class DifferentialEvolution implements InterfaceOptimizer, java.io.Serial
if (parents != null) { if (parents != null) {
parents.add((AbstractEAIndividual)indy); parents.add((AbstractEAIndividual) indy);
} }
result = new double[x1.length]; result = new double[x1.length];
@@ -220,7 +221,7 @@ public class DifferentialEvolution implements InterfaceOptimizer, java.io.Serial
for (int i = 0; i < x1.length; i++) { for (int i = 0; i < x1.length; i++) {
result[i] = x1[i] - x2[i]; result[i] = x1[i] - x2[i];
isEmpty = (isEmpty && (result[i]==0)); isEmpty = (isEmpty && (result[i] == 0));
} }
iterations++; iterations++;
} }
@@ -232,13 +233,12 @@ public class DifferentialEvolution implements InterfaceOptimizer, java.io.Serial
// for n (popSize) iterations there were only zero vectors found // for n (popSize) iterations there were only zero vectors found
// so now the hard way: construct a random vector // so now the hard way: construct a random vector
for (int i = 0; i < x1.length; i++) { for (int i = 0; i < x1.length; i++) {
if (RNG.flipCoin(1/(double)x1.length)) { if (RNG.flipCoin(1 / (double) x1.length)) {
result[i] = 0.01*RNG.gaussianDouble(0.1); result[i] = 0.01 * RNG.gaussianDouble(0.1);
} } else {
else {
result[i] = 0; result[i] = 0;
} }
isEmpty = (isEmpty && (result[i]==0)); isEmpty = (isEmpty && (result[i] == 0));
} }
// single parent! dont add another one // single parent! dont add another one
} }
@@ -261,7 +261,7 @@ public class DifferentialEvolution implements InterfaceOptimizer, java.io.Serial
result = new double[x1.length]; result = new double[x1.length];
if (m_Problem instanceof AbstractMultiObjectiveOptimizationProblem) { if (m_Problem instanceof AbstractMultiObjectiveOptimizationProblem) {
// implements MODE for the multi-objective case: a dominating individual is selected for difference building // implements MODE for the multi-objective case: a dominating individual is selected for difference building
Population domSet = pop.getDominatingSet((AbstractEAIndividual)indy); Population domSet = pop.getDominatingSet((AbstractEAIndividual) indy);
if (domSet.size() > 0) { if (domSet.size() > 0) {
xbIndy = getRandomIndy(domSet); xbIndy = getRandomIndy(domSet);
} else { } else {
@@ -283,7 +283,9 @@ public class DifferentialEvolution implements InterfaceOptimizer, java.io.Serial
return result; return result;
} }
/** This method returns two parents to the original individual /**
* This method returns two parents to the original individual
*
* @param pop The population to choose from * @param pop The population to choose from
* @return the delta vector * @return the delta vector
*/ */
@@ -301,8 +303,9 @@ public class DifferentialEvolution implements InterfaceOptimizer, java.io.Serial
// result[1] = indy2.getDGenotype(); // result[1] = indy2.getDGenotype();
// return result; // return result;
// } // }
/**
/** This method will generate one new individual from the given population * This method will generate one new individual from the given population
*
* @param pop The current population * @param pop The current population
* @return AbstractEAIndividual * @return AbstractEAIndividual
*/ */
@@ -313,17 +316,16 @@ public class DifferentialEvolution implements InterfaceOptimizer, java.io.Serial
if (doLogParents) { if (doLogParents) {
parents = new Vector<AbstractEAIndividual>(); parents = new Vector<AbstractEAIndividual>();
} } else {
else {
parents = null; parents = null;
} }
try { try {
// select one random indy as starting individual. its a parent in any case. // select one random indy as starting individual. its a parent in any case.
if (parentIndex<0) { if (parentIndex < 0) {
parentIndex = RNG.randomInt(0, pop.size()-1); parentIndex = RNG.randomInt(0, pop.size() - 1);
} }
indy = (AbstractEAIndividual)(pop.getEAIndividual(parentIndex)).getClone(); indy = (AbstractEAIndividual) (pop.getEAIndividual(parentIndex)).getClone();
esIndy = (InterfaceDataTypeDouble)indy; esIndy = (InterfaceDataTypeDouble) indy;
} catch (java.lang.ClassCastException e) { } catch (java.lang.ClassCastException e) {
throw new RuntimeException("Differential Evolution currently requires InterfaceESIndividual as basic data type!"); throw new RuntimeException("Differential Evolution currently requires InterfaceESIndividual as basic data type!");
// return (AbstractEAIndividual)((AbstractEAIndividual)pop.get(RNG.randomInt(0, pop.size()-1))).getClone(); // return (AbstractEAIndividual)((AbstractEAIndividual)pop.get(RNG.randomInt(0, pop.size()-1))).getClone();
@@ -340,11 +342,11 @@ public class DifferentialEvolution implements InterfaceOptimizer, java.io.Serial
parents.add(pop.getEAIndividual(parentIndex)); parents.add(pop.getEAIndividual(parentIndex));
} // Add wherever oX is used directly } // Add wherever oX is used directly
for (int i = 0; i < oX.length; i++) { for (int i = 0; i < oX.length; i++) {
vX[i] = oX[i] + this.getCurrentF()*delta[i]; vX[i] = oX[i] + this.getCurrentF() * delta[i];
} }
break; break;
} }
case DE_CurrentToRand : { case DE_CurrentToRand: {
// this is DE/current-to-rand/1 // this is DE/current-to-rand/1
double[] rndDelta = this.fetchDeltaRandom(pop); double[] rndDelta = this.fetchDeltaRandom(pop);
double[] bestDelta = this.fetchDeltaCurrentRandom(pop, esIndy); double[] bestDelta = this.fetchDeltaCurrentRandom(pop, esIndy);
@@ -356,7 +358,7 @@ public class DifferentialEvolution implements InterfaceOptimizer, java.io.Serial
} }
break; break;
} }
case DE2_CurrentToBest : { case DE2_CurrentToBest: {
// this is DE2 or DE/current-to-best/1 // this is DE2 or DE/current-to-best/1
double[] rndDelta = this.fetchDeltaRandom(pop); double[] rndDelta = this.fetchDeltaRandom(pop);
double[] bestDelta = this.fetchDeltaBest(pop, esIndy); double[] bestDelta = this.fetchDeltaBest(pop, esIndy);
@@ -382,7 +384,7 @@ public class DifferentialEvolution implements InterfaceOptimizer, java.io.Serial
} }
break; break;
} }
case TrigonometricDE : { case TrigonometricDE: {
// this is trigonometric mutation // this is trigonometric mutation
if (parents != null) { if (parents != null) {
parents.add(pop.getEAIndividual(parentIndex)); parents.add(pop.getEAIndividual(parentIndex));
@@ -393,23 +395,23 @@ public class DifferentialEvolution implements InterfaceOptimizer, java.io.Serial
InterfaceDataTypeDouble indy1 = null, indy2 = null; InterfaceDataTypeDouble indy1 = null, indy2 = null;
try { try {
// and i got indy! // and i got indy!
indy1 = (InterfaceDataTypeDouble)pop.get(RNG.randomInt(0, pop.size()-1)); indy1 = (InterfaceDataTypeDouble) pop.get(RNG.randomInt(0, pop.size() - 1));
indy2 = (InterfaceDataTypeDouble)pop.get(RNG.randomInt(0, pop.size()-1)); indy2 = (InterfaceDataTypeDouble) pop.get(RNG.randomInt(0, pop.size() - 1));
if (parents != null) { if (parents != null) {
parents.add((AbstractEAIndividual)indy1); parents.add((AbstractEAIndividual) indy1);
parents.add((AbstractEAIndividual)indy2); parents.add((AbstractEAIndividual) indy2);
} }
} catch (java.lang.ClassCastException e) { } catch (java.lang.ClassCastException e) {
EVAERROR.errorMsgOnce("Differential Evolution currently requires InterfaceESIndividual as basic data type!"); EVAERROR.errorMsgOnce("Differential Evolution currently requires InterfaceESIndividual as basic data type!");
} }
xk = indy1.getDoubleData(); xk = indy1.getDoubleData();
xl = indy2.getDoubleData(); xl = indy2.getDoubleData();
p = Math.abs(((AbstractEAIndividual)esIndy).getFitness(0)) + Math.abs(((AbstractEAIndividual)indy1).getFitness(0)) + Math.abs(((AbstractEAIndividual)indy2).getFitness(0)); p = Math.abs(((AbstractEAIndividual) esIndy).getFitness(0)) + Math.abs(((AbstractEAIndividual) indy1).getFitness(0)) + Math.abs(((AbstractEAIndividual) indy2).getFitness(0));
pj = Math.abs(((AbstractEAIndividual)esIndy).getFitness(0))/p; pj = Math.abs(((AbstractEAIndividual) esIndy).getFitness(0)) / p;
pk = Math.abs(((AbstractEAIndividual)indy1).getFitness(0))/p; pk = Math.abs(((AbstractEAIndividual) indy1).getFitness(0)) / p;
pl = Math.abs(((AbstractEAIndividual)indy2).getFitness(0))/p; pl = Math.abs(((AbstractEAIndividual) indy2).getFitness(0)) / p;
for (int i = 0; i < oX.length; i++) { for (int i = 0; i < oX.length; i++) {
vX[i] = (oX[i] + xk[i] + xl[i])/3.0 + ((pk-pj)*(oX[i]-xk[i])) + ((pl-pk)*(xk[i]-xl[i])) + ((pj-pl)*(xl[i]-oX[i])); vX[i] = (oX[i] + xk[i] + xl[i]) / 3.0 + ((pk - pj) * (oX[i] - xk[i])) + ((pl - pk) * (xk[i] - xl[i])) + ((pj - pl) * (xl[i] - oX[i]));
} }
} else { } else {
// this is DE1 // this is DE1
@@ -418,15 +420,15 @@ public class DifferentialEvolution implements InterfaceOptimizer, java.io.Serial
parents.add(pop.getEAIndividual(parentIndex)); parents.add(pop.getEAIndividual(parentIndex));
} // Add wherever oX is used directly } // Add wherever oX is used directly
for (int i = 0; i < oX.length; i++) { for (int i = 0; i < oX.length; i++) {
vX[i] = oX[i] + this.getCurrentF()*delta[i]; vX[i] = oX[i] + this.getCurrentF() * delta[i];
} }
} }
break; break;
} }
} }
int k=RNG.randomInt(oX.length); // at least one position is changed int k = RNG.randomInt(oX.length); // at least one position is changed
for (int i =0; i < oX.length; i++) { for (int i = 0; i < oX.length; i++) {
if ((i==k) || RNG.flipCoin(this.getCurrentK())) { if ((i == k) || RNG.flipCoin(this.getCurrentK())) {
// it is altered // it is altered
nX[i] = vX[i]; nX[i] = vX[i];
} else { } else {
@@ -452,48 +454,45 @@ public class DifferentialEvolution implements InterfaceOptimizer, java.io.Serial
private double getCurrentK() { private double getCurrentK() {
if (randomizeFKLambda) { if (randomizeFKLambda) {
return RNG.randomDouble(m_k*0.8, m_k * 1.2); return RNG.randomDouble(m_k * 0.8, m_k * 1.2);
} } else {
else {
return m_k; return m_k;
} }
} }
private double getCurrentLambda() { private double getCurrentLambda() {
if (randomizeFKLambda) { if (randomizeFKLambda) {
return RNG.randomDouble(m_Lambda*0.8, m_Lambda * 1.2); return RNG.randomDouble(m_Lambda * 0.8, m_Lambda * 1.2);
} } else {
else {
return m_Lambda; return m_Lambda;
} }
} }
private double getCurrentF() { private double getCurrentF() {
if (randomizeFKLambda) { if (randomizeFKLambda) {
return RNG.randomDouble(m_F*0.8, m_F * 1.2); return RNG.randomDouble(m_F * 0.8, m_F * 1.2);
} } else {
else {
return m_F; return m_F;
} }
} }
private AbstractEAIndividual getBestIndy(Population pop) { private AbstractEAIndividual getBestIndy(Population pop) {
return (AbstractEAIndividual)pop.getBestIndividual(); return (AbstractEAIndividual) pop.getBestIndividual();
} }
private AbstractEAIndividual getRandomIndy(Population pop) { private AbstractEAIndividual getRandomIndy(Population pop) {
if (pop.size()<1) { if (pop.size() < 1) {
System.err.println("Error: invalid pop size in DE!"); System.err.println("Error: invalid pop size in DE!");
System.err.println("DE: \n"+ BeanInspector.toString(this) + "\nPop: \n" + BeanInspector.toString(pop)); System.err.println("DE: \n" + BeanInspector.toString(this) + "\nPop: \n" + BeanInspector.toString(pop));
} }
int randIndex = RNG.randomInt(0, pop.size()-1); int randIndex = RNG.randomInt(0, pop.size() - 1);
return pop.getEAIndividual(randIndex); return pop.getEAIndividual(randIndex);
} }
private double[] getGenotype(AbstractEAIndividual indy) { private double[] getGenotype(AbstractEAIndividual indy) {
try { try {
return ((InterfaceDataTypeDouble)indy).getDoubleData(); return ((InterfaceDataTypeDouble) indy).getDoubleData();
} catch (java.lang.ClassCastException e) { } catch (java.lang.ClassCastException e) {
EVAERROR.errorMsgOnce("Differential Evolution currently requires InterfaceESIndividual as basic data type!"); EVAERROR.errorMsgOnce("Differential Evolution currently requires InterfaceESIndividual as basic data type!");
return null; return null;
@@ -504,16 +503,16 @@ public class DifferentialEvolution implements InterfaceOptimizer, java.io.Serial
public void optimize() { public void optimize() {
if (generational) { if (generational) {
optimizeGenerational(); optimizeGenerational();
} } else {
else {
optimizeSteadyState(); optimizeSteadyState();
} }
} }
/** /**
* This generational DE variant calls the method AbstractOptimizationProblem.evaluate(Population). * This generational DE variant calls the method
* Its performance may be slightly worse for schemes that rely on current best individuals, * AbstractOptimizationProblem.evaluate(Population). Its performance may be
* because improvements are not immediately incorporated as in the steady state DE. * slightly worse for schemes that rely on current best individuals, because
* improvements are not immediately incorporated as in the steady state DE.
* However it may be easier to parallelize. * However it may be easier to parallelize.
* *
*/ */
@@ -522,18 +521,16 @@ public class DifferentialEvolution implements InterfaceOptimizer, java.io.Serial
int parentIndex; int parentIndex;
// required for dynamic problems especially // required for dynamic problems especially
// m_Problem.evaluatePopulationStart(m_Population); // m_Problem.evaluatePopulationStart(m_Population);
if (children==null) { if (children == null) {
children = new Population(m_Population.size()); children = new Population(m_Population.size());
} } else {
else {
children.clear(); children.clear();
} }
for (int i = 0; i < this.m_Population.size(); i++) { for (int i = 0; i < this.m_Population.size(); i++) {
if (cyclePop) { if (cyclePop) {
parentIndex=i; parentIndex = i;
} } else {
else { parentIndex = RNG.randomInt(0, this.m_Population.size() - 1);
parentIndex=RNG.randomInt(0, this.m_Population.size()-1);
} }
AbstractEAIndividual indy = generateNewIndividual(m_Population, parentIndex); AbstractEAIndividual indy = generateNewIndividual(m_Population, parentIndex);
children.add(indy); children.add(indy);
@@ -543,14 +540,15 @@ public class DifferentialEvolution implements InterfaceOptimizer, java.io.Serial
m_Problem.evaluate(children); m_Problem.evaluate(children);
/** /**
* MdP: added a reevalutation mechanism for dynamically changing problems * MdP: added a reevalutation mechanism for dynamically changing
* problems
*/ */
if(isReEvaluate()){ if (isReEvaluate()) {
for(int i=0;i<this.m_Population.size();i++){ for (int i = 0; i < this.m_Population.size(); i++) {
if (((AbstractEAIndividual)m_Population.get(i)).getAge() >= maximumAge) { if (((AbstractEAIndividual) m_Population.get(i)).getAge() >= maximumAge) {
this.m_Problem.evaluate(((AbstractEAIndividual)m_Population.get(i))); this.m_Problem.evaluate(((AbstractEAIndividual) m_Population.get(i)));
((AbstractEAIndividual)m_Population.get(i)).SetAge(0); ((AbstractEAIndividual) m_Population.get(i)).SetAge(0);
m_Population.incrFunctionCalls(); m_Population.incrFunctionCalls();
} }
} }
@@ -560,24 +558,23 @@ public class DifferentialEvolution implements InterfaceOptimizer, java.io.Serial
for (int i = 0; i < this.m_Population.size(); i++) { for (int i = 0; i < this.m_Population.size(); i++) {
AbstractEAIndividual indy = children.getEAIndividual(i); AbstractEAIndividual indy = children.getEAIndividual(i);
if (cyclePop) { if (cyclePop) {
parentIndex=i; parentIndex = i;
} } else {
else { parentIndex = RNG.randomInt(0, this.m_Population.size() - 1);
parentIndex=RNG.randomInt(0, this.m_Population.size()-1);
} }
if (nextDoomed >= 0) { // this one is lucky, may replace an 'old' one if (nextDoomed >= 0) { // this one is lucky, may replace an 'old' one
m_Population.replaceIndividualAt(nextDoomed, indy); m_Population.replaceIndividualAt(nextDoomed, indy);
nextDoomed = getNextDoomed(m_Population, nextDoomed+1); nextDoomed = getNextDoomed(m_Population, nextDoomed + 1);
} else { } else {
if (m_Problem instanceof AbstractMultiObjectiveOptimizationProblem&indy.getFitness().length>1) { if (m_Problem instanceof AbstractMultiObjectiveOptimizationProblem & indy.getFitness().length > 1) {
ReplacementCrowding repl = new ReplacementCrowding(); ReplacementCrowding repl = new ReplacementCrowding();
repl.insertIndividual(indy, m_Population, null); repl.insertIndividual(indy, m_Population, null);
} else { } else {
// index = RNG.randomInt(0, this.m_Population.size()-1); // index = RNG.randomInt(0, this.m_Population.size()-1);
if (!compareToParent) { if (!compareToParent) {
parentIndex = RNG.randomInt(0, this.m_Population.size()-1); parentIndex = RNG.randomInt(0, this.m_Population.size() - 1);
} }
AbstractEAIndividual orig = (AbstractEAIndividual)this.m_Population.get(parentIndex); AbstractEAIndividual orig = (AbstractEAIndividual) this.m_Population.get(parentIndex);
if (indy.isDominatingDebConstraints(orig)) { if (indy.isDominatingDebConstraints(orig)) {
this.m_Population.replaceIndividualAt(parentIndex, indy); this.m_Population.replaceIndividualAt(parentIndex, indy);
} }
@@ -600,15 +597,16 @@ public class DifferentialEvolution implements InterfaceOptimizer, java.io.Serial
/** /**
* MdP: added a reevalutation mechanism for dynamically changing problems * MdP: added a reevalutation mechanism for dynamically changing
* problems
*/ */
if(isReEvaluate()){ if (isReEvaluate()) {
nextDoomed=-1; nextDoomed = -1;
for(int i=0;i<this.m_Population.size();i++){ for (int i = 0; i < this.m_Population.size(); i++) {
if (((AbstractEAIndividual)m_Population.get(i)).getAge() >= maximumAge) { if (((AbstractEAIndividual) m_Population.get(i)).getAge() >= maximumAge) {
this.m_Problem.evaluate(((AbstractEAIndividual)m_Population.get(i))); this.m_Problem.evaluate(((AbstractEAIndividual) m_Population.get(i)));
((AbstractEAIndividual)m_Population.get(i)).SetAge(0); ((AbstractEAIndividual) m_Population.get(i)).SetAge(0);
m_Population.incrFunctionCalls(); m_Population.incrFunctionCalls();
} }
} }
@@ -617,10 +615,9 @@ public class DifferentialEvolution implements InterfaceOptimizer, java.io.Serial
for (int i = 0; i < this.m_Population.size(); i++) { for (int i = 0; i < this.m_Population.size(); i++) {
if (cyclePop) { if (cyclePop) {
index=i; index = i;
} } else {
else { index = RNG.randomInt(0, this.m_Population.size() - 1);
index=RNG.randomInt(0, this.m_Population.size()-1);
} }
indy = generateNewIndividual(m_Population, index); indy = generateNewIndividual(m_Population, index);
// if (cyclePop) indy = this.generateNewIndividual(this.m_Population, i); // if (cyclePop) indy = this.generateNewIndividual(this.m_Population, i);
@@ -629,14 +626,14 @@ public class DifferentialEvolution implements InterfaceOptimizer, java.io.Serial
this.m_Population.incrFunctionCalls(); this.m_Population.incrFunctionCalls();
if (nextDoomed >= 0) { // this one is lucky, may replace an 'old' one if (nextDoomed >= 0) { // this one is lucky, may replace an 'old' one
m_Population.replaceIndividualAt(nextDoomed, indy); m_Population.replaceIndividualAt(nextDoomed, indy);
nextDoomed = getNextDoomed(m_Population, nextDoomed+1); nextDoomed = getNextDoomed(m_Population, nextDoomed + 1);
} else { } else {
if (m_Problem instanceof AbstractMultiObjectiveOptimizationProblem) { if (m_Problem instanceof AbstractMultiObjectiveOptimizationProblem) {
if(indy.isDominatingDebConstraints(m_Population.getEAIndividual(index))){ //child dominates the parent replace the parent if (indy.isDominatingDebConstraints(m_Population.getEAIndividual(index))) { //child dominates the parent replace the parent
m_Population.replaceIndividualAt(index, indy); m_Population.replaceIndividualAt(index, indy);
}else if(!(m_Population.getEAIndividual(index).isDominatingDebConstraints(indy))){ //do nothing if parent dominates the child use crowding if neither one dominates the other one } else if (!(m_Population.getEAIndividual(index).isDominatingDebConstraints(indy))) { //do nothing if parent dominates the child use crowding if neither one dominates the other one
ReplacementNondominatedSortingDistanceCrowding repl =new ReplacementNondominatedSortingDistanceCrowding(); ReplacementNondominatedSortingDistanceCrowding repl = new ReplacementNondominatedSortingDistanceCrowding();
repl.insertIndividual(indy, m_Population, null); repl.insertIndividual(indy, m_Population, null);
} }
// ReplacementCrowding repl = new ReplacementCrowding(); // ReplacementCrowding repl = new ReplacementCrowding();
@@ -646,9 +643,9 @@ public class DifferentialEvolution implements InterfaceOptimizer, java.io.Serial
} else { } else {
// index = RNG.randomInt(0, this.m_Population.size()-1); // index = RNG.randomInt(0, this.m_Population.size()-1);
if (!compareToParent) { if (!compareToParent) {
index = RNG.randomInt(0, this.m_Population.size()-1); index = RNG.randomInt(0, this.m_Population.size() - 1);
} }
orig = (AbstractEAIndividual)this.m_Population.get(index); orig = (AbstractEAIndividual) this.m_Population.get(index);
if (indy.isDominatingDebConstraints(orig)) { if (indy.isDominatingDebConstraints(orig)) {
this.m_Population.replaceIndividualAt(index, indy); this.m_Population.replaceIndividualAt(index, indy);
} }
@@ -699,9 +696,10 @@ public class DifferentialEvolution implements InterfaceOptimizer, java.io.Serial
} }
/** /**
* Search for the first individual which is older than the age limit and return its index. * Search for the first individual which is older than the age limit and
* If there is no age limit or all individuals are younger, -1 is returned. The start index * return its index. If there is no age limit or all individuals are
* of the search may be provided to make iterative search efficient. * younger, -1 is returned. The start index of the search may be provided to
* make iterative search efficient.
* *
* @param pop Population to search * @param pop Population to search
* @param startIndex index to start the search from * @param startIndex index to start the search from
@@ -709,8 +707,8 @@ public class DifferentialEvolution implements InterfaceOptimizer, java.io.Serial
*/ */
protected int getNextDoomed(Population pop, int startIndex) { protected int getNextDoomed(Population pop, int startIndex) {
if (maximumAge > 0) { if (maximumAge > 0) {
for (int i=startIndex; i<pop.size(); i++) { for (int i = startIndex; i < pop.size(); i++) {
if (((AbstractEAIndividual)pop.get(i)).getAge() >= maximumAge) { if (((AbstractEAIndividual) pop.get(i)).getAge() >= maximumAge) {
return i; return i;
} }
} }
@@ -718,51 +716,62 @@ public class DifferentialEvolution implements InterfaceOptimizer, java.io.Serial
return -1; return -1;
} }
/** 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 * @param ea
*/ */
@Override @Override
public void addPopulationChangedEventListener(InterfacePopulationChangedEventListener ea) { public void addPopulationChangedEventListener(InterfacePopulationChangedEventListener ea) {
if(this.m_Listener ==null){ if (this.m_Listener == null) {
this.m_Listener=new Vector<InterfacePopulationChangedEventListener>(); this.m_Listener = new Vector<InterfacePopulationChangedEventListener>();
} }
this.m_Listener.add(ea); this.m_Listener.add(ea);
} }
@Override @Override
public boolean removePopulationChangedEventListener( public boolean removePopulationChangedEventListener(
InterfacePopulationChangedEventListener ea) { InterfacePopulationChangedEventListener ea) {
if (m_Listener!=null&&m_Listener.removeElement(ea)) { if (m_Listener != null && m_Listener.removeElement(ea)) {
return true; return true;
} else { } else {
return false; return false;
} }
} }
/** Something has changed
/**
* Something has changed
*
* @param name * @param name
*/ */
protected void firePropertyChangedEvent (String name) { protected void firePropertyChangedEvent(String name) {
if (this.m_Listener != null){ if (this.m_Listener != null) {
for(int i=0;i<this.m_Listener.size();i++){ for (int i = 0; i < this.m_Listener.size(); i++) {
this.m_Listener.get(i).registerPopulationStateChanged(this, name); this.m_Listener.get(i).registerPopulationStateChanged(this, name);
} }
} }
} }
/** This method will set the problem that is to be optimized /**
* This method will set the problem that is to be optimized
*
* @param problem * @param problem
*/ */
@Override @Override
public void setProblem (InterfaceOptimizationProblem problem) { public void setProblem(InterfaceOptimizationProblem problem) {
this.m_Problem = (AbstractOptimizationProblem)problem; this.m_Problem = (AbstractOptimizationProblem) problem;
}
@Override
public InterfaceOptimizationProblem getProblem () {
return (InterfaceOptimizationProblem)this.m_Problem;
} }
/** This method will return a string describing all properties of the optimizer @Override
* and the applied methods. public InterfaceOptimizationProblem getProblem() {
return (InterfaceOptimizationProblem) this.m_Problem;
}
/**
* This method will return a string describing all properties of the
* optimizer and the applied methods.
*
* @return A descriptive string * @return A descriptive string
*/ */
@Override @Override
@@ -770,39 +779,42 @@ public class DifferentialEvolution implements InterfaceOptimizer, java.io.Serial
String result = ""; String result = "";
result += "Differential Evolution:\n"; result += "Differential Evolution:\n";
result += "Optimization Problem: "; result += "Optimization Problem: ";
result += this.m_Problem.getStringRepresentationForProblem(this) +"\n"; result += this.m_Problem.getStringRepresentationForProblem(this) + "\n";
result += this.m_Population.getStringRepresentation(); result += this.m_Population.getStringRepresentation();
return result; return result;
} }
/** 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 identifier * @param name The identifier
*/ */
@Override @Override
public void setIdentifier(String name) { public void setIdentifier(String name) {
this.m_Identifier = name; this.m_Identifier = name;
} }
@Override @Override
public String getIdentifier() { public String getIdentifier() {
return this.m_Identifier; return this.m_Identifier;
} }
/** This method is required to free the memory on a RMIServer, /**
* but there is nothing to implement. * ********************************************************************************************************************
*/
@Override
public void freeWilly() {
}
/**********************************************************************************************************************
* These are for GUI * These are for GUI
*/ */
/** This method returns a global info string /**
* This method returns a global info string
*
* @return description * @return description
*/ */
public static String globalInfo() { public static String globalInfo() {
return "Differential Evolution using a steady-state population scheme."; return "Differential Evolution using a steady-state population scheme.";
} }
/** This method will return a naming String
/**
* This method will return a naming String
*
* @return The name of the algorithm * @return The name of the algorithm
*/ */
@Override @Override
@@ -810,19 +822,23 @@ public class DifferentialEvolution implements InterfaceOptimizer, java.io.Serial
return "DE"; return "DE";
} }
/** Assuming that all optimizer will store their data in a population /**
* we will allow access to this population to query to current state * Assuming that all optimizer will store their data in a population we will
* of the optimizer. * allow access to this population to query to current state of the
* optimizer.
*
* @return The population of current solutions to a given problem. * @return The population of current solutions to a given problem.
*/ */
@Override @Override
public Population getPopulation() { public Population getPopulation() {
return this.m_Population; return this.m_Population;
} }
@Override @Override
public void setPopulation(Population pop){ public void setPopulation(Population pop) {
this.m_Population = pop; this.m_Population = pop;
} }
public String populationTipText() { public String populationTipText() {
return "Edit the properties of the population used."; return "Edit the properties of the population used.";
} }
@@ -833,20 +849,28 @@ public class DifferentialEvolution implements InterfaceOptimizer, java.io.Serial
return new SolutionSet(pop, pop); return new SolutionSet(pop, pop);
} }
/** F is a real and constant factor which controls the amplification of the differential variation /**
* F is a real and constant factor which controls the amplification of the
* differential variation
*
* @param f * @param f
*/ */
public void setF (double f) { public void setF(double f) {
this.m_F = f; this.m_F = f;
} }
public double getF() { public double getF() {
return this.m_F; return this.m_F;
} }
public String fTipText() { public String fTipText() {
return "F is a real and constant factor which controls the amplification of the differential variation."; return "F is a real and constant factor which controls the amplification of the differential variation.";
} }
/** Probability of alteration through DE (something like a discrete uniform crossover is performed here) /**
* Probability of alteration through DE (something like a discrete uniform
* crossover is performed here)
*
* @param k * @param k
*/ */
public void setK(double k) { public void setK(double k) {
@@ -858,30 +882,39 @@ public class DifferentialEvolution implements InterfaceOptimizer, java.io.Serial
} }
this.m_k = k; this.m_k = k;
} }
public double getK() { public double getK() {
return this.m_k; return this.m_k;
} }
public String kTipText() { public String kTipText() {
return "Probability of alteration through DE (a.k.a. CR, similar to discrete uniform crossover)."; return "Probability of alteration through DE (a.k.a. CR, similar to discrete uniform crossover).";
} }
/** Enhance greediness through amplification of the differential vector to the best individual for DE2 /**
* Enhance greediness through amplification of the differential vector to
* the best individual for DE2
*
* @param l * @param l
*/ */
public void setLambda (double l) { public void setLambda(double l) {
this.m_Lambda = l; this.m_Lambda = l;
} }
public double getLambda() { public double getLambda() {
return this.m_Lambda; return this.m_Lambda;
} }
public String lambdaTipText() { public String lambdaTipText() {
return "Enhance greediness through amplification of the differential vector to the best individual for DE2."; return "Enhance greediness through amplification of the differential vector to the best individual for DE2.";
} }
/** In case of trig. mutation DE, the TMO is applied wit probability Mt /**
* In case of trig. mutation DE, the TMO is applied wit probability Mt
*
* @param l * @param l
*/ */
public void setMt (double l) { public void setMt(double l) {
this.m_Mt = l; this.m_Mt = l;
if (this.m_Mt < 0) { if (this.m_Mt < 0) {
this.m_Mt = 0; this.m_Mt = 0;
@@ -890,39 +923,47 @@ public class DifferentialEvolution implements InterfaceOptimizer, java.io.Serial
this.m_Mt = 1; this.m_Mt = 1;
} }
} }
public double getMt() { public double getMt() {
return this.m_Mt; return this.m_Mt;
} }
public String mtTipText() { public String mtTipText() {
return "In case of trigonometric mutation DE, the TMO is applied with probability Mt."; return "In case of trigonometric mutation DE, the TMO is applied with probability Mt.";
} }
/** This method allows you to choose the type of Differential Evolution. /**
* This method allows you to choose the type of Differential Evolution.
*
* @param s The type. * @param s The type.
*/ */
public void setDEType(DETypeEnum s) { public void setDEType(DETypeEnum s) {
this.m_DEType = s; this.m_DEType = s;
// show mt for trig. DE only // show mt for trig. DE only
GenericObjectEditor.setShowProperty(this.getClass(), "lambda", s==DETypeEnum.DE2_CurrentToBest); GenericObjectEditor.setShowProperty(this.getClass(), "lambda", s == DETypeEnum.DE2_CurrentToBest);
GenericObjectEditor.setShowProperty(this.getClass(), "mt", s==DETypeEnum.TrigonometricDE); GenericObjectEditor.setShowProperty(this.getClass(), "mt", s == DETypeEnum.TrigonometricDE);
} }
public DETypeEnum getDEType() { public DETypeEnum getDEType() {
return this.m_DEType; return this.m_DEType;
} }
public String dETypeTipText() { public String dETypeTipText() {
return "Choose the type of Differential Evolution."; return "Choose the type of Differential Evolution.";
} }
/** /**
* @return the maximumAge * @return the maximumAge
**/ *
*/
public int getMaximumAge() { public int getMaximumAge() {
return maximumAge; return maximumAge;
} }
/** /**
* @param maximumAge the maximumAge to set * @param maximumAge the maximumAge to set
**/ *
*/
public void setMaximumAge(int maximumAge) { public void setMaximumAge(int maximumAge) {
this.maximumAge = maximumAge; this.maximumAge = maximumAge;
} }
@@ -933,6 +974,7 @@ public class DifferentialEvolution implements InterfaceOptimizer, java.io.Serial
/** /**
* Check whether the problem range will be enforced. * Check whether the problem range will be enforced.
*
* @return the forceRange * @return the forceRange
*/ */
public boolean isCheckRange() { public boolean isCheckRange() {
@@ -973,7 +1015,6 @@ public class DifferentialEvolution implements InterfaceOptimizer, java.io.Serial
// public String cyclePopTipText() { // public String cyclePopTipText() {
// return "Use all individuals as parents in cyclic sequence instead of randomly."; // return "Use all individuals as parents in cyclic sequence instead of randomly.";
// } // }
public boolean isCompareToParent() { public boolean isCompareToParent() {
return compareToParent; return compareToParent;
} }
@@ -1012,14 +1053,16 @@ public class DifferentialEvolution implements InterfaceOptimizer, java.io.Serial
/** /**
* @return the maximumAge * @return the maximumAge
**/ *
*/
public boolean isReEvaluate() { public boolean isReEvaluate() {
return reEvaluate; return reEvaluate;
} }
/** /**
* @param maximumAge the maximumAge to set * @param maximumAge the maximumAge to set
**/ *
*/
public void setReEvaluate(boolean reEvaluate) { public void setReEvaluate(boolean reEvaluate) {
this.reEvaluate = reEvaluate; this.reEvaluate = reEvaluate;
} }
@@ -1027,5 +1070,4 @@ public class DifferentialEvolution implements InterfaceOptimizer, java.io.Serial
public String reEvaluateTipText() { public String reEvaluateTipText() {
return "Reeavulates individuals which are older than maximum age instead of discarding them"; return "Reeavulates individuals which are older than maximum age instead of discarding them";
} }
} }

View File

@@ -284,6 +284,8 @@ public class EsDpiNiching implements InterfaceOptimizer, Serializable, Interface
* with the given parameters. If windowLen <= 0, the deactivation mechanism * with the given parameters. If windowLen <= 0, the deactivation mechanism
* is disabled. This provides for semi-sequential niching with DPI-ES * is disabled. This provides for semi-sequential niching with DPI-ES
* *
*
*
* *
* @param threshold * @param threshold
@@ -948,7 +950,8 @@ public class EsDpiNiching implements InterfaceOptimizer, Serializable, Interface
/** /**
* Calculate the dynamic population size, which is the number of individuals * Calculate the dynamic population size, which is the number of individuals
* that are currently "alive" in the peak set. This must be implemented in * that are currently "alive" in the peak set. This must be implemented in
* analogy to {@link #collectPopulationIncGen(Population, EvolutionStrategies[], Population)} * analogy to
* {@link #collectPopulationIncGen(Population, EvolutionStrategies[], Population)}
* *
* @return * @return
*/ */
@@ -1048,10 +1051,6 @@ public class EsDpiNiching implements InterfaceOptimizer, Serializable, Interface
} }
} }
@Override
public void freeWilly() {
}
@Override @Override
public InterfaceSolutionSet getAllSolutions() { public InterfaceSolutionSet getAllSolutions() {
Population peaks = new Population(peakOpts.length); Population peaks = new Population(peakOpts.length);

View File

@@ -12,20 +12,20 @@ import eva2.server.go.populations.SolutionSet;
import eva2.server.go.problems.B1Problem; import eva2.server.go.problems.B1Problem;
import eva2.server.go.problems.InterfaceOptimizationProblem; import eva2.server.go.problems.InterfaceOptimizationProblem;
/** Evolution strategies by Rechenberg and Schwefel, but please remember that /**
* Evolution strategies by Rechenberg and Schwefel, but please remember that
* this only gives the generation strategy and not the coding. But this is the * this only gives the generation strategy and not the coding. But this is the
* only stategy that is able to utilize the 1/5 success rule mutation. Unfortunately, * only stategy that is able to utilize the 1/5 success rule mutation.
* there is a minor problem with the interpretation of the population size in constrast * Unfortunately, there is a minor problem with the interpretation of the
* to the parameters mu and lambda used by Rechenberg and Schwefel. Therefore, i'm * population size in constrast to the parameters mu and lambda used by
* afraid that the interpretation of the population size may be subject to future * Rechenberg and Schwefel. Therefore, i'm afraid that the interpretation of the
* changes. * population size may be subject to future changes. This is a implementation of
* This is a implementation of Evolution Strategies. * Evolution Strategies. Copyright: Copyright (c) 2003 Company: University of
* Copyright: Copyright (c) 2003 * Tuebingen, Computer Architecture
* Company: University of Tuebingen, Computer Architecture *
* @author Felix Streichert * @author Felix Streichert
* @version: $Revision: 307 $ * @version: $Revision: 307 $ $Date: 2007-12-04 14:31:47 +0100 (Tue, 04 Dec
* $Date: 2007-12-04 14:31:47 +0100 (Tue, 04 Dec 2007) $ * 2007) $ $Author: mkron $
* $Author: mkron $
*/ */
public class EvolutionStrategies implements InterfaceOptimizer, java.io.Serializable { public class EvolutionStrategies implements InterfaceOptimizer, java.io.Serializable {
@@ -339,18 +339,9 @@ public class EvolutionStrategies implements InterfaceOptimizer, java.io.Serializ
return this.identifier; return this.identifier;
} }
/**
* This method is required to free the memory on a RMIServer, but there is
* nothing to implement.
*/
@Override
public void freeWilly() {
}
/** /**
* These are for GUI * These are for GUI
*/ */
/** /**
* This method returns a global info string * This method returns a global info string
* *

View File

@@ -10,26 +10,25 @@ import eva2.server.go.populations.SolutionSet;
import eva2.server.go.problems.F1Problem; import eva2.server.go.problems.F1Problem;
import eva2.server.go.problems.InterfaceOptimizationProblem; import eva2.server.go.problems.InterfaceOptimizationProblem;
/** Evolutionary programming by Fogel. Works fine but is actually a quite greedy local search /**
* strategy solely based on mutation. To prevent any confusion, the mutation rate is temporaily * Evolutionary programming by Fogel. Works fine but is actually a quite greedy
* set to 1.0. * local search strategy solely based on mutation. To prevent any confusion, the
* Potential citation: the PhD thesis of David B. Fogel (1992). * mutation rate is temporaily set to 1.0. Potential citation: the PhD thesis of
* David B. Fogel (1992).
*
* Copyright: Copyright (c) 2003 Company: University of Tuebingen, Computer
* Architecture
* *
* Copyright: Copyright (c) 2003
* Company: University of Tuebingen, Computer Architecture
* @author Felix Streichert * @author Felix Streichert
* @version: $Revision: 307 $ * @version: $Revision: 307 $ $Date: 2007-12-04 14:31:47 +0100 (Tue, 04 Dec
* $Date: 2007-12-04 14:31:47 +0100 (Tue, 04 Dec 2007) $ * 2007) $ $Author: mkron $
* $Author: mkron $
*/ */
public class EvolutionaryProgramming implements InterfaceOptimizer, java.io.Serializable { public class EvolutionaryProgramming implements InterfaceOptimizer, java.io.Serializable {
private int m_PopulationSize = 0; private int m_PopulationSize = 0;
private Population m_Population = new Population(); private Population m_Population = new Population();
private InterfaceOptimizationProblem m_Problem = new F1Problem(); private InterfaceOptimizationProblem m_Problem = new F1Problem();
private InterfaceSelection m_EnvironmentSelection = new SelectEPTournaments(); private InterfaceSelection m_EnvironmentSelection = new SelectEPTournaments();
private String m_Identifier = ""; private String m_Identifier = "";
transient private InterfacePopulationChangedEventListener m_Listener; transient private InterfacePopulationChangedEventListener m_Listener;
@@ -37,10 +36,10 @@ public class EvolutionaryProgramming implements InterfaceOptimizer, java.io.Seri
} }
public EvolutionaryProgramming(EvolutionaryProgramming a) { public EvolutionaryProgramming(EvolutionaryProgramming a) {
this.m_Population = (Population)a.m_Population.clone(); this.m_Population = (Population) a.m_Population.clone();
this.m_Problem = (InterfaceOptimizationProblem)a.m_Problem.clone(); this.m_Problem = (InterfaceOptimizationProblem) a.m_Problem.clone();
this.m_Identifier = a.m_Identifier; this.m_Identifier = a.m_Identifier;
this.m_EnvironmentSelection = (InterfaceSelection)a.m_EnvironmentSelection.clone(); this.m_EnvironmentSelection = (InterfaceSelection) a.m_EnvironmentSelection.clone();
} }
@Override @Override
@@ -56,12 +55,14 @@ public class EvolutionaryProgramming implements InterfaceOptimizer, java.io.Seri
this.firePropertyChangedEvent(Population.nextGenerationPerformed); this.firePropertyChangedEvent(Population.nextGenerationPerformed);
} }
/** This method will init the optimizer with a given population /**
* This method will init the optimizer with a given population
*
* @param reset If true the population is reset. * @param reset If true the population is reset.
*/ */
@Override @Override
public void initByPopulation(Population pop, boolean reset) { public void initByPopulation(Population pop, boolean reset) {
this.m_Population = (Population)pop.clone(); this.m_Population = (Population) pop.clone();
if (reset) { if (reset) {
this.m_Population.init(); this.m_Population.init();
this.evaluatePopulation(this.m_Population); this.evaluatePopulation(this.m_Population);
@@ -69,8 +70,9 @@ public class EvolutionaryProgramming implements InterfaceOptimizer, java.io.Seri
} }
} }
/** This method will evaluate the current population using the /**
* given problem. * This method will evaluate the current population using the given problem.
*
* @param population The population that is to be evaluated * @param population The population that is to be evaluated
*/ */
private void evaluatePopulation(Population population) { private void evaluatePopulation(Population population) {
@@ -78,16 +80,17 @@ public class EvolutionaryProgramming implements InterfaceOptimizer, java.io.Seri
population.incrGeneration(); population.incrGeneration();
} }
/** 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.
*/ */
private Population generateChildren() { private Population generateChildren() {
Population result = (Population)this.m_Population.cloneWithoutInds(); Population result = (Population) this.m_Population.cloneWithoutInds();
AbstractEAIndividual mutant; AbstractEAIndividual mutant;
result.clear(); result.clear();
for (int i = 0; i < this.m_Population.size(); i++) { for (int i = 0; i < this.m_Population.size(); i++) {
mutant = (AbstractEAIndividual)((AbstractEAIndividual)this.m_Population.get(i)).clone(); mutant = (AbstractEAIndividual) ((AbstractEAIndividual) this.m_Population.get(i)).clone();
double tmpD = mutant.getMutationProbability(); double tmpD = mutant.getMutationProbability();
mutant.setMutationProbability(1.0); mutant.setMutationProbability(1.0);
mutant.mutate(); mutant.mutate();
@@ -113,45 +116,55 @@ public class EvolutionaryProgramming implements InterfaceOptimizer, java.io.Seri
this.firePropertyChangedEvent(Population.nextGenerationPerformed); this.firePropertyChangedEvent(Population.nextGenerationPerformed);
} }
/** 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 * @param ea
*/ */
@Override @Override
public void addPopulationChangedEventListener(InterfacePopulationChangedEventListener ea) { public void addPopulationChangedEventListener(InterfacePopulationChangedEventListener ea) {
this.m_Listener = ea; this.m_Listener = ea;
} }
@Override @Override
public boolean removePopulationChangedEventListener( public boolean removePopulationChangedEventListener(
InterfacePopulationChangedEventListener ea) { InterfacePopulationChangedEventListener ea) {
if (m_Listener==ea) { if (m_Listener == ea) {
m_Listener=null; m_Listener = null;
return true; return true;
} else { } else {
return false; return false;
} }
} }
/** Something has changed
/**
* Something has changed
*/ */
protected void firePropertyChangedEvent (String name) { protected void firePropertyChangedEvent(String name) {
if (this.m_Listener != null) { if (this.m_Listener != null) {
this.m_Listener.registerPopulationStateChanged(this, name); this.m_Listener.registerPopulationStateChanged(this, name);
} }
} }
/** This method will set the problem that is to be optimized /**
* This method will set the problem that is to be optimized
*
* @param problem * @param problem
*/ */
@Override @Override
public void setProblem (InterfaceOptimizationProblem problem) { public void setProblem(InterfaceOptimizationProblem problem) {
this.m_Problem = problem; this.m_Problem = problem;
} }
@Override @Override
public InterfaceOptimizationProblem getProblem () { public InterfaceOptimizationProblem getProblem() {
return this.m_Problem; return this.m_Problem;
} }
/** This method will return a string describing all properties of the optimizer /**
* and the applied methods. * This method will return a string describing all properties of the
* optimizer and the applied methods.
*
* @return A descriptive string * @return A descriptive string
*/ */
@Override @Override
@@ -159,39 +172,42 @@ public class EvolutionaryProgramming implements InterfaceOptimizer, java.io.Seri
String result = ""; String result = "";
result += "Evolutionary Programming:\n"; result += "Evolutionary Programming:\n";
result += "Optimization Problem: "; result += "Optimization Problem: ";
result += this.m_Problem.getStringRepresentationForProblem(this) +"\n"; result += this.m_Problem.getStringRepresentationForProblem(this) + "\n";
result += this.m_Population.getStringRepresentation(); result += this.m_Population.getStringRepresentation();
return result; return result;
} }
/** 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 * @param name The indenifier
*/ */
@Override @Override
public void setIdentifier(String name) { public void setIdentifier(String name) {
this.m_Identifier = name; this.m_Identifier = name;
} }
@Override @Override
public String getIdentifier() { public String getIdentifier() {
return this.m_Identifier; return this.m_Identifier;
} }
/** This method is required to free the memory on a RMIServer, /**
* but there is nothing to implement. * ********************************************************************************************************************
*/
@Override
public void freeWilly() {
}
/**********************************************************************************************************************
* These are for GUI * These are for GUI
*/ */
/** This method returns a global info string /**
* This method returns a global info string
*
* @return description * @return description
*/ */
public static String globalInfo() { public static String globalInfo() {
return "This is a basic Evolutionary Programming scheme."; return "This is a basic Evolutionary Programming scheme.";
} }
/** This method will return a naming String
/**
* This method will return a naming String
*
* @return The name of the algorithm * @return The name of the algorithm
*/ */
@Override @Override
@@ -199,19 +215,23 @@ public class EvolutionaryProgramming implements InterfaceOptimizer, java.io.Seri
return "EP"; return "EP";
} }
/** Assuming that all optimizer will store thier data in a population /**
* we will allow acess to this population to query to current state * Assuming that all optimizer will store thier data in a population we will
* of the optimizer. * allow acess to this population to query to current state of the
* optimizer.
*
* @return The population of current solutions to a given problem. * @return The population of current solutions to a given problem.
*/ */
@Override @Override
public Population getPopulation() { public Population getPopulation() {
return this.m_Population; return this.m_Population;
} }
@Override @Override
public void setPopulation(Population pop){ public void setPopulation(Population pop) {
this.m_Population = pop; this.m_Population = pop;
} }
public String populationTipText() { public String populationTipText() {
return "Edit the properties of the population used."; return "Edit the properties of the population used.";
} }
@@ -220,15 +240,20 @@ public class EvolutionaryProgramming implements InterfaceOptimizer, java.io.Seri
public InterfaceSolutionSet getAllSolutions() { public InterfaceSolutionSet getAllSolutions() {
return new SolutionSet(getPopulation()); return new SolutionSet(getPopulation());
} }
/** Choose a method for selecting the reduced population.
/**
* Choose a method for selecting the reduced population.
*
* @param selection * @param selection
*/ */
public void setEnvironmentSelection(InterfaceSelection selection) { public void setEnvironmentSelection(InterfaceSelection selection) {
this.m_EnvironmentSelection = selection; this.m_EnvironmentSelection = selection;
} }
public InterfaceSelection getEnvironmentSelection() { public InterfaceSelection getEnvironmentSelection() {
return this.m_EnvironmentSelection; return this.m_EnvironmentSelection;
} }
public String environmentSelectionTipText() { public String environmentSelectionTipText() {
return "Choose a method for selecting the reduced population."; return "Choose a method for selecting the reduced population.";
} }

View File

@@ -9,21 +9,20 @@ import eva2.server.go.populations.SolutionSet;
import eva2.server.go.problems.B1Problem; import eva2.server.go.problems.B1Problem;
import eva2.server.go.problems.InterfaceOptimizationProblem; import eva2.server.go.problems.InterfaceOptimizationProblem;
/** The flood algorithm, and alternative to the threshold algorithms. No really /**
* good but commonly known and sometimes even used. Here the problem is to choose * The flood algorithm, and alternative to the threshold algorithms. No really
* the initial flood peak and the drain rate such that it fits the current optimization * good but commonly known and sometimes even used. Here the problem is to
* problem. But again this is a greedy local search strategy. Similar to the * choose the initial flood peak and the drain rate such that it fits the
* evolutionary programming strategy this strategy sets the mutation rate temporarily * current optimization problem. But again this is a greedy local search
* to 1.0. * strategy. Similar to the evolutionary programming strategy this strategy sets
* The algorithm regards only one-dimensional fitness. * the mutation rate temporarily to 1.0. The algorithm regards only
* Created by IntelliJ IDEA. * one-dimensional fitness. Created by IntelliJ IDEA. User: streiche Date:
* User: streiche * 01.10.2004 Time: 13:46:02 To change this template use File | Settings | File
* Date: 01.10.2004 * Templates.
* Time: 13:46:02
* To change this template use File | Settings | File Templates.
*/ */
public class FloodAlgorithm implements InterfaceOptimizer, java.io.Serializable { public class FloodAlgorithm implements InterfaceOptimizer, java.io.Serializable {
// These variables are necessary for the simple testcase // These variables are necessary for the simple testcase
private InterfaceOptimizationProblem m_Problem = new B1Problem(); private InterfaceOptimizationProblem m_Problem = new B1Problem();
private int m_MultiRuns = 100; private int m_MultiRuns = 100;
private int m_FitnessCalls = 100; private int m_FitnessCalls = 100;
@@ -31,7 +30,6 @@ public class FloodAlgorithm implements InterfaceOptimizer, java.io.Serializable
GAIndividualBinaryData m_Best, m_Test; GAIndividualBinaryData m_Best, m_Test;
public double m_InitialFloodPeak = 2000.0, m_CurrentFloodPeak; public double m_InitialFloodPeak = 2000.0, m_CurrentFloodPeak;
public double m_DrainRate = 1.0; public double m_DrainRate = 1.0;
// These variables are necessary for the more complex LectureGUI enviroment // These variables are necessary for the more complex LectureGUI enviroment
transient private String m_Identifier = ""; transient private String m_Identifier = "";
transient private InterfacePopulationChangedEventListener m_Listener; transient private InterfacePopulationChangedEventListener m_Listener;
@@ -43,8 +41,8 @@ public class FloodAlgorithm implements InterfaceOptimizer, java.io.Serializable
} }
public FloodAlgorithm(FloodAlgorithm a) { public FloodAlgorithm(FloodAlgorithm a) {
this.m_Population = (Population)a.m_Population.clone(); this.m_Population = (Population) a.m_Population.clone();
this.m_Problem = (InterfaceOptimizationProblem)a.m_Problem.clone(); this.m_Problem = (InterfaceOptimizationProblem) a.m_Problem.clone();
this.m_InitialFloodPeak = a.m_InitialFloodPeak; this.m_InitialFloodPeak = a.m_InitialFloodPeak;
this.m_DrainRate = a.m_DrainRate; this.m_DrainRate = a.m_DrainRate;
} }
@@ -54,7 +52,8 @@ public class FloodAlgorithm implements InterfaceOptimizer, java.io.Serializable
return (Object) new FloodAlgorithm(this); return (Object) new FloodAlgorithm(this);
} }
/** This method will init the HillClimber /**
* This method will init the HillClimber
*/ */
@Override @Override
public void init() { public void init() {
@@ -64,12 +63,14 @@ public class FloodAlgorithm implements InterfaceOptimizer, java.io.Serializable
this.firePropertyChangedEvent(Population.nextGenerationPerformed); this.firePropertyChangedEvent(Population.nextGenerationPerformed);
} }
/** This method will init the optimizer with a given population /**
* This method will init the optimizer with a given population
*
* @param reset If true the population is reset. * @param reset If true the population is reset.
*/ */
@Override @Override
public void initByPopulation(Population pop, boolean reset) { public void initByPopulation(Population pop, boolean reset) {
this.m_Population = (Population)pop.clone(); this.m_Population = (Population) pop.clone();
if (reset) { if (reset) {
this.m_Population.init(); this.m_Population.init();
this.m_Problem.evaluate(this.m_Population); this.m_Problem.evaluate(this.m_Population);
@@ -78,12 +79,13 @@ public class FloodAlgorithm implements InterfaceOptimizer, java.io.Serializable
this.m_CurrentFloodPeak = this.m_InitialFloodPeak; this.m_CurrentFloodPeak = this.m_InitialFloodPeak;
} }
/** This method will optimize /**
* This method will optimize
*/ */
@Override @Override
public void optimize() { public void optimize() {
AbstractEAIndividual indy; AbstractEAIndividual indy;
Population original = (Population)this.m_Population.clone(); Population original = (Population) this.m_Population.clone();
double[] fitness; double[] fitness;
for (int i = 0; i < this.m_Population.size(); i++) { for (int i = 0; i < this.m_Population.size(); i++) {
@@ -95,7 +97,7 @@ public class FloodAlgorithm implements InterfaceOptimizer, java.io.Serializable
} }
this.m_Problem.evaluate(this.m_Population); this.m_Problem.evaluate(this.m_Population);
for (int i = 0; i < this.m_Population.size(); i++) { for (int i = 0; i < this.m_Population.size(); i++) {
fitness = ((AbstractEAIndividual)this.m_Population.get(i)).getFitness(); fitness = ((AbstractEAIndividual) this.m_Population.get(i)).getFitness();
if (fitness[0] > this.m_CurrentFloodPeak) { if (fitness[0] > this.m_CurrentFloodPeak) {
this.m_Population.remove(i); this.m_Population.remove(i);
this.m_Population.add(i, original.get(i)); this.m_Population.add(i, original.get(i));
@@ -106,7 +108,9 @@ public class FloodAlgorithm implements InterfaceOptimizer, java.io.Serializable
this.firePropertyChangedEvent(Population.nextGenerationPerformed); this.firePropertyChangedEvent(Population.nextGenerationPerformed);
} }
/** This method calculates the difference between the fitness values /**
* This method calculates the difference between the fitness values
*
* @param org The original * @param org The original
* @param mut The mutant * @param mut The mutant
*/ */
@@ -121,19 +125,23 @@ public class FloodAlgorithm implements InterfaceOptimizer, java.io.Serializable
return result; return result;
} }
/** This method will set the problem that is to be optimized /**
* This method will set the problem that is to be optimized
*
* @param problem * @param problem
*/ */
@Override @Override
public void setProblem (InterfaceOptimizationProblem problem) { public void setProblem(InterfaceOptimizationProblem problem) {
this.m_Problem = problem; this.m_Problem = problem;
} }
@Override @Override
public InterfaceOptimizationProblem getProblem () { public InterfaceOptimizationProblem getProblem() {
return this.m_Problem; return this.m_Problem;
} }
/** This method will init the HillClimber /**
* This method will init the HillClimber
*/ */
public void defaultInit() { public void defaultInit() {
this.m_FitnessCallsNeeded = 0; this.m_FitnessCallsNeeded = 0;
@@ -141,24 +149,26 @@ public class FloodAlgorithm implements InterfaceOptimizer, java.io.Serializable
this.m_Best.defaultInit(m_Problem); this.m_Best.defaultInit(m_Problem);
} }
/** This method will optimize /**
* This method will optimize
*/ */
public void defaultOptimize() { public void defaultOptimize() {
for (int i = 0; i < m_FitnessCalls; i++) { for (int i = 0; i < m_FitnessCalls; i++) {
this.m_Test = (GAIndividualBinaryData)((this.m_Best).clone()); this.m_Test = (GAIndividualBinaryData) ((this.m_Best).clone());
this.m_Test.defaultMutate(); this.m_Test.defaultMutate();
if (this.m_Test.defaultEvaulateAsMiniBits() < this.m_Best.defaultEvaulateAsMiniBits()) { if (this.m_Test.defaultEvaulateAsMiniBits() < this.m_Best.defaultEvaulateAsMiniBits()) {
this.m_Best = this.m_Test; this.m_Best = this.m_Test;
} }
this.m_FitnessCallsNeeded = i; this.m_FitnessCallsNeeded = i;
if (this.m_Best.defaultEvaulateAsMiniBits() == 0) { if (this.m_Best.defaultEvaulateAsMiniBits() == 0) {
i = this.m_FitnessCalls +1; i = this.m_FitnessCalls + 1;
} }
} }
} }
/** This main method will start a simple hillclimber. /**
* No arguments necessary. * This main method will start a simple hillclimber. No arguments necessary.
*
* @param args * @param args
*/ */
public static void main(String[] args) { public static void main(String[] args) {
@@ -172,36 +182,43 @@ public class FloodAlgorithm implements InterfaceOptimizer, java.io.Serializable
} }
TmpMeanCalls /= program.m_MultiRuns; TmpMeanCalls /= program.m_MultiRuns;
TmpMeanFitness /= program.m_MultiRuns; TmpMeanFitness /= program.m_MultiRuns;
System.out.println("("+program.m_MultiRuns+"/"+program.m_FitnessCalls+") Mean Fitness : " + TmpMeanFitness + " Mean Calls needed: " + TmpMeanCalls); System.out.println("(" + program.m_MultiRuns + "/" + program.m_FitnessCalls + ") Mean Fitness : " + TmpMeanFitness + " Mean Calls needed: " + TmpMeanCalls);
} }
/** 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 * @param ea
*/ */
@Override @Override
public void addPopulationChangedEventListener(InterfacePopulationChangedEventListener ea) { public void addPopulationChangedEventListener(InterfacePopulationChangedEventListener ea) {
this.m_Listener = ea; this.m_Listener = ea;
} }
@Override @Override
public boolean removePopulationChangedEventListener( public boolean removePopulationChangedEventListener(
InterfacePopulationChangedEventListener ea) { InterfacePopulationChangedEventListener ea) {
if (m_Listener==ea) { if (m_Listener == ea) {
m_Listener=null; m_Listener = null;
return true; return true;
} else { } else {
return false; return false;
} }
} }
/** Something has changed
/**
* Something has changed
*/ */
protected void firePropertyChangedEvent (String name) { protected void firePropertyChangedEvent(String name) {
if (this.m_Listener != null) { if (this.m_Listener != null) {
this.m_Listener.registerPopulationStateChanged(this, name); this.m_Listener.registerPopulationStateChanged(this, name);
} }
} }
/** This method will return a string describing all properties of the optimizer /**
* and the applied methods. * This method will return a string describing all properties of the
* optimizer and the applied methods.
*
* @return A descriptive string * @return A descriptive string
*/ */
@Override @Override
@@ -209,44 +226,46 @@ public class FloodAlgorithm implements InterfaceOptimizer, java.io.Serializable
String result = ""; String result = "";
if (this.m_Population.size() > 1) { if (this.m_Population.size() > 1) {
result += "Multi(" + this.m_Population.size() + ")-Start Hill Climbing:\n"; result += "Multi(" + this.m_Population.size() + ")-Start Hill Climbing:\n";
} } else {
else {
result += "Simulated Annealing:\n"; result += "Simulated Annealing:\n";
} }
result += "Optimization Problem: "; result += "Optimization Problem: ";
result += this.m_Problem.getStringRepresentationForProblem(this) +"\n"; result += this.m_Problem.getStringRepresentationForProblem(this) + "\n";
result += this.m_Population.getStringRepresentation(); result += this.m_Population.getStringRepresentation();
return result; return result;
} }
/** 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 * @param name The indenifier
*/ */
@Override @Override
public void setIdentifier(String name) { public void setIdentifier(String name) {
this.m_Identifier = name; this.m_Identifier = name;
} }
@Override @Override
public String getIdentifier() { public String getIdentifier() {
return this.m_Identifier; return this.m_Identifier;
} }
/** This method is required to free the memory on a RMIServer, /**
* but there is nothing to implement. * ********************************************************************************************************************
*/
@Override
public void freeWilly() {
}
/**********************************************************************************************************************
* These are for GUI * These are for GUI
*/ */
/** This method returns a global info string /**
* This method returns a global info string
*
* @return description * @return description
*/ */
public static String globalInfo() { public static String globalInfo() {
return "The flood algorithm uses an declining flood peak to accpect new solutions (*shudder* check inital flood peak and drain very carefully!)."; return "The flood algorithm uses an declining flood peak to accpect new solutions (*shudder* check inital flood peak and drain very carefully!).";
} }
/** This method will return a naming String
/**
* This method will return a naming String
*
* @return The name of the algorithm * @return The name of the algorithm
*/ */
@Override @Override
@@ -254,55 +273,67 @@ public class FloodAlgorithm implements InterfaceOptimizer, java.io.Serializable
return "MS-FA"; return "MS-FA";
} }
/** Assuming that all optimizer will store thier data in a population /**
* we will allow acess to this population to query to current state * Assuming that all optimizer will store thier data in a population we will
* of the optimizer. * allow acess to this population to query to current state of the
* optimizer.
*
* @return The population of current solutions to a given problem. * @return The population of current solutions to a given problem.
*/ */
@Override @Override
public Population getPopulation() { public Population getPopulation() {
return this.m_Population; return this.m_Population;
} }
@Override @Override
public void setPopulation(Population pop){ public void setPopulation(Population pop) {
this.m_Population = pop; this.m_Population = pop;
} }
public String populationTipText() { public String populationTipText() {
return "Change the number of best individuals stored (MS-FA)."; return "Change the number of best individuals stored (MS-FA).";
} }
@Override @Override
public InterfaceSolutionSet getAllSolutions() { public InterfaceSolutionSet getAllSolutions() {
return new SolutionSet(getPopulation()); return new SolutionSet(getPopulation());
} }
/** This methods allow you to set/get the temperatur of the flood
* algorithm procedure /**
* This methods allow you to set/get the temperatur of the flood algorithm
* procedure
*
* @return The initial flood level. * @return The initial flood level.
*/ */
public double getInitialFloodPeak() { public double getInitialFloodPeak() {
return this.m_InitialFloodPeak; return this.m_InitialFloodPeak;
} }
public void setInitialFloodPeak(double pop){
public void setInitialFloodPeak(double pop) {
this.m_InitialFloodPeak = pop; this.m_InitialFloodPeak = pop;
} }
public String initialFloodPeakTipText() { public String initialFloodPeakTipText() {
return "Set the initial flood peak."; return "Set the initial flood peak.";
} }
/** This methods allow you to set/get the drain rate of the flood /**
* algorithm procedure * This methods allow you to set/get the drain rate of the flood algorithm
* procedure
*
* @return The drain rate. * @return The drain rate.
*/ */
public double getDrainRate() { public double getDrainRate() {
return this.m_DrainRate; return this.m_DrainRate;
} }
public void setDrainRate(double a){
public void setDrainRate(double a) {
this.m_DrainRate = a; this.m_DrainRate = a;
if (this.m_DrainRate < 0) { if (this.m_DrainRate < 0) {
this.m_DrainRate = 0.0; this.m_DrainRate = 0.0;
} }
} }
public String drainRateTipText() { public String drainRateTipText() {
return "Set the drain rate that reduces the current flood level each generation."; return "Set the drain rate that reduces the current flood level each generation.";
} }

View File

@@ -241,14 +241,6 @@ public class GeneticAlgorithm implements InterfaceOptimizer, java.io.Serializabl
return this.identifier; return this.identifier;
} }
/**
* This method is required to free the memory on a RMIServer, but there is
* nothing to implement.
*/
@Override
public void freeWilly() {
}
/** /**
* ******************************************************************************************************************** * ********************************************************************************************************************
* These are for GUI * These are for GUI

View File

@@ -22,11 +22,9 @@ import eva2.tools.ReflectPackage;
* @author not attributable * @author not attributable
* @version 1.0 * @version 1.0
*/ */
public class GradientDescentAlgorithm implements InterfaceOptimizer, java.io.Serializable { public class GradientDescentAlgorithm implements InterfaceOptimizer, java.io.Serializable {
private InterfaceOptimizationProblem m_Problem; private InterfaceOptimizationProblem m_Problem;
InterfaceDataTypeDouble m_Best, m_Test; InterfaceDataTypeDouble m_Best, m_Test;
private int iterations = 1; private int iterations = 1;
private double wDecreaseStepSize = 0.5; private double wDecreaseStepSize = 0.5;
@@ -46,13 +44,10 @@ public class GradientDescentAlgorithm implements InterfaceOptimizer, java.io.Ser
transient private InterfacePopulationChangedEventListener m_Listener; transient private InterfacePopulationChangedEventListener m_Listener;
public double maximumabsolutechange = 0.2; public double maximumabsolutechange = 0.2;
// Hashtable indyhash; // Hashtable indyhash;
// These variables are necessary for the more complex LectureGUI enviroment // These variables are necessary for the more complex LectureGUI enviroment
transient private String m_Identifier = ""; transient private String m_Identifier = "";
private Population m_Population; private Population m_Population;
private static boolean TRACE = false;
private static boolean TRACE=false;
private static final String lockKey = "gdaLockDataKey"; private static final String lockKey = "gdaLockDataKey";
private static final String lastFitnessKey = "gdaLastFitDataKey"; private static final String lastFitnessKey = "gdaLastFitDataKey";
private static final String stepSizeKey = "gdaStepSizeDataKey"; private static final String stepSizeKey = "gdaStepSizeDataKey";
@@ -87,8 +82,8 @@ public class GradientDescentAlgorithm implements InterfaceOptimizer, java.io.Ser
* @param maxAbsoluteChange * @param maxAbsoluteChange
*/ */
public GradientDescentAlgorithm(double minStepSize, double maxStepSize, double maxAbsoluteChange) { public GradientDescentAlgorithm(double minStepSize, double maxStepSize, double maxAbsoluteChange) {
globalStepSizeAdaption=false; globalStepSizeAdaption = false;
localStepSizeAdaption=true; localStepSizeAdaption = true;
localminstepsize = minStepSize; localminstepsize = minStepSize;
globalminstepsize = minStepSize; globalminstepsize = minStepSize;
localmaxstepsize = maxStepSize; localmaxstepsize = maxStepSize;
@@ -98,7 +93,9 @@ public class GradientDescentAlgorithm implements InterfaceOptimizer, java.io.Ser
@Override @Override
public Object clone() { public Object clone() {
/**@todo Implement InterfaceOptimizer method*/ /**
* @todo Implement InterfaceOptimizer method
*/
throw new java.lang.UnsupportedOperationException("Method clone() not yet implemented."); throw new java.lang.UnsupportedOperationException("Method clone() not yet implemented.");
} }
@@ -126,7 +123,7 @@ public class GradientDescentAlgorithm implements InterfaceOptimizer, java.io.Ser
// if ((this.indyhash == null) || (this.indyhash.size() <1)) init(); // if ((this.indyhash == null) || (this.indyhash.size() <1)) init();
for (int i = 0; i < this.m_Population.size(); i++) { for (int i = 0; i < this.m_Population.size(); i++) {
indy = ((AbstractEAIndividual)this.m_Population.get(i)); indy = ((AbstractEAIndividual) this.m_Population.get(i));
if (!indy.hasData(gradientKey)) { if (!indy.hasData(gradientKey)) {
//System.out.println("new indy to hash"); //System.out.println("new indy to hash");
// Hashtable history = new Hashtable(); // Hashtable history = new Hashtable();
@@ -151,10 +148,10 @@ public class GradientDescentAlgorithm implements InterfaceOptimizer, java.io.Ser
// System.out.println("hashtable built"); // System.out.println("hashtable built");
for (int i = 0; i < this.m_Population.size(); i++) { for (int i = 0; i < this.m_Population.size(); i++) {
indy = ((AbstractEAIndividual)this.m_Population.get(i)); indy = ((AbstractEAIndividual) this.m_Population.get(i));
double[][] range = ((InterfaceDataTypeDouble) indy).getDoubleRange(); double[][] range = ((InterfaceDataTypeDouble) indy).getDoubleRange();
double[] params = ((InterfaceDataTypeDouble) indy).getDoubleData(); double[] params = ((InterfaceDataTypeDouble) indy).getDoubleData();
indy.putData(oldParamsKey , params); indy.putData(oldParamsKey, params);
int[] lock = (int[]) indy.getData(lockKey); int[] lock = (int[]) indy.getData(lockKey);
double indystepsize = ((Double) indy.getData(stepSizeKey)).doubleValue(); double indystepsize = ((Double) indy.getData(stepSizeKey)).doubleValue();
@@ -191,7 +188,7 @@ public class GradientDescentAlgorithm implements InterfaceOptimizer, java.io.Ser
indy.putData(gradientKey, gradient); indy.putData(gradientKey, gradient);
double[] change = new double[params.length]; double[] change = new double[params.length];
if (indy.hasData(changesKey)) { if (indy.hasData(changesKey)) {
oldchange =(double[]) indy.getData(changesKey); oldchange = (double[]) indy.getData(changesKey);
} }
boolean dograddesc = (this.momentumterm) && (oldchange != null); boolean dograddesc = (this.momentumterm) && (oldchange != null);
@@ -204,7 +201,7 @@ public class GradientDescentAlgorithm implements InterfaceOptimizer, java.io.Ser
if (this.globalStepSizeAdaption) { if (this.globalStepSizeAdaption) {
tempstepsize *= indystepsize; tempstepsize *= indystepsize;
} }
double wchange = signum(tempstepsize * gradient[j]) * Math.min(maximumabsolutechange,Math.abs(tempstepsize * gradient[j])); //indystepsize * gradient[j]; double wchange = signum(tempstepsize * gradient[j]) * Math.min(maximumabsolutechange, Math.abs(tempstepsize * gradient[j])); //indystepsize * gradient[j];
if (this.manhattan) { if (this.manhattan) {
wchange = this.signum(wchange) * tempstepsize; wchange = this.signum(wchange) * tempstepsize;
} }
@@ -236,12 +233,12 @@ public class GradientDescentAlgorithm implements InterfaceOptimizer, java.io.Ser
} // end if ((this.m_Problem instanceof InterfaceFirstOrderDerivableProblem) && (indy instanceof InterfaceDataTypeDouble)) { } // end if ((this.m_Problem instanceof InterfaceFirstOrderDerivableProblem) && (indy instanceof InterfaceDataTypeDouble)) {
else { else {
String msg="Warning, problem of type InterfaceFirstOrderDerivableProblem and template of type InterfaceDataTypeDouble is required for " + this.getClass(); String msg = "Warning, problem of type InterfaceFirstOrderDerivableProblem and template of type InterfaceDataTypeDouble is required for " + this.getClass();
EVAERROR.errorMsgOnce(msg); EVAERROR.errorMsgOnce(msg);
Class<?>[] clsArr = ReflectPackage.getAssignableClasses(InterfaceFirstOrderDerivableProblem.class.getName(), true, true); Class<?>[] clsArr = ReflectPackage.getAssignableClasses(InterfaceFirstOrderDerivableProblem.class.getName(), true, true);
msg += " (available: "; msg += " (available: ";
for (Class<?> cls: clsArr) { for (Class<?> cls : clsArr) {
msg=msg+" "+cls.getSimpleName(); msg = msg + " " + cls.getSimpleName();
} }
msg += ")"; msg += ")";
throw new RuntimeException(msg); throw new RuntimeException(msg);
@@ -253,7 +250,7 @@ public class GradientDescentAlgorithm implements InterfaceOptimizer, java.io.Ser
if (this.recovery) { if (this.recovery) {
for (int i = 0; i < this.m_Population.size(); i++) { for (int i = 0; i < this.m_Population.size(); i++) {
indy = ((AbstractEAIndividual)this.m_Population.get(i)); indy = ((AbstractEAIndividual) this.m_Population.get(i));
// Hashtable history = (Hashtable) indyhash.get(indy); // Hashtable history = (Hashtable) indyhash.get(indy);
if (indy.getFitness()[0] > recoverythreshold) { if (indy.getFitness()[0] > recoverythreshold) {
if (TRACE) { if (TRACE) {
@@ -284,7 +281,7 @@ public class GradientDescentAlgorithm implements InterfaceOptimizer, java.io.Ser
//System.out.println("gsa main"); //System.out.println("gsa main");
for (int i = 0; i < this.m_Population.size(); i++) { for (int i = 0; i < this.m_Population.size(); i++) {
indy = ((AbstractEAIndividual)this.m_Population.get(i)); indy = ((AbstractEAIndividual) this.m_Population.get(i));
// Hashtable history = (Hashtable) indyhash.get(indy); // Hashtable history = (Hashtable) indyhash.get(indy);
// if (history == null) break; // if (history == null) break;
if (indy.getData(lastFitnessKey) != null) { if (indy.getData(lastFitnessKey) != null) {
@@ -311,7 +308,6 @@ public class GradientDescentAlgorithm implements InterfaceOptimizer, java.io.Ser
this.firePropertyChangedEvent(Population.nextGenerationPerformed); this.firePropertyChangedEvent(Population.nextGenerationPerformed);
} }
private double momentumweigth = 0.1; private double momentumweigth = 0.1;
protected void firePropertyChangedEvent(String name) { protected void firePropertyChangedEvent(String name) {
@@ -340,8 +336,9 @@ public class GradientDescentAlgorithm implements InterfaceOptimizer, java.io.Ser
this.m_Population = pop; this.m_Population = pop;
} }
/**
/** 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 * @param name The indenifier
*/ */
@Override @Override
@@ -374,16 +371,18 @@ public class GradientDescentAlgorithm implements InterfaceOptimizer, java.io.Ser
public void addPopulationChangedEventListener(InterfacePopulationChangedEventListener ea) { public void addPopulationChangedEventListener(InterfacePopulationChangedEventListener ea) {
this.m_Listener = ea; this.m_Listener = ea;
} }
@Override @Override
public boolean removePopulationChangedEventListener( public boolean removePopulationChangedEventListener(
InterfacePopulationChangedEventListener ea) { InterfacePopulationChangedEventListener ea) {
if (m_Listener==ea) { if (m_Listener == ea) {
m_Listener=null; m_Listener = null;
return true; return true;
} else { } else {
return false; return false;
} }
} }
public static void main(String[] args) { public static void main(String[] args) {
GradientDescentAlgorithm program = new GradientDescentAlgorithm(); GradientDescentAlgorithm program = new GradientDescentAlgorithm();
InterfaceOptimizationProblem problem = new F1Problem(); InterfaceOptimizationProblem problem = new F1Problem();
@@ -399,22 +398,22 @@ public class GradientDescentAlgorithm implements InterfaceOptimizer, java.io.Ser
} }
} }
@Override
public void freeWilly() { }
public static String globalInfo() { public static String globalInfo() {
return "Gradient Descent can be applied to derivable functions ("+InterfaceFirstOrderDerivableProblem.class.getSimpleName()+")."; return "Gradient Descent can be applied to derivable functions (" + InterfaceFirstOrderDerivableProblem.class.getSimpleName() + ").";
} }
//////////////// for global adaption //////////////// for global adaption
public boolean isAdaptStepSizeGlobally() { public boolean isAdaptStepSizeGlobally() {
return globalStepSizeAdaption; return globalStepSizeAdaption;
} }
public void setAdaptStepSizeGlobally(boolean globalstepsizeadaption) { public void setAdaptStepSizeGlobally(boolean globalstepsizeadaption) {
this.globalStepSizeAdaption = globalstepsizeadaption; this.globalStepSizeAdaption = globalstepsizeadaption;
if (globalstepsizeadaption && localStepSizeAdaption) { if (globalstepsizeadaption && localStepSizeAdaption) {
setAdaptStepSizeLocally(false); setAdaptStepSizeLocally(false);
} }
} }
public String adaptStepSizeGloballyTipText() { public String adaptStepSizeGloballyTipText() {
return "Use a single step size per individual - (priority over local step size)."; return "Use a single step size per individual - (priority over local step size).";
} }
@@ -422,9 +421,11 @@ public class GradientDescentAlgorithm implements InterfaceOptimizer, java.io.Ser
public double getGlobalMaxStepSize() { public double getGlobalMaxStepSize() {
return globalmaxstepsize; return globalmaxstepsize;
} }
public void setGlobalMaxStepSize(double p) { public void setGlobalMaxStepSize(double p) {
globalmaxstepsize = p; globalmaxstepsize = p;
} }
public String globalMaxStepSizeTipText() { public String globalMaxStepSizeTipText() {
return "Maximum step size for global adaption."; return "Maximum step size for global adaption.";
} }
@@ -432,9 +433,11 @@ public class GradientDescentAlgorithm implements InterfaceOptimizer, java.io.Ser
public double getGlobalMinStepSize() { public double getGlobalMinStepSize() {
return globalminstepsize; return globalminstepsize;
} }
public void setGlobalMinStepSize(double p) { public void setGlobalMinStepSize(double p) {
globalminstepsize = p; globalminstepsize = p;
} }
public String globalMindStepSizeTipText() { public String globalMindStepSizeTipText() {
return "Minimum step size for global adaption."; return "Minimum step size for global adaption.";
} }
@@ -442,9 +445,11 @@ public class GradientDescentAlgorithm implements InterfaceOptimizer, java.io.Ser
public double getGlobalInitStepSize() { public double getGlobalInitStepSize() {
return globalinitstepsize; return globalinitstepsize;
} }
public void setGlobalInitStepSize(double initstepsize) { public void setGlobalInitStepSize(double initstepsize) {
this.globalinitstepsize = initstepsize; this.globalinitstepsize = initstepsize;
} }
public String globalInitStepSizeTipText() { public String globalInitStepSizeTipText() {
return "Initial step size for global adaption."; return "Initial step size for global adaption.";
} }
@@ -453,12 +458,14 @@ public class GradientDescentAlgorithm implements InterfaceOptimizer, java.io.Ser
public boolean isAdaptStepSizeLocally() { public boolean isAdaptStepSizeLocally() {
return localStepSizeAdaption; return localStepSizeAdaption;
} }
public void setAdaptStepSizeLocally(boolean stepsizeadaption) { public void setAdaptStepSizeLocally(boolean stepsizeadaption) {
this.localStepSizeAdaption = stepsizeadaption; this.localStepSizeAdaption = stepsizeadaption;
if (globalStepSizeAdaption && localStepSizeAdaption) { if (globalStepSizeAdaption && localStepSizeAdaption) {
setAdaptStepSizeGlobally(false); setAdaptStepSizeGlobally(false);
} }
} }
public String adaptStepSizeLocallyTipText() { public String adaptStepSizeLocallyTipText() {
return "Use a step size parameter in any dimension."; return "Use a step size parameter in any dimension.";
} }
@@ -466,6 +473,7 @@ public class GradientDescentAlgorithm implements InterfaceOptimizer, java.io.Ser
public double getLocalMinStepSize() { public double getLocalMinStepSize() {
return localminstepsize; return localminstepsize;
} }
public void setLocalMinStepSize(double localminstepsize) { public void setLocalMinStepSize(double localminstepsize) {
this.localminstepsize = localminstepsize; this.localminstepsize = localminstepsize;
} }
@@ -473,6 +481,7 @@ public class GradientDescentAlgorithm implements InterfaceOptimizer, java.io.Ser
public double getLocalMaxStepSize() { public double getLocalMaxStepSize() {
return localmaxstepsize; return localmaxstepsize;
} }
public void setLocalMaxStepSize(double localmaxstepsize) { public void setLocalMaxStepSize(double localmaxstepsize) {
this.localmaxstepsize = localmaxstepsize; this.localmaxstepsize = localmaxstepsize;
} }
@@ -480,9 +489,11 @@ public class GradientDescentAlgorithm implements InterfaceOptimizer, java.io.Ser
public void setStepSizeIncreaseFact(double nplus) { public void setStepSizeIncreaseFact(double nplus) {
this.wIncreaseStepSize = nplus; this.wIncreaseStepSize = nplus;
} }
public double getStepSizeIncreaseFact() { public double getStepSizeIncreaseFact() {
return wIncreaseStepSize; return wIncreaseStepSize;
} }
public String stepSizeIncreaseFactTipText() { public String stepSizeIncreaseFactTipText() {
return "Factor for increasing the step size in adaption."; return "Factor for increasing the step size in adaption.";
} }
@@ -490,9 +501,11 @@ public class GradientDescentAlgorithm implements InterfaceOptimizer, java.io.Ser
public void setStepSizeDecreaseFact(double nminus) { public void setStepSizeDecreaseFact(double nminus) {
this.wDecreaseStepSize = nminus; this.wDecreaseStepSize = nminus;
} }
public double getStepSizeDecreaseFact() { public double getStepSizeDecreaseFact() {
return wDecreaseStepSize; return wDecreaseStepSize;
} }
public String stepSizeDecreaseFactTipText() { public String stepSizeDecreaseFactTipText() {
return "Factor for decreasing the step size in adaption."; return "Factor for decreasing the step size in adaption.";
} }
@@ -501,40 +514,47 @@ public class GradientDescentAlgorithm implements InterfaceOptimizer, java.io.Ser
public boolean isRecovery() { public boolean isRecovery() {
return recovery; return recovery;
} }
public void setRecovery(boolean recovery) { public void setRecovery(boolean recovery) {
this.recovery = recovery; this.recovery = recovery;
} }
public int getRecoveryLocksteps() { public int getRecoveryLocksteps() {
return recoverylocksteps; return recoverylocksteps;
} }
public void setRecoveryLocksteps(int locksteps) { public void setRecoveryLocksteps(int locksteps) {
this.recoverylocksteps = locksteps; this.recoverylocksteps = locksteps;
} }
public double getRecoveryThreshold() { public double getRecoveryThreshold() {
return recoverythreshold; return recoverythreshold;
} }
public void setRecoveryThreshold(double recoverythreshold) { public void setRecoveryThreshold(double recoverythreshold) {
this.recoverythreshold = recoverythreshold; this.recoverythreshold = recoverythreshold;
} }
public String recoveryThresholdTipText() { public String recoveryThresholdTipText() {
return "If the fitness exceeds this threshold, an unstable area is assumed and one step recovered."; return "If the fitness exceeds this threshold, an unstable area is assumed and one step recovered.";
} }
public int getIterations() { public int getIterations() {
return iterations; return iterations;
} }
public void setIterations(int iterations) { public void setIterations(int iterations) {
this.iterations = iterations; this.iterations = iterations;
} }
public String iterationsTipText() { public String iterationsTipText() {
return "The number of GD-iterations per generation."; return "The number of GD-iterations per generation.";
} }
public boolean isManhattan() { public boolean isManhattan() {
return manhattan; return manhattan;
} }
public void setManhattan(boolean manhattan) { public void setManhattan(boolean manhattan) {
this.manhattan = manhattan; this.manhattan = manhattan;
} }
@@ -542,6 +562,7 @@ public class GradientDescentAlgorithm implements InterfaceOptimizer, java.io.Ser
public boolean isMomentumTerm() { public boolean isMomentumTerm() {
return momentumterm; return momentumterm;
} }
public void setMomentumTerm(boolean momentum) { public void setMomentumTerm(boolean momentum) {
this.momentumterm = momentum; this.momentumterm = momentum;
} }
@@ -549,6 +570,7 @@ public class GradientDescentAlgorithm implements InterfaceOptimizer, java.io.Ser
public double getMomentumWeigth() { public double getMomentumWeigth() {
return momentumweigth; return momentumweigth;
} }
public void setMomentumWeigth(double momentumweigth) { public void setMomentumWeigth(double momentumweigth) {
this.momentumweigth = momentumweigth; this.momentumweigth = momentumweigth;
} }
@@ -556,11 +578,12 @@ public class GradientDescentAlgorithm implements InterfaceOptimizer, java.io.Ser
public double getMaximumAbsoluteChange() { public double getMaximumAbsoluteChange() {
return maximumabsolutechange; return maximumabsolutechange;
} }
public void setMaximumAbsoluteChange(double maximumabsolutechange) { public void setMaximumAbsoluteChange(double maximumabsolutechange) {
this.maximumabsolutechange = maximumabsolutechange; this.maximumabsolutechange = maximumabsolutechange;
} }
public String maximumAbsoluteChangeTipText() { public String maximumAbsoluteChangeTipText() {
return "The maximum change along a coordinate in one step."; return "The maximum change along a coordinate in one step.";
} }
} }

View File

@@ -9,27 +9,25 @@ import eva2.server.go.populations.SolutionSet;
import eva2.server.go.problems.B1Problem; import eva2.server.go.problems.B1Problem;
import eva2.server.go.problems.InterfaceOptimizationProblem; import eva2.server.go.problems.InterfaceOptimizationProblem;
/**
/** This is a Multi-Start Hill-Climber, here the population size gives the number of * This is a Multi-Start Hill-Climber, here the population size gives the number
* multi-starts. Similar to the evolutionary programming strategy this strategy sets the * of multi-starts. Similar to the evolutionary programming strategy this
* mutation rate temporarily to 1.0. * strategy sets the mutation rate temporarily to 1.0. Copyright: Copyright (c)
* Copyright: Copyright (c) 2003 * 2003 Company: University of Tuebingen, Computer Architecture
* Company: University of Tuebingen, Computer Architecture *
* @author Felix Streichert * @author Felix Streichert
* @version: $Revision: 307 $ * @version: $Revision: 307 $ $Date: 2007-12-04 14:31:47 +0100 (Tue, 04 Dec
* $Date: 2007-12-04 14:31:47 +0100 (Tue, 04 Dec 2007) $ * 2007) $ $Author: mkron $
* $Author: mkron $
*/ */
public class HillClimbing implements InterfaceOptimizer, java.io.Serializable { public class HillClimbing implements InterfaceOptimizer, java.io.Serializable {
// These variables are necessary for the simple testcase // These variables are necessary for the simple testcase
private InterfaceOptimizationProblem m_Problem = new B1Problem(); private InterfaceOptimizationProblem m_Problem = new B1Problem();
private InterfaceMutation mutator = null; private InterfaceMutation mutator = null;
// private int m_MultiRuns = 100; // private int m_MultiRuns = 100;
// private int m_FitnessCalls = 100; // private int m_FitnessCalls = 100;
// private int m_FitnessCallsNeeded = 0; // private int m_FitnessCallsNeeded = 0;
// GAIndividualBinaryData m_Best, m_Test; // GAIndividualBinaryData m_Best, m_Test;
// These variables are necessary for the more complex LectureGUI enviroment // These variables are necessary for the more complex LectureGUI enviroment
transient private String m_Identifier = ""; transient private String m_Identifier = "";
transient private InterfacePopulationChangedEventListener m_Listener; transient private InterfacePopulationChangedEventListener m_Listener;
@@ -41,8 +39,8 @@ public class HillClimbing implements InterfaceOptimizer, java.io.Serializable {
} }
public HillClimbing(HillClimbing a) { public HillClimbing(HillClimbing a) {
this.m_Population = (Population)a.m_Population.clone(); this.m_Population = (Population) a.m_Population.clone();
this.m_Problem = (InterfaceOptimizationProblem)a.m_Problem.clone(); this.m_Problem = (InterfaceOptimizationProblem) a.m_Problem.clone();
} }
@Override @Override
@@ -50,7 +48,8 @@ public class HillClimbing implements InterfaceOptimizer, java.io.Serializable {
return (Object) new HillClimbing(this); return (Object) new HillClimbing(this);
} }
/** This method will init the HillClimber /**
* This method will init the HillClimber
*/ */
@Override @Override
public void init() { public void init() {
@@ -61,7 +60,7 @@ public class HillClimbing implements InterfaceOptimizer, java.io.Serializable {
@Override @Override
public void initByPopulation(Population pop, boolean reset) { public void initByPopulation(Population pop, boolean reset) {
this.m_Population = (Population)pop.clone(); this.m_Population = (Population) pop.clone();
if (reset) { if (reset) {
this.m_Population.init(); this.m_Population.init();
this.m_Problem.evaluate(this.m_Population); this.m_Problem.evaluate(this.m_Population);
@@ -69,12 +68,13 @@ public class HillClimbing implements InterfaceOptimizer, java.io.Serializable {
} }
} }
/** This method will optimize /**
* This method will optimize
*/ */
@Override @Override
public void optimize() { public void optimize() {
AbstractEAIndividual indy; AbstractEAIndividual indy;
Population original = (Population)this.m_Population.clone(); Population original = (Population) this.m_Population.clone();
double tmpD; double tmpD;
InterfaceMutation tmpMut; InterfaceMutation tmpMut;
@@ -84,15 +84,14 @@ public class HillClimbing implements InterfaceOptimizer, java.io.Serializable {
indy.setMutationProbability(1.0); indy.setMutationProbability(1.0);
if (mutator == null) { if (mutator == null) {
indy.mutate(); indy.mutate();
} } else {
else {
mutator.mutate(indy); mutator.mutate(indy);
} }
indy.setMutationProbability(tmpD); indy.setMutationProbability(tmpD);
} }
this.m_Problem.evaluate(this.m_Population); this.m_Problem.evaluate(this.m_Population);
for (int i = 0; i < this.m_Population.size(); i++) { for (int i = 0; i < this.m_Population.size(); i++) {
if (((AbstractEAIndividual)original.get(i)).isDominatingDebConstraints(((AbstractEAIndividual)this.m_Population.get(i)))) { if (((AbstractEAIndividual) original.get(i)).isDominatingDebConstraints(((AbstractEAIndividual) this.m_Population.get(i)))) {
// this.m_Population.remove(i); // this.m_Population.remove(i);
// throw away mutated one and replace by old one // throw away mutated one and replace by old one
this.m_Population.set(i, original.get(i)); this.m_Population.set(i, original.get(i));
@@ -123,8 +122,9 @@ public class HillClimbing implements InterfaceOptimizer, java.io.Serializable {
} }
/** /**
* Allows to set a desired mutator by hand, which is used instead of the one in the individuals. * Allows to set a desired mutator by hand, which is used instead of the one
* Set it to null to use the one in the individuals, which is the default. * in the individuals. Set it to null to use the one in the individuals,
* which is the default.
* *
* @param mute * @param mute
*/ */
@@ -132,15 +132,18 @@ public class HillClimbing implements InterfaceOptimizer, java.io.Serializable {
mutator = mute; mutator = mute;
} }
/** This method will set the problem that is to be optimized /**
* This method will set the problem that is to be optimized
*
* @param problem * @param problem
*/ */
@Override @Override
public void setProblem (InterfaceOptimizationProblem problem) { public void setProblem(InterfaceOptimizationProblem problem) {
this.m_Problem = problem; this.m_Problem = problem;
} }
@Override @Override
public InterfaceOptimizationProblem getProblem () { public InterfaceOptimizationProblem getProblem() {
return this.m_Problem; return this.m_Problem;
} }
@@ -163,7 +166,6 @@ public class HillClimbing implements InterfaceOptimizer, java.io.Serializable {
// if (this.m_Best.defaultEvaulateAsMiniBits() == 0) i = this.m_FitnessCalls +1; // if (this.m_Best.defaultEvaulateAsMiniBits() == 0) i = this.m_FitnessCalls +1;
// } // }
// } // }
// /** This main method will start a simple hillclimber. // /** This main method will start a simple hillclimber.
// * No arguments necessary. // * No arguments necessary.
// * @param args // * @param args
@@ -181,34 +183,40 @@ public class HillClimbing implements InterfaceOptimizer, java.io.Serializable {
// TmpMeanFitness = TmpMeanFitness/program.m_MultiRuns; // TmpMeanFitness = TmpMeanFitness/program.m_MultiRuns;
// System.out.println("("+program.m_MultiRuns+"/"+program.m_FitnessCalls+") Mean Fitness : " + TmpMeanFitness + " Mean Calls needed: " + TmpMeanCalls); // System.out.println("("+program.m_MultiRuns+"/"+program.m_FitnessCalls+") Mean Fitness : " + TmpMeanFitness + " Mean Calls needed: " + TmpMeanCalls);
// } // }
/**
/** 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 * @param ea
*/ */
@Override @Override
public void addPopulationChangedEventListener(InterfacePopulationChangedEventListener ea) { public void addPopulationChangedEventListener(InterfacePopulationChangedEventListener ea) {
this.m_Listener = ea; this.m_Listener = ea;
} }
@Override @Override
public boolean removePopulationChangedEventListener( public boolean removePopulationChangedEventListener(
InterfacePopulationChangedEventListener ea) { InterfacePopulationChangedEventListener ea) {
if (m_Listener==ea) { if (m_Listener == ea) {
m_Listener=null; m_Listener = null;
return true; return true;
} else { } else {
return false; return false;
} }
} }
/** Something has changed
/**
* Something has changed
*/ */
protected void firePropertyChangedEvent (String name) { protected void firePropertyChangedEvent(String name) {
if (this.m_Listener != null) { if (this.m_Listener != null) {
this.m_Listener.registerPopulationStateChanged(this, name); this.m_Listener.registerPopulationStateChanged(this, name);
} }
} }
/** This method will return a string describing all properties of the optimizer /**
* and the applied methods. * This method will return a string describing all properties of the
* optimizer and the applied methods.
*
* @return A descriptive string * @return A descriptive string
*/ */
@Override @Override
@@ -216,56 +224,60 @@ public class HillClimbing implements InterfaceOptimizer, java.io.Serializable {
String result = ""; String result = "";
if (this.m_Population.size() > 1) { if (this.m_Population.size() > 1) {
result += "Multi(" + this.m_Population.size() + ")-Start Hill Climbing:\n"; result += "Multi(" + this.m_Population.size() + ")-Start Hill Climbing:\n";
} } else {
else {
result += "Hill Climbing:\n"; result += "Hill Climbing:\n";
} }
result += "Optimization Problem: "; result += "Optimization Problem: ";
result += this.m_Problem.getStringRepresentationForProblem(this) +"\n"; result += this.m_Problem.getStringRepresentationForProblem(this) + "\n";
result += this.m_Population.getStringRepresentation(); result += this.m_Population.getStringRepresentation();
return result; return result;
} }
/** 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 * @param name The indenifier
*/ */
@Override @Override
public void setIdentifier(String name) { public void setIdentifier(String name) {
this.m_Identifier = name; this.m_Identifier = name;
} }
@Override @Override
public String getIdentifier() { public String getIdentifier() {
return this.m_Identifier; return this.m_Identifier;
} }
/** This method is required to free the memory on a RMIServer, /**
* but there is nothing to implement. * ********************************************************************************************************************
*/
@Override
public void freeWilly() {
}
/**********************************************************************************************************************
* These are for GUI * These are for GUI
*/ */
/** This method returns a global info string /**
* This method returns a global info string
*
* @return description * @return description
*/ */
public static String globalInfo() { public static String globalInfo() {
return "The Hill Climber uses the default EA mutation and initializing operators. If the population size is bigger than one a multi-start Hill Climber is performed."; return "The Hill Climber uses the default EA mutation and initializing operators. If the population size is bigger than one a multi-start Hill Climber is performed.";
} }
/** This method will return a naming String
/**
* This method will return a naming String
*
* @return The name of the algorithm * @return The name of the algorithm
*/ */
@Override @Override
public String getName() { public String getName() {
return "MS-HC"+getIdentifier(); return "MS-HC" + getIdentifier();
} }
@Override @Override
public Population getPopulation() { public Population getPopulation() {
return this.m_Population; return this.m_Population;
} }
@Override @Override
public void setPopulation(Population pop){ public void setPopulation(Population pop) {
this.m_Population = pop; this.m_Population = pop;
} }
@@ -273,6 +285,7 @@ public class HillClimbing implements InterfaceOptimizer, java.io.Serializable {
public InterfaceSolutionSet getAllSolutions() { public InterfaceSolutionSet getAllSolutions() {
return new SolutionSet(getPopulation()); return new SolutionSet(getPopulation());
} }
public String populationTipText() { public String populationTipText() {
return "Change the number of best individuals stored (MS-HC)."; return "Change the number of best individuals stored (MS-HC).";
} }

View File

@@ -22,29 +22,29 @@ public interface InterfaceOptimizer {
/** This method will return deep clone of the optimizer /** This method will return deep clone of the optimizer
* @return The clone * @return The clone
*/ */
public Object clone(); Object clone();
/** This method will return a naming String /** This method will return a naming String
* @return The name of the algorithm * @return The name of the algorithm
*/ */
public String getName(); String getName();
/** /**
* This method allows you to add a listener to the Optimizer. * This method allows you to add a listener to the Optimizer.
* @param ea * @param ea
*/ */
public void addPopulationChangedEventListener(InterfacePopulationChangedEventListener ea); void addPopulationChangedEventListener(InterfacePopulationChangedEventListener ea);
/** /**
* This method removes a listener from the Optimizer. It returns true on success, * This method removes a listener from the Optimizer. It returns true on success,
* false if the listener could not be found. * false if the listener could not be found.
* @param ea * @param ea
*/ */
public boolean removePopulationChangedEventListener(InterfacePopulationChangedEventListener ea); boolean removePopulationChangedEventListener(InterfacePopulationChangedEventListener ea);
/** This method will init the optimizer /** This method will init the optimizer
*/ */
public void init(); void init();
/** /**
* This method will init the optimizer with a given population. * This method will init the optimizer with a given population.
@@ -52,22 +52,22 @@ public interface InterfaceOptimizer {
* @param pop The initial population * @param pop The initial population
* @param reset If true the population is reinitialized and reevaluated. * @param reset If true the population is reinitialized and reevaluated.
*/ */
public void initByPopulation(Population pop, boolean reset); void initByPopulation(Population pop, boolean reset);
/** This method will optimize for a single iteration, after this step /** This method will optimize for a single iteration, after this step
* the population should be as big as possible (ie. the size of lambda * the population should be as big as possible (ie. the size of lambda
* and not mu) and all individual should be evaluated. This allows more * and not mu) and all individual should be evaluated. This allows more
* usefull statistics on the population. * usefull statistics on the population.
*/ */
public void optimize(); void optimize();
/** Assuming that all optimizer will store their data in a population /** Assuming that all optimizer will store their data in a population
* we will allow access to this population to query to current state * we will allow access to this population to query to current state
* of the optimizer. * of the optimizer.
* @return The population of current solutions to a given problem. * @return The population of current solutions to a given problem.
*/ */
public Population getPopulation(); Population getPopulation();
public void setPopulation(Population pop); void setPopulation(Population pop);
/** /**
* Return all found solutions (local optima) if they are not contained in the current population. Be * Return all found solutions (local optima) if they are not contained in the current population. Be
@@ -78,14 +78,14 @@ public interface InterfaceOptimizer {
* *
* @return A solution set of the current population and possibly earlier solutions. * @return A solution set of the current population and possibly earlier solutions.
*/ */
public InterfaceSolutionSet getAllSolutions(); InterfaceSolutionSet getAllSolutions();
/** /**
* 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 identifier * @param name The identifier
*/ */
public void setIdentifier(String name); void setIdentifier(String name);
public String getIdentifier(); String getIdentifier();
/** /**
* This method will set the problem that is to be optimized. The problem * This method will set the problem that is to be optimized. The problem
@@ -93,17 +93,12 @@ public interface InterfaceOptimizer {
* *
* @param problem * @param problem
*/ */
public void setProblem (InterfaceOptimizationProblem problem); void setProblem (InterfaceOptimizationProblem problem);
public InterfaceOptimizationProblem getProblem (); InterfaceOptimizationProblem getProblem ();
/** This method will return a string describing all properties of the optimizer /** This method will return a string describing all properties of the optimizer
* and the applied methods. * and the applied methods.
* @return A descriptive string * @return A descriptive string
*/ */
public String getStringRepresentation(); String getStringRepresentation();
/** This method is required to free the memory on a RMIServer,
* but there is nothing to implement.
*/
public void freeWilly();
} }

View File

@@ -17,27 +17,26 @@ import eva2.server.go.problems.F8Problem;
import eva2.server.go.problems.InterfaceOptimizationProblem; import eva2.server.go.problems.InterfaceOptimizationProblem;
import eva2.server.go.problems.TF1Problem; import eva2.server.go.problems.TF1Problem;
/** The one and only island model for parallelization. Since parallelization based /**
* on the RMIProxyRemoteThread is on the one hand much slower than benchmark function * The one and only island model for parallelization. Since parallelization
* evaluation and on the other hand the GUI based distribution scheme is rather prone * based on the RMIProxyRemoteThread is on the one hand much slower than
* to config errors (the correct ssh version is required, the jar needs to be in * benchmark function evaluation and on the other hand the GUI based
* the working dir and possible problem data must be on the servers to) an implicit * distribution scheme is rather prone to config errors (the correct ssh version
* island-model has been implemented too to allow fast and reliable computation. * is required, the jar needs to be in the working dir and possible problem data
* This is still usefull, since it is less prone to premature convergence and also * must be on the servers to) an implicit island-model has been implemented too
* an heterogenuous island model can be used. * to allow fast and reliable computation. This is still usefull, since it is
* less prone to premature convergence and also an heterogenuous island model
* can be used.
* *
* A population of the same size is sent to all nodes and evaluated there independently * A population of the same size is sent to all nodes and evaluated there
* for a cycle (more precisely: for MigrationRate generations) after which a communication * independently for a cycle (more precisely: for MigrationRate generations)
* step is performed according to the migration model. Only after migration is a main * after which a communication step is performed according to the migration
* cycle complete, the statistics updated etc. * model. Only after migration is a main cycle complete, the statistics updated
* etc.
* *
* Created by IntelliJ IDEA. * Created by IntelliJ IDEA. User: streiche Date: 12.09.2004 Time: 14:48:20 To
* User: streiche * change this template use File | Settings | File Templates.
* Date: 12.09.2004
* Time: 14:48:20
* To change this template use File | Settings | File Templates.
*/ */
public class IslandModelEA implements InterfacePopulationChangedEventListener, InterfaceOptimizer, java.io.Serializable { public class IslandModelEA implements InterfacePopulationChangedEventListener, InterfaceOptimizer, java.io.Serializable {
private Population m_Population = new Population(); private Population m_Population = new Population();
@@ -47,30 +46,26 @@ public class IslandModelEA implements InterfacePopulationChangedEventListener, I
// private String[] m_NodesList; // private String[] m_NodesList;
private int m_MigrationRate = 10; private int m_MigrationRate = 10;
private boolean m_HeterogenuousProblems = false; private boolean m_HeterogenuousProblems = false;
// These are the processor to run on // These are the processor to run on
private int m_numLocalCPUs = 1; private int m_numLocalCPUs = 1;
private boolean m_localOnly = false; private boolean m_localOnly = false;
transient private InterfaceOptimizer[] m_Islands; transient private InterfaceOptimizer[] m_Islands;
// This is for debugging // This is for debugging
private boolean m_LogLocalChanges = true; private boolean m_LogLocalChanges = true;
private boolean m_Show = false; private boolean m_Show = false;
transient private Plot m_Plot = null; transient private Plot m_Plot = null;
transient private String m_Identifier = ""; transient private String m_Identifier = "";
transient private InterfacePopulationChangedEventListener m_Listener; transient private InterfacePopulationChangedEventListener m_Listener;
transient private final boolean TRACE = false; transient private final boolean TRACE = false;
public IslandModelEA() { public IslandModelEA() {
} }
public IslandModelEA(IslandModelEA a) { public IslandModelEA(IslandModelEA a) {
this.m_Population = (Population)a.m_Population.clone(); this.m_Population = (Population) a.m_Population.clone();
this.m_Problem = (InterfaceOptimizationProblem)a.m_Problem.clone(); this.m_Problem = (InterfaceOptimizationProblem) a.m_Problem.clone();
this.m_Optimizer = (InterfaceOptimizer)a.m_Optimizer.clone(); this.m_Optimizer = (InterfaceOptimizer) a.m_Optimizer.clone();
this.m_Migration = (InterfaceMigration)a.m_Migration.clone(); this.m_Migration = (InterfaceMigration) a.m_Migration.clone();
this.m_MigrationRate = a.m_MigrationRate; this.m_MigrationRate = a.m_MigrationRate;
this.m_HeterogenuousProblems = a.m_HeterogenuousProblems; this.m_HeterogenuousProblems = a.m_HeterogenuousProblems;
this.m_numLocalCPUs = a.m_numLocalCPUs; this.m_numLocalCPUs = a.m_numLocalCPUs;
@@ -98,14 +93,14 @@ public class IslandModelEA implements InterfacePopulationChangedEventListener, I
this.m_Population.init(); this.m_Population.init();
this.m_Optimizer.init(); this.m_Optimizer.init();
this.m_Optimizer.setProblem(this.m_Problem); this.m_Optimizer.setProblem(this.m_Problem);
this.m_Optimizer.setPopulation((Population)m_Population.clone()); this.m_Optimizer.setPopulation((Population) m_Population.clone());
InterfacePopulationChangedEventListener myLocal = null; InterfacePopulationChangedEventListener myLocal = null;
if (this.m_localOnly) { if (this.m_localOnly) {
// this is running on the local machine // this is running on the local machine
this.m_Islands = new InterfaceOptimizer[this.m_numLocalCPUs]; this.m_Islands = new InterfaceOptimizer[this.m_numLocalCPUs];
for (int i = 0; i < this.m_numLocalCPUs; i++) { for (int i = 0; i < this.m_numLocalCPUs; i++) {
this.m_Islands[i] = (InterfaceOptimizer) this.m_Optimizer.clone(); this.m_Islands[i] = (InterfaceOptimizer) this.m_Optimizer.clone();
this.m_Islands[i].setIdentifier(""+i); this.m_Islands[i].setIdentifier("" + i);
this.m_Islands[i].init(); this.m_Islands[i].init();
if (this.m_LogLocalChanges) { if (this.m_LogLocalChanges) {
this.m_Islands[i].addPopulationChangedEventListener(this); this.m_Islands[i].addPopulationChangedEventListener(this);
@@ -142,17 +137,19 @@ public class IslandModelEA implements InterfacePopulationChangedEventListener, I
this.m_Population.incrGeneration(); // the island-initialization has increased the island-pop generations. this.m_Population.incrGeneration(); // the island-initialization has increased the island-pop generations.
for (int i = 0; i < this.m_Islands.length; i++) { for (int i = 0; i < this.m_Islands.length; i++) {
pop = (Population)this.m_Islands[i].getPopulation().clone(); pop = (Population) this.m_Islands[i].getPopulation().clone();
this.m_Population.addPopulation(pop); this.m_Population.addPopulation(pop);
this.m_Population.incrFunctionCallsBy(pop.getFunctionCalls()); this.m_Population.incrFunctionCallsBy(pop.getFunctionCalls());
if (m_Islands[i].getPopulation().getGeneration()!=m_Population.getGeneration()) { if (m_Islands[i].getPopulation().getGeneration() != m_Population.getGeneration()) {
System.err.println("Error, inconsistent generations!"); System.err.println("Error, inconsistent generations!");
} }
} }
this.firePropertyChangedEvent(Population.nextGenerationPerformed, this.m_Optimizer.getPopulation()); this.firePropertyChangedEvent(Population.nextGenerationPerformed, this.m_Optimizer.getPopulation());
} }
/** This method will init the optimizer with a given population /**
* This method will init the optimizer with a given population
*
* @param reset If true the population is reset. * @param reset If true the population is reset.
*/ */
@Override @Override
@@ -167,7 +164,7 @@ public class IslandModelEA implements InterfacePopulationChangedEventListener, I
} }
} }
this.m_Population = (Population)tpop.clone(); this.m_Population = (Population) tpop.clone();
if (reset) { if (reset) {
this.m_Population.init(); this.m_Population.init();
this.m_Population.incrGeneration(); this.m_Population.incrGeneration();
@@ -180,7 +177,7 @@ public class IslandModelEA implements InterfacePopulationChangedEventListener, I
this.m_Islands = new InterfaceOptimizer[this.m_numLocalCPUs]; this.m_Islands = new InterfaceOptimizer[this.m_numLocalCPUs];
for (int i = 0; i < this.m_numLocalCPUs; i++) { for (int i = 0; i < this.m_numLocalCPUs; i++) {
this.m_Islands[i] = (InterfaceOptimizer) this.m_Optimizer.clone(); this.m_Islands[i] = (InterfaceOptimizer) this.m_Optimizer.clone();
this.m_Islands[i].setIdentifier(""+i); this.m_Islands[i].setIdentifier("" + i);
this.m_Islands[i].init(); this.m_Islands[i].init();
if (this.m_LogLocalChanges) { if (this.m_LogLocalChanges) {
this.m_Islands[i].addPopulationChangedEventListener(this); this.m_Islands[i].addPopulationChangedEventListener(this);
@@ -216,21 +213,22 @@ public class IslandModelEA implements InterfacePopulationChangedEventListener, I
this.m_Migration.initMigration(this.m_Islands); this.m_Migration.initMigration(this.m_Islands);
Population pop; Population pop;
for (int i = 0; i < this.m_Islands.length; i++) { for (int i = 0; i < this.m_Islands.length; i++) {
pop = (Population)this.m_Islands[i].getPopulation().clone(); pop = (Population) this.m_Islands[i].getPopulation().clone();
this.m_Population.addPopulation(pop); this.m_Population.addPopulation(pop);
this.m_Population.incrFunctionCallsBy(pop.getFunctionCalls()); this.m_Population.incrFunctionCallsBy(pop.getFunctionCalls());
} }
this.firePropertyChangedEvent(Population.nextGenerationPerformed, this.m_Optimizer.getPopulation()); this.firePropertyChangedEvent(Population.nextGenerationPerformed, this.m_Optimizer.getPopulation());
} }
/** The optimize method will compute an 'improved' and evaluated population /**
* The optimize method will compute an 'improved' and evaluated population
*/ */
@Override @Override
public void optimize() { public void optimize() {
for (int i = 0; i < this.m_Islands.length; i++) { for (int i = 0; i < this.m_Islands.length; i++) {
if (this.m_Islands[i].getPopulation().size() > 0) { if (this.m_Islands[i].getPopulation().size() > 0) {
this.m_Islands[i].optimize(); this.m_Islands[i].optimize();
if (TRACE ) { if (TRACE) {
System.out.println(BeanInspector.toString(m_Islands[i].getPopulation())); System.out.println(BeanInspector.toString(m_Islands[i].getPopulation()));
} }
} else { } else {
@@ -253,8 +251,8 @@ public class IslandModelEA implements InterfacePopulationChangedEventListener, I
System.gc(); System.gc();
} }
/** This method will manage communication between the /**
* islands * This method will manage communication between the islands
*/ */
private void communicate() { private void communicate() {
// Here i'll have to wait until all islands are finished // Here i'll have to wait until all islands are finished
@@ -264,13 +262,13 @@ public class IslandModelEA implements InterfacePopulationChangedEventListener, I
allReachedG = true; allReachedG = true;
String gen = "["; String gen = "[";
for (int i = 0; i < this.m_Islands.length; i++) { for (int i = 0; i < this.m_Islands.length; i++) {
gen += this.m_Islands[i].getPopulation().getGeneration()+"; "; gen += this.m_Islands[i].getPopulation().getGeneration() + "; ";
if (this.m_Islands[i].getPopulation().getGeneration() != G) { if (this.m_Islands[i].getPopulation().getGeneration() != G) {
allReachedG = false; allReachedG = false;
} }
} }
if (!allReachedG) { if (!allReachedG) {
System.out.println("Waiting...."+gen+"] ?= " + G); System.out.println("Waiting...." + gen + "] ?= " + G);
try { try {
Thread.sleep(1000); Thread.sleep(1000);
} catch (Exception e) { } catch (Exception e) {
@@ -282,7 +280,7 @@ public class IslandModelEA implements InterfacePopulationChangedEventListener, I
this.m_Population.setFunctionCalls(0); this.m_Population.setFunctionCalls(0);
Population pop; Population pop;
for (int i = 0; i < this.m_Islands.length; i++) { for (int i = 0; i < this.m_Islands.length; i++) {
pop = (Population)this.m_Islands[i].getPopulation().clone(); pop = (Population) this.m_Islands[i].getPopulation().clone();
this.m_Population.addPopulation(pop); this.m_Population.addPopulation(pop);
this.m_Population.incrFunctionCallsBy(pop.getFunctionCalls()); this.m_Population.incrFunctionCallsBy(pop.getFunctionCalls());
} }
@@ -296,46 +294,56 @@ public class IslandModelEA implements InterfacePopulationChangedEventListener, I
this.m_Migration.migrate(this.m_Islands); this.m_Migration.migrate(this.m_Islands);
} }
/** 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 * @param ea
*/ */
@Override @Override
public void addPopulationChangedEventListener(InterfacePopulationChangedEventListener ea) { public void addPopulationChangedEventListener(InterfacePopulationChangedEventListener ea) {
this.m_Listener = ea; this.m_Listener = ea;
} }
@Override @Override
public boolean removePopulationChangedEventListener( public boolean removePopulationChangedEventListener(
InterfacePopulationChangedEventListener ea) { InterfacePopulationChangedEventListener ea) {
if (m_Listener==ea) { if (m_Listener == ea) {
m_Listener=null; m_Listener = null;
return true; return true;
} else { } else {
return false; return false;
} }
} }
/** Something has changed
/**
* Something has changed
*/ */
protected void firePropertyChangedEvent (String name, Population population) { protected void firePropertyChangedEvent(String name, Population population) {
if (this.m_Listener != null) { if (this.m_Listener != null) {
this.m_Listener.registerPopulationStateChanged(this, name); this.m_Listener.registerPopulationStateChanged(this, name);
} }
} }
/** This method will set the problem that is to be optimized /**
* This method will set the problem that is to be optimized
*
* @param problem * @param problem
*/ */
@Override @Override
public void setProblem (InterfaceOptimizationProblem problem) { public void setProblem(InterfaceOptimizationProblem problem) {
this.m_Problem = problem; this.m_Problem = problem;
this.m_Optimizer.setProblem(problem); this.m_Optimizer.setProblem(problem);
} }
@Override @Override
public InterfaceOptimizationProblem getProblem () { public InterfaceOptimizationProblem getProblem() {
return this.m_Problem; return this.m_Problem;
} }
/** This method will return a string describing all properties of the optimizer /**
* and the applied methods. * This method will return a string describing all properties of the
* optimizer and the applied methods.
*
* @return A descriptive string * @return A descriptive string
*/ */
@Override @Override
@@ -350,11 +358,11 @@ public class IslandModelEA implements InterfacePopulationChangedEventListener, I
if (this.m_HeterogenuousProblems) { if (this.m_HeterogenuousProblems) {
result += " Heterogenuous Optimizers: \n"; result += " Heterogenuous Optimizers: \n";
for (int i = 0; i < this.m_Islands.length; i++) { for (int i = 0; i < this.m_Islands.length; i++) {
result += this.m_Islands[i].getStringRepresentation() +"\n"; result += this.m_Islands[i].getStringRepresentation() + "\n";
} }
} else { } else {
result += " Homogeneous Optimizer = " + this.m_Optimizer.getClass().toString() + "\n"; result += " Homogeneous Optimizer = " + this.m_Optimizer.getClass().toString() + "\n";
result += this.m_Optimizer.getStringRepresentation() +"\n"; result += this.m_Optimizer.getStringRepresentation() + "\n";
} }
//result += "=> The Optimization Problem: "; //result += "=> The Optimization Problem: ";
//result += this.m_Problem.getStringRepresentationForProblem(this) +"\n"; //result += this.m_Problem.getStringRepresentationForProblem(this) +"\n";
@@ -362,7 +370,8 @@ public class IslandModelEA implements InterfacePopulationChangedEventListener, I
return result; return result;
} }
/** This method is to test the parallelization scheme /**
* This method is to test the parallelization scheme
* *
* @param args * @param args
*/ */
@@ -374,10 +383,10 @@ public class IslandModelEA implements InterfacePopulationChangedEventListener, I
imea.m_localOnly = false; imea.m_localOnly = false;
if (false) { if (false) {
imea.m_Optimizer = new MultiObjectiveEA(); imea.m_Optimizer = new MultiObjectiveEA();
((MultiObjectiveEA)imea.m_Optimizer).setArchiveSize(25); ((MultiObjectiveEA) imea.m_Optimizer).setArchiveSize(25);
((MultiObjectiveEA)imea.m_Optimizer).getPopulation().setTargetSize(50); ((MultiObjectiveEA) imea.m_Optimizer).getPopulation().setTargetSize(50);
imea.m_Problem = new TF1Problem(); imea.m_Problem = new TF1Problem();
((TF1Problem)imea.m_Problem).setEAIndividual(new ESIndividualDoubleData()); ((TF1Problem) imea.m_Problem).setEAIndividual(new ESIndividualDoubleData());
// ((TF1Problem)imea.m_Problem).setEAIndividual(new ESIndividualDoubleData()); // ((TF1Problem)imea.m_Problem).setEAIndividual(new ESIndividualDoubleData());
// imea.m_Problem = new TFPortfolioSelectionProblem(); // imea.m_Problem = new TFPortfolioSelectionProblem();
// ((TFPortfolioSelectionProblem)imea.m_Problem).setEAIndividual(new ESIndividualDoubleData()); // ((TFPortfolioSelectionProblem)imea.m_Problem).setEAIndividual(new ESIndividualDoubleData());
@@ -399,7 +408,7 @@ public class IslandModelEA implements InterfacePopulationChangedEventListener, I
} }
} else { } else {
imea.m_Problem = new F8Problem(); imea.m_Problem = new F8Problem();
((F1Problem)imea.m_Problem).setEAIndividual(new ESIndividualDoubleData()); ((F1Problem) imea.m_Problem).setEAIndividual(new ESIndividualDoubleData());
} }
imea.m_MigrationRate = 15; imea.m_MigrationRate = 15;
imea.init(); imea.init();
@@ -410,75 +419,82 @@ public class IslandModelEA implements InterfacePopulationChangedEventListener, I
//System.exit(0); //System.exit(0);
} }
/** 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 * @param name The indenifier
*/ */
@Override @Override
public void setIdentifier(String name) { public void setIdentifier(String name) {
this.m_Identifier = name; this.m_Identifier = name;
} }
@Override @Override
public String getIdentifier() { public String getIdentifier() {
return this.m_Identifier; return this.m_Identifier;
} }
/** This method will return the Optimizers /**
* This method will return the Optimizers
*
* @return An array of optimizers * @return An array of optimizers
*/ */
public InterfaceOptimizer[] getOptimizers() { public InterfaceOptimizer[] getOptimizers() {
return this.m_Islands; return this.m_Islands;
} }
/** This method will allow you to toggel between homogenuous and heterogenuous problems. /**
* In case of heterogenuous problems the individuals need to be reevaluated after migration. * This method will allow you to toggel between homogenuous and
* heterogenuous problems. In case of heterogenuous problems the individuals
* need to be reevaluated after migration.
*
* @param t * @param t
*/ */
public void setHeterogenuousProblems(boolean t) { public void setHeterogenuousProblems(boolean t) {
this.m_HeterogenuousProblems = t; this.m_HeterogenuousProblems = t;
} }
/** This method is required to free the memory on a RMIServer, /**
* but there is nothing to implement. * ********************************************************************************************************************
*/
@Override
public void freeWilly() {
for (int i = 0; i < this.m_Islands.length; i++) {
this.m_Islands[i].freeWilly();
}
}
/**********************************************************************************************************************
* These are for InterfacePopulationChangedEventListener * These are for InterfacePopulationChangedEventListener
*/ */
/** This method allows an optimizer to register a change in the EA-lecture /**
* This method allows an optimizer to register a change in the EA-lecture
*
* @param source The source of the event. * @param source The source of the event.
* @param name Could be used to indicate the nature of the event. * @param name Could be used to indicate the nature of the event.
*/ */
@Override @Override
public void registerPopulationStateChanged(Object source, String name) { public void registerPopulationStateChanged(Object source, String name) {
InterfaceOptimizer opt = (InterfaceOptimizer)source; InterfaceOptimizer opt = (InterfaceOptimizer) source;
int sourceID = new Integer(opt.getIdentifier()).intValue(); int sourceID = new Integer(opt.getIdentifier()).intValue();
double cFCOpt = opt.getPopulation().getFunctionCalls(); double cFCOpt = opt.getPopulation().getFunctionCalls();
double plotValue = (this.m_Problem.getDoublePlotValue(opt.getPopulation())).doubleValue(); double plotValue = (this.m_Problem.getDoublePlotValue(opt.getPopulation())).doubleValue();
if (this.m_Show) { if (this.m_Show) {
this.m_Plot.setConnectedPoint(cFCOpt, plotValue, (sourceID+1)); this.m_Plot.setConnectedPoint(cFCOpt, plotValue, (sourceID + 1));
} }
//System.out.println("Someone has finished, ("+this.m_Generation+"/"+this.m_Performed+")"); //System.out.println("Someone has finished, ("+this.m_Generation+"/"+this.m_Performed+")");
//System.out.println(sourceID + " is at generation "+ opt.getPopulation().getGeneration() +" i'm at " +this.m_Generation); //System.out.println(sourceID + " is at generation "+ opt.getPopulation().getGeneration() +" i'm at " +this.m_Generation);
} }
/********************************************************************************************************************** /**
* ********************************************************************************************************************
* These are for GUI * These are for GUI
*/ */
/** This method returns a global info string /**
* This method returns a global info string
*
* @return description * @return description
*/ */
public static String globalInfo() { public static String globalInfo() {
return "This is an island model EA distributing the individuals across several (remote) CPUs for optimization."; return "This is an island model EA distributing the individuals across several (remote) CPUs for optimization.";
} }
/** This method will return a naming String
/**
* This method will return a naming String
*
* @return The name of the algorithm * @return The name of the algorithm
*/ */
@Override @Override
@@ -486,8 +502,10 @@ public class IslandModelEA implements InterfacePopulationChangedEventListener, I
return "IslandEA"; return "IslandEA";
} }
/** This method allows you to toggle between a truly parallel /**
* and a serial implementation. * This method allows you to toggle between a truly parallel and a serial
* implementation.
*
* @return The current optimization mode * @return The current optimization mode
*/ */
// TODO Deactivated from GUI because the current implementation does not really parallelize on a multicore. // TODO Deactivated from GUI because the current implementation does not really parallelize on a multicore.
@@ -495,62 +513,79 @@ public class IslandModelEA implements InterfacePopulationChangedEventListener, I
// public boolean isLocalOnly() { // public boolean isLocalOnly() {
// return this.m_localOnly; // return this.m_localOnly;
// } // }
public void setLocalOnly(boolean b){ public void setLocalOnly(boolean b) {
this.m_localOnly = b; this.m_localOnly = b;
} }
public String localOnlyTipText() { public String localOnlyTipText() {
return "Toggle between usage of local CPUs and remote servers."; return "Toggle between usage of local CPUs and remote servers.";
} }
/** This will show the local performance /**
* This will show the local performance
*
* @return The current optimzation mode * @return The current optimzation mode
*/ */
public boolean getShow() { public boolean getShow() {
return this.m_Show; return this.m_Show;
} }
public void setShow(boolean b){
public void setShow(boolean b) {
this.m_Show = b; this.m_Show = b;
this.m_LogLocalChanges = b; this.m_LogLocalChanges = b;
} }
public String showTipText() { public String showTipText() {
return "This will show the local performance."; return "This will show the local performance.";
} }
/** This method allows you to set/get the optimizing technique to use. /**
* This method allows you to set/get the optimizing technique to use.
*
* @return The current optimizing method * @return The current optimizing method
*/ */
public InterfaceOptimizer getOptimizer() { public InterfaceOptimizer getOptimizer() {
return this.m_Optimizer; return this.m_Optimizer;
} }
public void setOptimizer(InterfaceOptimizer b){
public void setOptimizer(InterfaceOptimizer b) {
this.m_Optimizer = b; this.m_Optimizer = b;
} }
public String optimizerTipText() { public String optimizerTipText() {
return "Choose a population based optimizing technique to use."; return "Choose a population based optimizing technique to use.";
} }
/** This method allows you to set/get the migration strategy to use. /**
* This method allows you to set/get the migration strategy to use.
*
* @return The current migration strategy * @return The current migration strategy
*/ */
public InterfaceMigration getMigrationStrategy() { public InterfaceMigration getMigrationStrategy() {
return this.m_Migration; return this.m_Migration;
} }
public void setMigrationStrategy(InterfaceMigration b){
public void setMigrationStrategy(InterfaceMigration b) {
this.m_Migration = b; this.m_Migration = b;
} }
public String migrationStrategyTipText() { public String migrationStrategyTipText() {
return "Choose a migration strategy to use."; return "Choose a migration strategy to use.";
} }
/** This method allows you to set/get the migration rate to use. /**
* This method allows you to set/get the migration rate to use.
*
* @return The current migration rate * @return The current migration rate
*/ */
public int getMigrationRate() { public int getMigrationRate() {
return this.m_MigrationRate; return this.m_MigrationRate;
} }
public void setMigrationRate(int b){
public void setMigrationRate(int b) {
this.m_MigrationRate = b; this.m_MigrationRate = b;
} }
public String migrationRateTipText() { public String migrationRateTipText() {
return "Set the migration rate for communication between islands."; return "Set the migration rate for communication between islands.";
} }
@@ -559,20 +594,24 @@ public class IslandModelEA implements InterfacePopulationChangedEventListener, I
return "Choose and manage the servers (only active in parallelized mode)."; return "Choose and manage the servers (only active in parallelized mode).";
} }
/** Assuming that all optimizer will store thier data in a population /**
* we will allow acess to this population to query to current state * Assuming that all optimizer will store thier data in a population we will
* of the optimizer. * allow acess to this population to query to current state of the
* optimizer.
*
* @return The population of current solutions to a given problem. * @return The population of current solutions to a given problem.
*/ */
@Override @Override
public Population getPopulation() { public Population getPopulation() {
return this.m_Population; return this.m_Population;
} }
@Override @Override
public void setPopulation(Population pop) { public void setPopulation(Population pop) {
// @todo Jetzt m<>sste ich die pop auch auf die Rechner verteilen... // @todo Jetzt m<>sste ich die pop auch auf die Rechner verteilen...
this.m_Population = pop; this.m_Population = pop;
} }
public String populationTipText() { public String populationTipText() {
return "(Defunct)"; return "(Defunct)";
} }
@@ -581,14 +620,16 @@ public class IslandModelEA implements InterfacePopulationChangedEventListener, I
public InterfaceSolutionSet getAllSolutions() { public InterfaceSolutionSet getAllSolutions() {
return new SolutionSet(getPopulation()); return new SolutionSet(getPopulation());
} }
/** This method allows you to set the number of processors in local mode
/**
* This method allows you to set the number of processors in local mode
*
* @param n Number of processors. * @param n Number of processors.
*/ */
public void setNumberLocalCPUs(int n) { public void setNumberLocalCPUs(int n) {
if (n>=1) { if (n >= 1) {
this.m_numLocalCPUs = n; this.m_numLocalCPUs = n;
} } else {
else {
System.err.println("Number of CPUs must be at least 1!"); System.err.println("Number of CPUs must be at least 1!");
} }
} }
@@ -597,6 +638,7 @@ public class IslandModelEA implements InterfacePopulationChangedEventListener, I
// public int getNumberLocalCPUs() { // public int getNumberLocalCPUs() {
// return this.m_LocalCPUs; // return this.m_LocalCPUs;
// } // }
public String numberLocalCPUsTipText() { public String numberLocalCPUsTipText() {
return "Set the number of local CPUS (>=1, only used in local mode)."; return "Set the number of local CPUS (>=1, only used in local mode).";
} }

View File

@@ -364,10 +364,6 @@ public class LTGA implements InterfaceOptimizer, java.io.Serializable, Interface
return "Linkage Tree GA"; return "Linkage Tree GA";
} }
@Override
public void freeWilly() {
}
@Override @Override
public void registerPopulationStateChanged(Object source, String name) { public void registerPopulationStateChanged(Object source, String name) {
// The events of the interim hill climbing population will be caught here // The events of the interim hill climbing population will be caught here

View File

@@ -246,13 +246,13 @@ public class MLTGA implements InterfaceOptimizer, java.io.Serializable, Interfac
this.problem.evaluatePopulationStart(this.population); this.problem.evaluatePopulationStart(this.population);
Stack<Set<Integer>> linkageTree = buildLinkageTree(); Stack<Set<Integer>> linkageTree = buildLinkageTree();
Population newPop = new Population(this.popSize); Population newPop = new Population(this.popSize);
if(elitism){ if (elitism) {
AbstractEAIndividual firstIndy = this.population.getBestEAIndividual(); AbstractEAIndividual firstIndy = this.population.getBestEAIndividual();
AbstractEAIndividual firstNewIndy = buildNewIndy(firstIndy, linkageTree); AbstractEAIndividual firstNewIndy = buildNewIndy(firstIndy, linkageTree);
newPop.add(firstNewIndy); newPop.add(firstNewIndy);
} }
for (int i = 0; i < this.popSize; i++) { for (int i = 0; i < this.popSize; i++) {
if(this.elitism && i==0){ if (this.elitism && i == 0) {
continue; continue;
} }
Population indies = this.population.getRandNIndividuals(1); Population indies = this.population.getRandNIndividuals(1);
@@ -321,15 +321,15 @@ public class MLTGA implements InterfaceOptimizer, java.io.Serializable, Interfac
this.problem = (AbstractOptimizationProblem) problem; this.problem = (AbstractOptimizationProblem) problem;
} }
public boolean getElitism(){ public boolean getElitism() {
return this.elitism; return this.elitism;
} }
public void setElitism(boolean b){ public void setElitism(boolean b) {
this.elitism = b; this.elitism = b;
} }
public String elitismTipText(){ public String elitismTipText() {
return "use elitism?"; return "use elitism?";
} }
@@ -343,10 +343,6 @@ public class MLTGA implements InterfaceOptimizer, java.io.Serializable, Interfac
return "Linkage Tree GA"; return "Linkage Tree GA";
} }
@Override
public void freeWilly() {
}
@Override @Override
public void registerPopulationStateChanged(Object source, String name) { public void registerPopulationStateChanged(Object source, String name) {
// The events of the interim hill climbing population will be caught here // The events of the interim hill climbing population will be caught here

View File

@@ -12,28 +12,15 @@ import eva2.server.go.problems.InterfaceLocalSearchable;
import eva2.server.go.problems.InterfaceOptimizationProblem; import eva2.server.go.problems.InterfaceOptimizationProblem;
import java.util.Hashtable; import java.util.Hashtable;
/** /**
* A memetic algorithm by hannes planatscher. The local search strategy can only * A memetic algorithm by hannes planatscher. The local search strategy can only
* be applied to problems which implement the InterfaceLocalSearchable else the * be applied to problems which implement the InterfaceLocalSearchable else the
* local search will not be activated at all. * local search will not be activated at all. <p> Title: EvA2 </p> <p>
* <p> * Description: </p> <p> Copyright: Copyright (c) 2003 </p> <p> Company: </p>
* Title: EvA2
* </p>
* <p>
* Description:
* </p>
* <p>
* Copyright: Copyright (c) 2003
* </p>
* <p>
* Company:
* </p>
* *
* @author not attributable * @author not attributable
* @version 1.0 * @version 1.0
*/ */
public class MemeticAlgorithm implements InterfaceOptimizer, public class MemeticAlgorithm implements InterfaceOptimizer,
java.io.Serializable { java.io.Serializable {
@@ -41,32 +28,20 @@ public class MemeticAlgorithm implements InterfaceOptimizer,
* serial version uid. * serial version uid.
*/ */
private static final long serialVersionUID = -1730086430763348568L; private static final long serialVersionUID = -1730086430763348568L;
private int localSearchSteps = 1; private int localSearchSteps = 1;
private int subsetsize = 5; private int subsetsize = 5;
private int globalSearchIterations = 1; private int globalSearchIterations = 1;
private boolean lamarckism = true; private boolean lamarckism = true;
// int counter = 0; !? // int counter = 0; !?
// int maxfunctioncalls = 1000; !? // int maxfunctioncalls = 1000; !?
private boolean TRACE = false; private boolean TRACE = false;
private String m_Identifier = ""; private String m_Identifier = "";
private InterfaceOptimizationProblem m_Problem = new F1Problem(); private InterfaceOptimizationProblem m_Problem = new F1Problem();
private InterfaceOptimizer m_GlobalOptimizer = new GeneticAlgorithm(); private InterfaceOptimizer m_GlobalOptimizer = new GeneticAlgorithm();
private InterfaceSelection selectorPlug = new SelectBestIndividuals(); private InterfaceSelection selectorPlug = new SelectBestIndividuals();
transient private InterfacePopulationChangedEventListener m_Listener; transient private InterfacePopulationChangedEventListener m_Listener;
public MemeticAlgorithm() { public MemeticAlgorithm() {
} }
public MemeticAlgorithm(MemeticAlgorithm a) { public MemeticAlgorithm(MemeticAlgorithm a) {
@@ -108,8 +83,7 @@ public class MemeticAlgorithm implements InterfaceOptimizer,
/** /**
* This method will evaluate the current population using the given problem. * This method will evaluate the current population using the given problem.
* *
* @param population * @param population The population that is to be evaluated
* The population that is to be evaluated
*/ */
private void evaluatePopulation(Population population) { private void evaluatePopulation(Population population) {
this.m_Problem.evaluate(population); this.m_Problem.evaluate(population);
@@ -124,7 +98,7 @@ public class MemeticAlgorithm implements InterfaceOptimizer,
} }
this.m_GlobalOptimizer.optimize(); this.m_GlobalOptimizer.optimize();
if ((globalSearchIterations>0) && (((this.m_GlobalOptimizer.getPopulation().getGeneration() % this.globalSearchIterations) == 0)) if ((globalSearchIterations > 0) && (((this.m_GlobalOptimizer.getPopulation().getGeneration() % this.globalSearchIterations) == 0))
&& (this.localSearchSteps > 0) && (this.localSearchSteps > 0)
&& (this.m_Problem instanceof InterfaceLocalSearchable)) { && (this.m_Problem instanceof InterfaceLocalSearchable)) {
// here the local search is performed // here the local search is performed
@@ -212,16 +186,18 @@ public class MemeticAlgorithm implements InterfaceOptimizer,
InterfacePopulationChangedEventListener ea) { InterfacePopulationChangedEventListener ea) {
this.m_Listener = ea; this.m_Listener = ea;
} }
@Override @Override
public boolean removePopulationChangedEventListener( public boolean removePopulationChangedEventListener(
InterfacePopulationChangedEventListener ea) { InterfacePopulationChangedEventListener ea) {
if (m_Listener==ea) { if (m_Listener == ea) {
m_Listener=null; m_Listener = null;
return true; return true;
} else { } else {
return false; return false;
} }
} }
/** /**
* Something has changed * Something has changed
*/ */
@@ -251,8 +227,8 @@ public class MemeticAlgorithm implements InterfaceOptimizer,
} }
/** /**
* This method will return a string describing all properties of the optimizer * This method will return a string describing all properties of the
* and the applied methods. * optimizer and the applied methods.
* *
* @return A descriptive string * @return A descriptive string
*/ */
@@ -269,8 +245,7 @@ public class MemeticAlgorithm implements InterfaceOptimizer,
/** /**
* This method allows you to set an identifier for the algorithm * This method allows you to set an identifier for the algorithm
* *
* @param name * @param name The indenifier
* The indenifier
*/ */
@Override @Override
public void setIdentifier(String name) { public void setIdentifier(String name) {
@@ -282,14 +257,6 @@ public class MemeticAlgorithm implements InterfaceOptimizer,
return this.m_Identifier; return this.m_Identifier;
} }
/**
* This method is required to free the memory on a RMIServer, but there is
* nothing to implement.
*/
@Override
public void freeWilly() {
}
/* /*
* ======================================================================================== * ========================================================================================
@@ -301,9 +268,9 @@ public class MemeticAlgorithm implements InterfaceOptimizer,
* @return description * @return description
*/ */
public static String globalInfo() { public static String globalInfo() {
return "This is a basic generational Memetic Algorithm. Local search steps are performed on a selected subset " + return "This is a basic generational Memetic Algorithm. Local search steps are performed on a selected subset "
"of individuals after certain numbers of global search iterations. Note " + + "of individuals after certain numbers of global search iterations. Note "
"that the problem class must implement InterfaceLocalSearchable."; + "that the problem class must implement InterfaceLocalSearchable.";
} }
/** /**
@@ -318,7 +285,8 @@ public class MemeticAlgorithm implements InterfaceOptimizer,
/** /**
* Assuming that all optimizer will store thier data in a population we will * Assuming that all optimizer will store thier data in a population we will
* allow acess to this population to query to current state of the optimizer. * allow acess to this population to query to current state of the
* optimizer.
* *
* @return The population of current solutions to a given problem. * @return The population of current solutions to a given problem.
*/ */
@@ -356,16 +324,19 @@ public class MemeticAlgorithm implements InterfaceOptimizer,
} }
/** /**
* Choose the number of local search steps to perform per selected individual. * Choose the number of local search steps to perform per selected
* individual.
* *
* @param localSearchSteps * @param localSearchSteps
*/ */
public void setLocalSearchSteps(int localSearchSteps) { public void setLocalSearchSteps(int localSearchSteps) {
this.localSearchSteps = localSearchSteps; this.localSearchSteps = localSearchSteps;
} }
public int getLocalSearchSteps() { public int getLocalSearchSteps() {
return localSearchSteps; return localSearchSteps;
} }
public String localSearchStepsTipText() { public String localSearchStepsTipText() {
return "Choose the number of local search steps to perform per selected individual."; return "Choose the number of local search steps to perform per selected individual.";
} }
@@ -378,9 +349,11 @@ public class MemeticAlgorithm implements InterfaceOptimizer,
public void setGlobalSearchIterations(int globalSearchSteps) { public void setGlobalSearchIterations(int globalSearchSteps) {
this.globalSearchIterations = globalSearchSteps; this.globalSearchIterations = globalSearchSteps;
} }
public int getGlobalSearchIterations() { public int getGlobalSearchIterations() {
return globalSearchIterations; return globalSearchIterations;
} }
public String globalSearchIterationsTipText() { public String globalSearchIterationsTipText() {
return "Choose the interval between the application of the local search."; return "Choose the interval between the application of the local search.";
} }
@@ -398,9 +371,11 @@ public class MemeticAlgorithm implements InterfaceOptimizer,
public void setSubsetsize(int subsetsize) { public void setSubsetsize(int subsetsize) {
this.subsetsize = subsetsize; this.subsetsize = subsetsize;
} }
public int getSubsetsize() { public int getSubsetsize() {
return subsetsize; return subsetsize;
} }
public String subsetsizeTipText() { public String subsetsizeTipText() {
return "Choose the number of individuals to be locally optimized."; return "Choose the number of individuals to be locally optimized.";
} }
@@ -413,9 +388,11 @@ public class MemeticAlgorithm implements InterfaceOptimizer,
public void setLamarckism(boolean lamarckism) { public void setLamarckism(boolean lamarckism) {
this.lamarckism = lamarckism; this.lamarckism = lamarckism;
} }
public String lamarckismTipText() { public String lamarckismTipText() {
return "Toggle between Lamarckism and the Baldwin Effect."; return "Toggle between Lamarckism and the Baldwin Effect.";
} }
public boolean isLamarckism() { public boolean isLamarckism() {
return lamarckism; return lamarckism;
} }
@@ -423,9 +400,11 @@ public class MemeticAlgorithm implements InterfaceOptimizer,
public InterfaceSelection getSubSetSelector() { public InterfaceSelection getSubSetSelector() {
return selectorPlug; return selectorPlug;
} }
public void setSubSetSelector(InterfaceSelection selectorPlug) { public void setSubSetSelector(InterfaceSelection selectorPlug) {
this.selectorPlug = selectorPlug; this.selectorPlug = selectorPlug;
} }
public String subSetSelectorTipText() { public String subSetSelectorTipText() {
return "Selection method to select the subset on which local search is to be performed."; return "Selection method to select the subset on which local search is to be performed.";
} }

View File

@@ -10,20 +10,20 @@ import eva2.server.go.problems.B1Problem;
import eva2.server.go.problems.InterfaceOptimizationProblem; import eva2.server.go.problems.InterfaceOptimizationProblem;
/** /**
* The simple random or Monte-Carlo search, simple but useful * The simple random or Monte-Carlo search, simple but useful to evaluate the
* to evaluate the complexity of the search space. * complexity of the search space. This implements a Random Walk Search using
* This implements a Random Walk Search using the initialization * the initialization method of the problem instance, meaning that the random
* method of the problem instance, meaning that the random characteristics * characteristics may be problem dependent.
* may be problem dependent. *
* Copyright: Copyright (c) 2003 Company: University of Tuebingen, Computer
* Architecture
* *
* Copyright: Copyright (c) 2003
* Company: University of Tuebingen, Computer Architecture
* @author Felix Streichert * @author Felix Streichert
* @version: $Revision: 307 $ * @version: $Revision: 307 $ $Date: 2007-12-04 14:31:47 +0100 (Tue, 04 Dec
* $Date: 2007-12-04 14:31:47 +0100 (Tue, 04 Dec 2007) $ * 2007) $ $Author: mkron $
* $Author: mkron $
*/ */
public class MonteCarloSearch implements InterfaceOptimizer, java.io.Serializable { public class MonteCarloSearch implements InterfaceOptimizer, java.io.Serializable {
/** /**
* Generated serial version id. * Generated serial version id.
*/ */
@@ -35,7 +35,6 @@ public class MonteCarloSearch implements InterfaceOptimizer, java.io.Serializabl
private int m_FitnessCallsNeeded = 0; private int m_FitnessCallsNeeded = 0;
private Population m_Population; private Population m_Population;
private GAIndividualBinaryData m_Best, m_Test; private GAIndividualBinaryData m_Best, m_Test;
// These variables are necessary for the more complex LectureGUI enviroment // These variables are necessary for the more complex LectureGUI enviroment
transient private String m_Identifier = ""; transient private String m_Identifier = "";
transient private InterfacePopulationChangedEventListener m_Listener; transient private InterfacePopulationChangedEventListener m_Listener;
@@ -46,8 +45,8 @@ public class MonteCarloSearch implements InterfaceOptimizer, java.io.Serializabl
} }
public MonteCarloSearch(MonteCarloSearch a) { public MonteCarloSearch(MonteCarloSearch a) {
this.m_Population = (Population)a.m_Population.clone(); this.m_Population = (Population) a.m_Population.clone();
this.m_Problem = (InterfaceOptimizationProblem)a.m_Problem.clone(); this.m_Problem = (InterfaceOptimizationProblem) a.m_Problem.clone();
} }
@Override @Override
@@ -55,7 +54,8 @@ public class MonteCarloSearch implements InterfaceOptimizer, java.io.Serializabl
return (Object) new MonteCarloSearch(this); return (Object) new MonteCarloSearch(this);
} }
/** This method will init the MonteCarloSearch /**
* This method will init the MonteCarloSearch
*/ */
@Override @Override
public void init() { public void init() {
@@ -64,13 +64,15 @@ public class MonteCarloSearch implements InterfaceOptimizer, java.io.Serializabl
this.firePropertyChangedEvent(Population.nextGenerationPerformed); this.firePropertyChangedEvent(Population.nextGenerationPerformed);
} }
/** 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 pop The initial population
* @param reset If true the population is reset. * @param reset If true the population is reset.
*/ */
@Override @Override
public void initByPopulation(Population pop, boolean reset) { public void initByPopulation(Population pop, boolean reset) {
this.m_Population = (Population)pop.clone(); this.m_Population = (Population) pop.clone();
if (reset) { if (reset) {
this.m_Population.init(); this.m_Population.init();
this.m_Problem.evaluate(this.m_Population); this.m_Problem.evaluate(this.m_Population);
@@ -79,22 +81,22 @@ public class MonteCarloSearch implements InterfaceOptimizer, java.io.Serializabl
} }
/** /**
* This method will optimize without specific operators, by just calling the individual method * This method will optimize without specific operators, by just calling the
* for initialization. * individual method for initialization.
*/ */
@Override @Override
public void optimize() { public void optimize() {
Population original = (Population)this.m_Population.clone(); Population original = (Population) this.m_Population.clone();
// this.m_Problem.initPopulation(this.m_Population); // this.m_Problem.initPopulation(this.m_Population);
for (int i=0; i<m_Population.size(); i++) { for (int i = 0; i < m_Population.size(); i++) {
m_Population.getEAIndividual(i).defaultInit(null); m_Population.getEAIndividual(i).defaultInit(null);
} }
this.m_Population.SetFunctionCalls(original.getFunctionCalls()); this.m_Population.SetFunctionCalls(original.getFunctionCalls());
this.m_Problem.evaluate(this.m_Population); this.m_Problem.evaluate(this.m_Population);
for (int i = 0; i < this.m_Population.size(); i++) { for (int i = 0; i < this.m_Population.size(); i++) {
if (((AbstractEAIndividual)original.get(i)).isDominatingDebConstraints(((AbstractEAIndividual)this.m_Population.get(i)))) { if (((AbstractEAIndividual) original.get(i)).isDominatingDebConstraints(((AbstractEAIndividual) this.m_Population.get(i)))) {
this.m_Population.remove(i); this.m_Population.remove(i);
this.m_Population.add(i, original.get(i)); this.m_Population.add(i, original.get(i));
} }
@@ -103,20 +105,23 @@ public class MonteCarloSearch implements InterfaceOptimizer, java.io.Serializabl
this.firePropertyChangedEvent(Population.nextGenerationPerformed); this.firePropertyChangedEvent(Population.nextGenerationPerformed);
} }
/**
/** This method will set the problem that is to be optimized * This method will set the problem that is to be optimized
*
* @param problem * @param problem
*/ */
@Override @Override
public void setProblem (InterfaceOptimizationProblem problem) { public void setProblem(InterfaceOptimizationProblem problem) {
this.m_Problem = problem; this.m_Problem = problem;
} }
@Override @Override
public InterfaceOptimizationProblem getProblem () { public InterfaceOptimizationProblem getProblem() {
return this.m_Problem; return this.m_Problem;
} }
/** This method will init the HillClimber /**
* This method will init the HillClimber
*/ */
public void defaultInit() { public void defaultInit() {
this.m_FitnessCallsNeeded = 0; this.m_FitnessCallsNeeded = 0;
@@ -124,7 +129,8 @@ public class MonteCarloSearch implements InterfaceOptimizer, java.io.Serializabl
this.m_Best.defaultInit(m_Problem); this.m_Best.defaultInit(m_Problem);
} }
/** This method will optimize /**
* This method will optimize
*/ */
public void defaultOptimize() { public void defaultOptimize() {
for (int i = 0; i < m_FitnessCalls; i++) { for (int i = 0; i < m_FitnessCalls; i++) {
@@ -135,13 +141,14 @@ public class MonteCarloSearch implements InterfaceOptimizer, java.io.Serializabl
} }
this.m_FitnessCallsNeeded = i; this.m_FitnessCallsNeeded = i;
if (this.m_Best.defaultEvaulateAsMiniBits() == 0) { if (this.m_Best.defaultEvaulateAsMiniBits() == 0) {
i = this.m_FitnessCalls +1; i = this.m_FitnessCalls + 1;
} }
} }
} }
/** This main method will start a simple hillclimber. /**
* No arguments necessary. * This main method will start a simple hillclimber. No arguments necessary.
*
* @param args * @param args
*/ */
public static void main(String[] args) { public static void main(String[] args) {
@@ -155,36 +162,43 @@ public class MonteCarloSearch implements InterfaceOptimizer, java.io.Serializabl
} }
TmpMeanCalls /= program.m_MultiRuns; TmpMeanCalls /= program.m_MultiRuns;
TmpMeanFitness /= program.m_MultiRuns; TmpMeanFitness /= program.m_MultiRuns;
System.out.println("("+program.m_MultiRuns+"/"+program.m_FitnessCalls+") Mean Fitness : " + TmpMeanFitness + " Mean Calls needed: " + TmpMeanCalls); System.out.println("(" + program.m_MultiRuns + "/" + program.m_FitnessCalls + ") Mean Fitness : " + TmpMeanFitness + " Mean Calls needed: " + TmpMeanCalls);
} }
/** 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 * @param ea
*/ */
@Override @Override
public void addPopulationChangedEventListener(InterfacePopulationChangedEventListener ea) { public void addPopulationChangedEventListener(InterfacePopulationChangedEventListener ea) {
this.m_Listener = ea; this.m_Listener = ea;
} }
@Override @Override
public boolean removePopulationChangedEventListener( public boolean removePopulationChangedEventListener(
InterfacePopulationChangedEventListener ea) { InterfacePopulationChangedEventListener ea) {
if (m_Listener==ea) { if (m_Listener == ea) {
m_Listener=null; m_Listener = null;
return true; return true;
} else { } else {
return false; return false;
} }
} }
/** Something has changed
/**
* Something has changed
*/ */
protected void firePropertyChangedEvent (String name) { protected void firePropertyChangedEvent(String name) {
if (this.m_Listener != null) { if (this.m_Listener != null) {
this.m_Listener.registerPopulationStateChanged(this, name); this.m_Listener.registerPopulationStateChanged(this, name);
} }
} }
/** This method will return a string describing all properties of the optimizer /**
* and the applied methods. * This method will return a string describing all properties of the
* optimizer and the applied methods.
*
* @return A descriptive string * @return A descriptive string
*/ */
@Override @Override
@@ -192,58 +206,66 @@ public class MonteCarloSearch implements InterfaceOptimizer, java.io.Serializabl
String result = ""; String result = "";
result += "Monte-Carlo Search:\n"; result += "Monte-Carlo Search:\n";
result += "Optimization Problem: "; result += "Optimization Problem: ";
result += this.m_Problem.getStringRepresentationForProblem(this) +"\n"; result += this.m_Problem.getStringRepresentationForProblem(this) + "\n";
result += this.m_Population.getStringRepresentation(); result += this.m_Population.getStringRepresentation();
return result; return result;
} }
/** 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 * @param name The indenifier
*/ */
@Override @Override
public void setIdentifier(String name) { public void setIdentifier(String name) {
this.m_Identifier = name; this.m_Identifier = name;
} }
@Override @Override
public String getIdentifier() { public String getIdentifier() {
return this.m_Identifier; return this.m_Identifier;
} }
/** This method is required to free the memory on a RMIServer, /**
* but there is nothing to implement. * ********************************************************************************************************************
*/
@Override
public void freeWilly() {
}
/**********************************************************************************************************************
* These are for GUI * These are for GUI
*/ */
/** This method returns a global info string /**
* This method returns a global info string
*
* @return description * @return description
*/ */
public static String globalInfo() { public static String globalInfo() {
return "The Monte Carlo Search repeatively creates random individuals and stores the best individuals found."; return "The Monte Carlo Search repeatively creates random individuals and stores the best individuals found.";
} }
/** This method will return a naming String
/**
* This method will return a naming String
*
* @return The name of the algorithm * @return The name of the algorithm
*/ */
@Override @Override
public String getName() { public String getName() {
return "MCS"; return "MCS";
} }
/** Assuming that all optimizer will store thier data in a population
* we will allow acess to this population to query to current state /**
* of the optimizer. * Assuming that all optimizer will store thier data in a population we will
* allow acess to this population to query to current state of the
* optimizer.
*
* @return The population of current solutions to a given problem. * @return The population of current solutions to a given problem.
*/ */
@Override @Override
public Population getPopulation() { public Population getPopulation() {
return this.m_Population; return this.m_Population;
} }
@Override @Override
public void setPopulation(Population pop){ public void setPopulation(Population pop) {
this.m_Population = pop; this.m_Population = pop;
} }
public String populationTipText() { public String populationTipText() {
return "Change the number of best individuals stored."; return "Change the number of best individuals stored.";
} }

View File

@@ -32,21 +32,17 @@ public class MultiObjectiveCMAES implements InterfaceOptimizer, Serializable {
* *
*/ */
class CounterClass { class CounterClass {
public CounterClass(int i) { public CounterClass(int i) {
value = i; value = i;
} }
public int value; public int value;
public boolean seen = false; public boolean seen = false;
} }
private String m_Identifier = "MOCMAES"; private String m_Identifier = "MOCMAES";
private Population m_Population; private Population m_Population;
private AbstractOptimizationProblem m_Problem; private AbstractOptimizationProblem m_Problem;
transient private InterfacePopulationChangedEventListener m_Listener; transient private InterfacePopulationChangedEventListener m_Listener;
private int m_lambda = 1; private int m_lambda = 1;
private int m_lambdamo = 1; private int m_lambdamo = 1;
@@ -105,15 +101,6 @@ public class MultiObjectiveCMAES implements InterfaceOptimizer, Serializable {
this.m_Listener = ea; this.m_Listener = ea;
} }
/*
* (non-Javadoc)
*
* @see eva2.server.go.strategies.InterfaceOptimizer#freeWilly()
*/
@Override
public void freeWilly() {
}
/* /*
* (non-Javadoc) * (non-Javadoc)
* *
@@ -221,8 +208,7 @@ public class MultiObjectiveCMAES implements InterfaceOptimizer, Serializable {
/** /**
* This method will evaluate the current population using the given problem. * This method will evaluate the current population using the given problem.
* *
* @param population * @param population The population that is to be evaluated
* The population that is to be evaluated
*/ */
private void evaluatePopulation(Population population) { private void evaluatePopulation(Population population) {
this.m_Problem.evaluate(population); this.m_Problem.evaluate(population);
@@ -417,5 +403,4 @@ public class MultiObjectiveCMAES implements InterfaceOptimizer, Serializable {
* *
* public void setLambdaMo(int mLambda) { m_lambdamo = mLambda; } * public void setLambdaMo(int mLambda) { m_lambdamo = mLambda; }
*/ */
} }

View File

@@ -16,28 +16,17 @@ import eva2.server.go.problems.FM0Problem;
import eva2.server.go.problems.InterfaceOptimizationProblem; import eva2.server.go.problems.InterfaceOptimizationProblem;
/** /**
* A generic framework for multi-objecitve optimization, you need * A generic framework for multi-objecitve optimization, you need to specify an
* to specify an optimization strategy (like GA), an archiver and * optimization strategy (like GA), an archiver and an information retrival
* an information retrival strategy. With this scheme you can realized: * strategy. With this scheme you can realized: Vector Evaluated GA Random
* Vector Evaluated GA * Weight GA Multiple Objective GA NSGA NSGA-II SPEA SPEA 2 PESA PESA-II In case
* Random Weight GA * you address a multi-objective optimization problem with a single- objective
* Multiple Objective GA * optimizer instead of this MOEA, such an optimizer would randomly toggle
* NSGA * between the objective for each selection and thus explore at least the
* NSGA-II * extreme points of the objective space, but simpler methods like random search
* SPEA * or hill-climbing might even fail on that. Created by IntelliJ IDEA. User:
* SPEA 2 * streiche Date: 05.06.2003 Time: 11:03:50 To change this template use Options
* PESA * | File Templates.
* PESA-II
* In case you address a multi-objective optimization problem with a single-
* objective optimizer instead of this MOEA, such an optimizer would randomly
* toggle between the objective for each selection and thus explore at least
* the extreme points of the objective space, but simpler methods like
* random search or hill-climbing might even fail on that.
* Created by IntelliJ IDEA.
* User: streiche
* Date: 05.06.2003
* Time: 11:03:50
* To change this template use Options | File Templates.
*/ */
public class MultiObjectiveEA implements InterfaceOptimizer, java.io.Serializable { public class MultiObjectiveEA implements InterfaceOptimizer, java.io.Serializable {
@@ -50,15 +39,15 @@ public class MultiObjectiveEA implements InterfaceOptimizer, java.io.Serializabl
public MultiObjectiveEA() { public MultiObjectiveEA() {
this.m_Optimizer.getPopulation().setTargetSize(100); this.m_Optimizer.getPopulation().setTargetSize(100);
((GeneticAlgorithm)this.m_Optimizer).setParentSelection(new SelectMONonDominated()); ((GeneticAlgorithm) this.m_Optimizer).setParentSelection(new SelectMONonDominated());
((GeneticAlgorithm)this.m_Optimizer).setPartnerSelection(new SelectMONonDominated()); ((GeneticAlgorithm) this.m_Optimizer).setPartnerSelection(new SelectMONonDominated());
} }
public MultiObjectiveEA(MultiObjectiveEA a) { public MultiObjectiveEA(MultiObjectiveEA a) {
this.m_Problem = (InterfaceOptimizationProblem)a.m_Problem.clone(); this.m_Problem = (InterfaceOptimizationProblem) a.m_Problem.clone();
this.m_Optimizer = (InterfaceOptimizer)a.m_Optimizer.clone(); this.m_Optimizer = (InterfaceOptimizer) a.m_Optimizer.clone();
this.m_Archiver = (InterfaceArchiving)a.m_Archiver.clone(); this.m_Archiver = (InterfaceArchiving) a.m_Archiver.clone();
this.m_InformationRetrieval = (InterfaceInformationRetrieval)a.m_InformationRetrieval.clone(); this.m_InformationRetrieval = (InterfaceInformationRetrieval) a.m_InformationRetrieval.clone();
} }
public MultiObjectiveEA(InterfaceOptimizer subOpt, InterfaceArchiving archiving, int archiveSize, public MultiObjectiveEA(InterfaceOptimizer subOpt, InterfaceArchiving archiving, int archiveSize,
@@ -82,8 +71,9 @@ public class MultiObjectiveEA implements InterfaceOptimizer, java.io.Serializabl
this.firePropertyChangedEvent(Population.nextGenerationPerformed); this.firePropertyChangedEvent(Population.nextGenerationPerformed);
} }
/**
/** 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 pop The initial population
* @param reset If true the population is reset. * @param reset If true the population is reset.
*/ */
@@ -94,7 +84,8 @@ public class MultiObjectiveEA implements InterfaceOptimizer, java.io.Serializabl
this.firePropertyChangedEvent(Population.nextGenerationPerformed); this.firePropertyChangedEvent(Population.nextGenerationPerformed);
} }
/** The optimize method will compute a 'improved' and evaluated population /**
* The optimize method will compute a 'improved' and evaluated population
*/ */
@Override @Override
public void optimize() { public void optimize() {
@@ -144,7 +135,7 @@ public class MultiObjectiveEA implements InterfaceOptimizer, java.io.Serializabl
double[][] fitness = new double[tmp.size()][]; double[][] fitness = new double[tmp.size()][];
for (int i = 0; i < tmp.size(); i++) { for (int i = 0; i < tmp.size(); i++) {
fitness[i] = ((AbstractEAIndividual)tmp.get(i)).getFitness(); fitness[i] = ((AbstractEAIndividual) tmp.get(i)).getFitness();
} }
double[] minY, maxY; double[] minY, maxY;
minY = fitness[0]; minY = fitness[0];
@@ -172,35 +163,40 @@ public class MultiObjectiveEA implements InterfaceOptimizer, java.io.Serializabl
@Override @Override
public boolean removePopulationChangedEventListener( public boolean removePopulationChangedEventListener(
InterfacePopulationChangedEventListener ea) { InterfacePopulationChangedEventListener ea) {
if (m_Listener==ea) { if (m_Listener == ea) {
m_Listener=null; m_Listener = null;
return true; return true;
} else { } else {
return false; return false;
} }
} }
protected void firePropertyChangedEvent (String name) { protected void firePropertyChangedEvent(String name) {
if (this.m_Listener != null) { if (this.m_Listener != null) {
this.m_Listener.registerPopulationStateChanged(this, name); this.m_Listener.registerPopulationStateChanged(this, name);
} }
} }
/** This method will set the problem that is to be optimized /**
* This method will set the problem that is to be optimized
*
* @param problem * @param problem
*/ */
@Override @Override
public void setProblem (InterfaceOptimizationProblem problem) { public void setProblem(InterfaceOptimizationProblem problem) {
this.m_Problem = problem; this.m_Problem = problem;
this.m_Optimizer.setProblem(problem); this.m_Optimizer.setProblem(problem);
} }
@Override @Override
public InterfaceOptimizationProblem getProblem () { public InterfaceOptimizationProblem getProblem() {
return this.m_Problem; return this.m_Problem;
} }
/** This method will return a string describing all properties of the optimizer /**
* and the applied methods. * This method will return a string describing all properties of the
* optimizer and the applied methods.
*
* @return A descriptive string * @return A descriptive string
*/ */
@Override @Override
@@ -212,42 +208,44 @@ public class MultiObjectiveEA implements InterfaceOptimizer, java.io.Serializabl
result += " Information Retrieval = " + this.m_InformationRetrieval.getClass().toString() + "\n"; result += " Information Retrieval = " + this.m_InformationRetrieval.getClass().toString() + "\n";
result += " Information Retrieval = " + this.getClass().toString() + "\n"; result += " Information Retrieval = " + this.getClass().toString() + "\n";
result += " Optimizer = " + this.m_Optimizer.getClass().toString() + "\n"; result += " Optimizer = " + this.m_Optimizer.getClass().toString() + "\n";
result += this.m_Optimizer.getStringRepresentation() +"\n"; result += this.m_Optimizer.getStringRepresentation() + "\n";
//result += "=> The Optimization Problem: "; //result += "=> The Optimization Problem: ";
//result += this.m_Problem.getStringRepresentationForProblem(this) +"\n"; //result += this.m_Problem.getStringRepresentationForProblem(this) +"\n";
//result += this.m_Population.getStringRepresentation(); //result += this.m_Population.getStringRepresentation();
return result; return result;
} }
/** 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 * @param name The indenifier
*/ */
@Override @Override
public void setIdentifier(String name) { public void setIdentifier(String name) {
this.m_Identifier = name; this.m_Identifier = name;
} }
@Override @Override
public String getIdentifier() { public String getIdentifier() {
return this.m_Identifier; return this.m_Identifier;
} }
/** This method is required to free the memory on a RMIServer, /**
* but there is nothing to implement. * ********************************************************************************************************************
*/
@Override
public void freeWilly() {
}
/**********************************************************************************************************************
* These are for GUI * These are for GUI
*/ */
/** This method returns a global info string /**
* This method returns a global info string
*
* @return description * @return description
*/ */
public static String globalInfo() { public static String globalInfo() {
return "This is a general Multi-objective Evolutionary Optimization Framework."; return "This is a general Multi-objective Evolutionary Optimization Framework.";
} }
/** This method will return a naming String
/**
* This method will return a naming String
*
* @return The name of the algorithm * @return The name of the algorithm
*/ */
@Override @Override
@@ -255,19 +253,23 @@ public class MultiObjectiveEA implements InterfaceOptimizer, java.io.Serializabl
return "MOEA"; return "MOEA";
} }
/** Assuming that all optimizer will store thier data in a population /**
* we will allow acess to this population to query to current state * Assuming that all optimizer will store thier data in a population we will
* of the optimizer. * allow acess to this population to query to current state of the
* optimizer.
*
* @return The population of current solutions to a given problem. * @return The population of current solutions to a given problem.
*/ */
@Override @Override
public Population getPopulation() { public Population getPopulation() {
return this.m_Optimizer.getPopulation(); return this.m_Optimizer.getPopulation();
} }
@Override @Override
public void setPopulation(Population pop){ public void setPopulation(Population pop) {
this.m_Optimizer.setPopulation(pop); this.m_Optimizer.setPopulation(pop);
} }
public String populationTipText() { public String populationTipText() {
return "Edit the properties of the Population used."; return "Edit the properties of the Population used.";
} }
@@ -277,47 +279,61 @@ public class MultiObjectiveEA implements InterfaceOptimizer, java.io.Serializabl
return new SolutionSet(getPopulation(), ArchivingNSGAII.getNonDominatedSortedFront(getPopulation().getArchive()).getSortedPop(new AbstractEAIndividualComparator(0))); return new SolutionSet(getPopulation(), ArchivingNSGAII.getNonDominatedSortedFront(getPopulation().getArchive()).getSortedPop(new AbstractEAIndividualComparator(0)));
} }
/** This method allows you to set/get the optimizing technique to use. /**
* This method allows you to set/get the optimizing technique to use.
*
* @return The current optimizing method * @return The current optimizing method
*/ */
public InterfaceOptimizer getOptimizer() { public InterfaceOptimizer getOptimizer() {
return this.m_Optimizer; return this.m_Optimizer;
} }
public void setOptimizer(InterfaceOptimizer b){
public void setOptimizer(InterfaceOptimizer b) {
this.m_Optimizer = b; this.m_Optimizer = b;
} }
public String optimizerTipText() { public String optimizerTipText() {
return "Choose a population based optimizing technique to use."; return "Choose a population based optimizing technique to use.";
} }
/** This method allows you to set/get the archiving strategy to use. /**
* This method allows you to set/get the archiving strategy to use.
*
* @return The current optimizing method * @return The current optimizing method
*/ */
public InterfaceArchiving getArchivingStrategy() { public InterfaceArchiving getArchivingStrategy() {
return this.m_Archiver; return this.m_Archiver;
} }
public void setArchivingStrategy(InterfaceArchiving b){
public void setArchivingStrategy(InterfaceArchiving b) {
this.m_Archiver = b; this.m_Archiver = b;
} }
public String archivingStrategyTipText() { public String archivingStrategyTipText() {
return "Choose the archiving strategy."; return "Choose the archiving strategy.";
} }
/**
/** This method allows you to set/get the Information Retrieval strategy to use. * This method allows you to set/get the Information Retrieval strategy to
* use.
*
* @return The current optimizing method * @return The current optimizing method
*/ */
public InterfaceInformationRetrieval getInformationRetrieval() { public InterfaceInformationRetrieval getInformationRetrieval() {
return this.m_InformationRetrieval; return this.m_InformationRetrieval;
} }
public void setInformationRetrieval(InterfaceInformationRetrieval b){
public void setInformationRetrieval(InterfaceInformationRetrieval b) {
this.m_InformationRetrieval = b; this.m_InformationRetrieval = b;
} }
public String informationRetrievalTipText() { public String informationRetrievalTipText() {
return "Choose the Information Retrieval strategy."; return "Choose the Information Retrieval strategy.";
} }
/** This method allows you to set/get the size of the archive. /**
* This method allows you to set/get the size of the archive.
*
* @return The current optimizing method * @return The current optimizing method
*/ */
public int getArchiveSize() { public int getArchiveSize() {
@@ -328,7 +344,8 @@ public class MultiObjectiveEA implements InterfaceOptimizer, java.io.Serializabl
} }
return archive.getTargetSize(); return archive.getTargetSize();
} }
public void setArchiveSize(int b){
public void setArchiveSize(int b) {
Population archive = this.m_Optimizer.getPopulation().getArchive(); Population archive = this.m_Optimizer.getPopulation().getArchive();
if (archive == null) { if (archive == null) {
archive = new Population(); archive = new Population();
@@ -336,6 +353,7 @@ public class MultiObjectiveEA implements InterfaceOptimizer, java.io.Serializabl
} }
archive.setTargetSize(b); archive.setTargetSize(b);
} }
public String archiveSizeTipText() { public String archiveSizeTipText() {
return "Choose the size of the archive."; return "Choose the size of the archive.";
} }

View File

@@ -15,9 +15,9 @@ import java.io.Serializable;
import java.util.Vector; import java.util.Vector;
/** /**
* Nelder-Mead-Simplex does not guarantee an equal number of evaluations within each optimize call * Nelder-Mead-Simplex does not guarantee an equal number of evaluations within
* because of the different step types. * each optimize call because of the different step types. Range check is now
* Range check is now available by projection at the bounds. * available by projection at the bounds.
* *
* @author mkron * @author mkron
* *
@@ -27,9 +27,7 @@ public class NelderMeadSimplex implements InterfaceOptimizer, Serializable, Inte
private int populationSize = 100; private int populationSize = 100;
// simulating the generational cycle. Set rather small (eg 5) for use as local search, higher for global search (eg 50) // simulating the generational cycle. Set rather small (eg 5) for use as local search, higher for global search (eg 50)
private int generationCycle = 50; private int generationCycle = 50;
private int fitIndex = 0; // choose criterion for multi objective functions private int fitIndex = 0; // choose criterion for multi objective functions
private Population m_Population; private Population m_Population;
private AbstractOptimizationProblem m_Problem; private AbstractOptimizationProblem m_Problem;
private transient Vector<InterfacePopulationChangedEventListener> m_Listener; private transient Vector<InterfacePopulationChangedEventListener> m_Listener;
@@ -41,13 +39,13 @@ public class NelderMeadSimplex implements InterfaceOptimizer, Serializable, Inte
} }
public NelderMeadSimplex(int popSize) { public NelderMeadSimplex(int popSize) {
populationSize=popSize; populationSize = popSize;
setPopulation(new Population(populationSize)); setPopulation(new Population(populationSize));
} }
public NelderMeadSimplex(NelderMeadSimplex a) { public NelderMeadSimplex(NelderMeadSimplex a) {
m_Problem = (AbstractOptimizationProblem)a.m_Problem.clone(); m_Problem = (AbstractOptimizationProblem) a.m_Problem.clone();
setPopulation((Population)a.m_Population.clone()); setPopulation((Population) a.m_Population.clone());
populationSize = a.populationSize; populationSize = a.populationSize;
generationCycle = a.generationCycle; generationCycle = a.generationCycle;
m_Identifier = a.m_Identifier; m_Identifier = a.m_Identifier;
@@ -65,18 +63,18 @@ public class NelderMeadSimplex implements InterfaceOptimizer, Serializable, Inte
@Override @Override
public void setProblem(InterfaceOptimizationProblem problem) { public void setProblem(InterfaceOptimizationProblem problem) {
m_Problem = (AbstractOptimizationProblem)problem; m_Problem = (AbstractOptimizationProblem) problem;
} }
public boolean setProblemAndPopSize(InterfaceOptimizationProblem problem) { public boolean setProblemAndPopSize(InterfaceOptimizationProblem problem) {
setProblem(problem); setProblem(problem);
if (m_Problem instanceof AbstractProblemDouble) { if (m_Problem instanceof AbstractProblemDouble) {
setPopulationSize(((AbstractProblemDouble)problem).getProblemDimension()+1); setPopulationSize(((AbstractProblemDouble) problem).getProblemDimension() + 1);
return true; return true;
} else { } else {
Object ret=BeanInspector.callIfAvailable(problem, "getProblemDimension", null); Object ret = BeanInspector.callIfAvailable(problem, "getProblemDimension", null);
if (ret!=null) { if (ret != null) {
setPopulationSize(((Integer)ret)+1); setPopulationSize(((Integer) ret) + 1);
return true; return true;
} }
} }
@@ -86,7 +84,7 @@ public class NelderMeadSimplex implements InterfaceOptimizer, Serializable, Inte
@Override @Override
public void addPopulationChangedEventListener( public void addPopulationChangedEventListener(
InterfacePopulationChangedEventListener ea) { InterfacePopulationChangedEventListener ea) {
if (ea!=null) { if (ea != null) {
if (m_Listener == null) { if (m_Listener == null) {
m_Listener = new Vector<InterfacePopulationChangedEventListener>(); m_Listener = new Vector<InterfacePopulationChangedEventListener>();
} }
@@ -99,21 +97,17 @@ public class NelderMeadSimplex implements InterfaceOptimizer, Serializable, Inte
@Override @Override
public boolean removePopulationChangedEventListener( public boolean removePopulationChangedEventListener(
InterfacePopulationChangedEventListener ea) { InterfacePopulationChangedEventListener ea) {
if (m_Listener==null) { if (m_Listener == null) {
return false; return false;
} } else {
else {
return m_Listener.remove(ea); return m_Listener.remove(ea);
} }
} }
@Override
public void freeWilly() {}
protected double[] calcChallengeVect(double[] centroid, double[] refX) { protected double[] calcChallengeVect(double[] centroid, double[] refX) {
double[] r = new double[centroid.length]; double[] r = new double[centroid.length];
for (int i=0; i<r.length; i++) { for (int i = 0; i < r.length; i++) {
r[i] = 2*centroid[i] - refX[i]; r[i] = 2 * centroid[i] - refX[i];
} }
// double alpha = 1.3; // double alpha = 1.3;
// for (int i=0; i<r.length; i++) r[i] = centroid[i] + alpha*(centroid[i] - refX[i]); // for (int i=0; i<r.length; i++) r[i] = centroid[i] + alpha*(centroid[i] - refX[i]);
@@ -121,11 +115,11 @@ public class NelderMeadSimplex implements InterfaceOptimizer, Serializable, Inte
} }
protected boolean firstIsBetter(double[] first, double[] second) { protected boolean firstIsBetter(double[] first, double[] second) {
return first[fitIndex]<second[fitIndex]; return first[fitIndex] < second[fitIndex];
} }
protected boolean firstIsBetterEqual(double[] first, double[] second) { protected boolean firstIsBetterEqual(double[] first, double[] second) {
return first[fitIndex]<=second[fitIndex]; return first[fitIndex] <= second[fitIndex];
} }
protected boolean firstIsBetter(AbstractEAIndividual first, AbstractEAIndividual second) { protected boolean firstIsBetter(AbstractEAIndividual first, AbstractEAIndividual second) {
@@ -141,10 +135,10 @@ public class NelderMeadSimplex implements InterfaceOptimizer, Serializable, Inte
// hole die n-1 besten individuen der fitness dimension fitIndex // hole die n-1 besten individuen der fitness dimension fitIndex
subpop.setSortingFitnessCriterion(fitIndex); subpop.setSortingFitnessCriterion(fitIndex);
Population bestpop = subpop.getBestNIndividuals(subpop.size()-1, fitIndex); Population bestpop = subpop.getBestNIndividuals(subpop.size() - 1, fitIndex);
// und das schlechteste // und das schlechteste
AbstractEAIndividual worst = subpop.getWorstEAIndividual(fitIndex); AbstractEAIndividual worst = subpop.getWorstEAIndividual(fitIndex);
AbstractEAIndividual best=subpop.getBestEAIndividual(fitIndex); AbstractEAIndividual best = subpop.getBestEAIndividual(fitIndex);
double[][] range = ((InterfaceDataTypeDouble) worst).getDoubleRange(); double[][] range = ((InterfaceDataTypeDouble) worst).getDoubleRange();
double[] x_worst = ((InterfaceDataTypeDouble) worst).getDoubleData(); double[] x_worst = ((InterfaceDataTypeDouble) worst).getDoubleData();
@@ -152,11 +146,11 @@ public class NelderMeadSimplex implements InterfaceOptimizer, Serializable, Inte
// Centroid berechnen // Centroid berechnen
double[] centroid = new double[dim]; double[] centroid = new double[dim];
for (int i=0; i<bestpop.size(); i++) { for (int i = 0; i < bestpop.size(); i++) {
for (int j=0; j<dim; j++) { for (int j = 0; j < dim; j++) {
AbstractEAIndividual bestIndi= (AbstractEAIndividual) bestpop.getIndividual(i); AbstractEAIndividual bestIndi = (AbstractEAIndividual) bestpop.getIndividual(i);
double[] bestIndyPos = ((InterfaceDataTypeDouble)bestIndi).getDoubleDataWithoutUpdate(); double[] bestIndyPos = ((InterfaceDataTypeDouble) bestIndi).getDoubleDataWithoutUpdate();
centroid[j] +=bestIndyPos[j]/bestpop.size(); // bug? centroid[j] += bestIndyPos[j] / bestpop.size(); // bug?
} }
} }
@@ -179,8 +173,8 @@ public class NelderMeadSimplex implements InterfaceOptimizer, Serializable, Inte
return reflectedInd; return reflectedInd;
} else if (firstIsBetter(reflectedInd, best)) { //neues besser als bisher bestes => Expansion } else if (firstIsBetter(reflectedInd, best)) { //neues besser als bisher bestes => Expansion
double[] e = new double[dim]; double[] e = new double[dim];
for (int i=0; i<dim; i++) { for (int i = 0; i < dim; i++) {
e[i] = 3*centroid[i] - 2*x_worst[i]; e[i] = 3 * centroid[i] - 2 * x_worst[i];
} }
if (checkConstraints && !Mathematics.isInRange(e, range)) { if (checkConstraints && !Mathematics.isInRange(e, range)) {
Mathematics.projectToRange(e, range); Mathematics.projectToRange(e, range);
@@ -197,8 +191,8 @@ public class NelderMeadSimplex implements InterfaceOptimizer, Serializable, Inte
} else if (firstIsBetterEqual(bestpop.getWorstEAIndividual(fitIndex), reflectedInd)) { } else if (firstIsBetterEqual(bestpop.getWorstEAIndividual(fitIndex), reflectedInd)) {
//kontrahiere da neues indi keine verbesserung brachte //kontrahiere da neues indi keine verbesserung brachte
double[] c = new double[dim]; double[] c = new double[dim];
for (int i=0; i<dim; i++) { for (int i = 0; i < dim; i++) {
c[i] = 0.5*centroid[i] + 0.5*x_worst[i]; c[i] = 0.5 * centroid[i] + 0.5 * x_worst[i];
} }
if (checkConstraints && !Mathematics.isInRange(c, range)) { if (checkConstraints && !Mathematics.isInRange(c, range)) {
Mathematics.projectToRange(c, range); Mathematics.projectToRange(c, range);
@@ -209,7 +203,7 @@ public class NelderMeadSimplex implements InterfaceOptimizer, Serializable, Inte
// m_Problem.evaluate(c_ind); // m_Problem.evaluate(c_ind);
AbstractEAIndividual c_ind = createEvalIndy(bestpop, c); AbstractEAIndividual c_ind = createEvalIndy(bestpop, c);
this.m_Population.incrFunctionCalls(); this.m_Population.incrFunctionCalls();
if(firstIsBetterEqual(c_ind, worst)) { if (firstIsBetterEqual(c_ind, worst)) {
return c_ind; return c_ind;
} }
} }
@@ -217,11 +211,11 @@ public class NelderMeadSimplex implements InterfaceOptimizer, Serializable, Inte
} }
private AbstractEAIndividual createEvalIndy(Population pop, double[] newGenotype) { private AbstractEAIndividual createEvalIndy(Population pop, double[] newGenotype) {
AbstractEAIndividual e_ind = (AbstractEAIndividual)((AbstractEAIndividual)pop.getIndividual(1)).clone(); AbstractEAIndividual e_ind = (AbstractEAIndividual) ((AbstractEAIndividual) pop.getIndividual(1)).clone();
((InterfaceDataTypeDouble)e_ind).SetDoubleGenotype(newGenotype); ((InterfaceDataTypeDouble) e_ind).SetDoubleGenotype(newGenotype);
e_ind.resetConstraintViolation(); e_ind.resetConstraintViolation();
m_Problem.evaluate(e_ind); m_Problem.evaluate(e_ind);
if (e_ind.getFitness(0)<6000) { if (e_ind.getFitness(0) < 6000) {
m_Problem.evaluate(e_ind); m_Problem.evaluate(e_ind);
} }
return e_ind; return e_ind;
@@ -279,7 +273,7 @@ public class NelderMeadSimplex implements InterfaceOptimizer, Serializable, Inte
private void fireNextGenerationPerformed() { private void fireNextGenerationPerformed() {
if (m_Listener != null) { if (m_Listener != null) {
for (int i=0; i<m_Listener.size(); i++) { for (int i = 0; i < m_Listener.size(); i++) {
m_Listener.elementAt(i).registerPopulationStateChanged(this, Population.nextGenerationPerformed); m_Listener.elementAt(i).registerPopulationStateChanged(this, Population.nextGenerationPerformed);
} }
} }
@@ -294,9 +288,9 @@ public class NelderMeadSimplex implements InterfaceOptimizer, Serializable, Inte
m_Problem.evaluatePopulationStart(m_Population); m_Problem.evaluatePopulationStart(m_Population);
do { do {
AbstractEAIndividual ind = simplexStep(m_Population); AbstractEAIndividual ind = simplexStep(m_Population);
if(ind!=null){ //Verbesserung gefunden if (ind != null) { //Verbesserung gefunden
double[] x=((InterfaceDataTypeDouble)ind).getDoubleData(); double[] x = ((InterfaceDataTypeDouble) ind).getDoubleData();
double[][] range = ((InterfaceDataTypeDouble)ind).getDoubleRange(); double[][] range = ((InterfaceDataTypeDouble) ind).getDoubleRange();
if (!Mathematics.isInRange(x, range)) { if (!Mathematics.isInRange(x, range)) {
System.err.println("WARNING: nelder mead step produced indy out of range!"); System.err.println("WARNING: nelder mead step produced indy out of range!");
// Mathematics.projectToRange(x, range); // Mathematics.projectToRange(x, range);
@@ -305,14 +299,14 @@ public class NelderMeadSimplex implements InterfaceOptimizer, Serializable, Inte
// this.m_Population.incrFunctionCalls(); // this.m_Population.incrFunctionCalls();
} }
m_Population.set(m_Population.getIndexOfWorstIndividualNoConstr(fitIndex), ind, fitIndex); m_Population.set(m_Population.getIndexOfWorstIndividualNoConstr(fitIndex), ind, fitIndex);
}else{//keine Verbesserung gefunden shrink!! } else {//keine Verbesserung gefunden shrink!!
double[] u_1 = ((InterfaceDataTypeDouble) m_Population.getBestEAIndividual(fitIndex)).getDoubleData(); double[] u_1 = ((InterfaceDataTypeDouble) m_Population.getBestEAIndividual(fitIndex)).getDoubleData();
for(int j=0;j<m_Population.size();j++){ for (int j = 0; j < m_Population.size(); j++) {
double [] c= ((InterfaceDataTypeDouble) m_Population.getEAIndividual(j)).getDoubleData(); double[] c = ((InterfaceDataTypeDouble) m_Population.getEAIndividual(j)).getDoubleData();
for (int i=0; i<c.length; i++) { for (int i = 0; i < c.length; i++) {
c[i] = 0.5*c[i] + 0.5*u_1[i]; c[i] = 0.5 * c[i] + 0.5 * u_1[i];
} }
((InterfaceDataTypeDouble) m_Population.getEAIndividual(j)).SetDoubleGenotype(c); ((InterfaceDataTypeDouble) m_Population.getEAIndividual(j)).SetDoubleGenotype(c);
// m_Population.getEAIndividual(j).resetConstraintViolation(); // not a good idea because during evaluation, a stats update may be performed which mustnt see indies which are evaluated, but possible constraints have been reset. // m_Population.getEAIndividual(j).resetConstraintViolation(); // not a good idea because during evaluation, a stats update may be performed which mustnt see indies which are evaluated, but possible constraints have been reset.
@@ -350,7 +344,7 @@ public class NelderMeadSimplex implements InterfaceOptimizer, Serializable, Inte
*/ */
public void setPopulationSize(int populationSize) { public void setPopulationSize(int populationSize) {
this.populationSize = populationSize; this.populationSize = populationSize;
if (m_Population!=null) { if (m_Population != null) {
m_Population.setTargetSize(populationSize); m_Population.setTargetSize(populationSize);
m_Population.setNotifyEvalInterval(m_Population.getTargetSize()); m_Population.setNotifyEvalInterval(m_Population.getTargetSize());
} }
@@ -370,10 +364,8 @@ public class NelderMeadSimplex implements InterfaceOptimizer, Serializable, Inte
/** /**
* This method creates a Nelder-Mead instance. * This method creates a Nelder-Mead instance.
* *
* @param pop * @param pop The size of the population
* The size of the population * @param problem The problem to be optimized
* @param problem
* The problem to be optimized
* @param listener * @param listener
* @return An optimization procedure that performs nelder mead optimization. * @return An optimization procedure that performs nelder mead optimization.
*/ */
@@ -384,12 +376,12 @@ public class NelderMeadSimplex implements InterfaceOptimizer, Serializable, Inte
NelderMeadSimplex nms = new NelderMeadSimplex(); NelderMeadSimplex nms = new NelderMeadSimplex();
nms.setProblemAndPopSize(problem); nms.setProblemAndPopSize(problem);
if (listener!=null) { if (listener != null) {
nms.addPopulationChangedEventListener(listener); nms.addPopulationChangedEventListener(listener);
} }
nms.init(); nms.init();
if (listener!=null) { if (listener != null) {
listener.registerPopulationStateChanged(nms.getPopulation(), ""); listener.registerPopulationStateChanged(nms.getPopulation(), "");
} }
@@ -398,15 +390,15 @@ public class NelderMeadSimplex implements InterfaceOptimizer, Serializable, Inte
/** /**
* This method creates a Nelder-Mead instance with an initial population * This method creates a Nelder-Mead instance with an initial population
* around a given candidate solution. The population is created as a simplex with given * around a given candidate solution. The population is created as a simplex
* perturbation ratio or randomly across the search range if the perturbation ratio is * with given perturbation ratio or randomly across the search range if the
* zero or below zero. * perturbation ratio is zero or below zero.
* *
* *
* @param problem * @param problem The problem to be optimized
* The problem to be optimized
* @param candidate starting point of the search * @param candidate starting point of the search
* @param perturbationRatio perturbation ratio relative to the problem range for the initial simplex creation * @param perturbationRatio perturbation ratio relative to the problem range
* for the initial simplex creation
* @param listener * @param listener
* @return An optimization procedure that performs nelder mead optimization. * @return An optimization procedure that performs nelder mead optimization.
*/ */
@@ -425,8 +417,8 @@ public class NelderMeadSimplex implements InterfaceOptimizer, Serializable, Inte
problem.initPopulation(initialPop); problem.initPopulation(initialPop);
initialPop.set(0, candidate); initialPop.set(0, candidate);
} else { } else {
double[][] range = ((InterfaceDataTypeDouble)candidate).getDoubleRange(); double[][] range = ((InterfaceDataTypeDouble) candidate).getDoubleRange();
if (range.length != nms.getPopulationSize()-1) { if (range.length != nms.getPopulationSize() - 1) {
System.err.println("Unexpected population size for nelder mead!"); System.err.println("Unexpected population size for nelder mead!");
} }
initialPop = createNMSPopulation(candidate, perturbationRatio, range, true); initialPop = createNMSPopulation(candidate, perturbationRatio, range, true);
@@ -441,11 +433,12 @@ public class NelderMeadSimplex implements InterfaceOptimizer, Serializable, Inte
} }
/** /**
* From a given candidate solution, create n solutions around the candidate, where every i-th * From a given candidate solution, create n solutions around the candidate,
* new candidate differs in i dimensions by a distance of perturbRatio relative to the range in * where every i-th new candidate differs in i dimensions by a distance of
* that dimension (respecting the range). * perturbRatio relative to the range in that dimension (respecting the
* The new solutions are returned as a population, which, if includeCand is true, * range). The new solutions are returned as a population, which, if
* also contains the initial candidate. However, the new candidates have not been evaluated. * includeCand is true, also contains the initial candidate. However, the
* new candidates have not been evaluated.
* *
* @param candidate * @param candidate
* @param perturbRelative * @param perturbRelative
@@ -467,20 +460,20 @@ public class NelderMeadSimplex implements InterfaceOptimizer, Serializable, Inte
private static void addPerturbedPopulation(double perturbationRatio, private static void addPerturbedPopulation(double perturbationRatio,
Population initialPop, double[][] range, AbstractEAIndividual candidate) { Population initialPop, double[][] range, AbstractEAIndividual candidate) {
AbstractEAIndividual indy = (AbstractEAIndividual)candidate.clone(); AbstractEAIndividual indy = (AbstractEAIndividual) candidate.clone();
// span by perturbation, every new individual i is modified in dimension i by // span by perturbation, every new individual i is modified in dimension i by
// a value of perturbRatio*range_i such that a simplex of relative side length perturbRatio is created. // a value of perturbRatio*range_i such that a simplex of relative side length perturbRatio is created.
for (int i=0; i<range.length; i+=1) { for (int i = 0; i < range.length; i += 1) {
double curPerturb = ((range[i][1]-range[i][0])*perturbationRatio); double curPerturb = ((range[i][1] - range[i][0]) * perturbationRatio);
double[] dat = ((InterfaceDataTypeDouble)indy).getDoubleData(); double[] dat = ((InterfaceDataTypeDouble) indy).getDoubleData();
if (dat[i]==range[i][1]) { // in this case the bound is said to be too close if (dat[i] == range[i][1]) { // in this case the bound is said to be too close
dat[i]=Math.max(dat[i]-curPerturb, range[i][0]); dat[i] = Math.max(dat[i] - curPerturb, range[i][0]);
} else { } else {
dat[i] = Math.min(dat[i]+curPerturb, range[i][1]); dat[i] = Math.min(dat[i] + curPerturb, range[i][1]);
} }
((InterfaceDataTypeDouble)indy).SetDoubleGenotype(dat); ((InterfaceDataTypeDouble) indy).SetDoubleGenotype(dat);
indy.resetConstraintViolation(); indy.resetConstraintViolation();
initialPop.add((AbstractEAIndividual)indy.clone()); initialPop.add((AbstractEAIndividual) indy.clone());
} }
initialPop.synchSize(); initialPop.synchSize();
} }
@@ -515,5 +508,4 @@ public class NelderMeadSimplex implements InterfaceOptimizer, Serializable, Inte
public String critIndexTipText() { public String critIndexTipText() {
return "For multi-criterial problems, set the index of the fitness to be used in 0..n-1. Default is 0"; return "For multi-criterial problems, set the index of the fitness to be used in 0..n-1. Default is 0";
} }
} }

File diff suppressed because it is too large Load Diff

View File

@@ -1,6 +1,5 @@
package eva2.server.go.strategies; package eva2.server.go.strategies;
import eva2.gui.BeanInspector; import eva2.gui.BeanInspector;
import eva2.gui.GenericObjectEditor; import eva2.gui.GenericObjectEditor;
import eva2.gui.Plot; import eva2.gui.Plot;
@@ -22,28 +21,27 @@ import eva2.server.go.problems.InterfaceOptimizationProblem;
/** /**
* This is a Particle Filter implemented by Frank Senke, only some documentation * This is a Particle Filter implemented by Frank Senke, only some documentation
* here and not completely checked whether this works on arbitrary problem * here and not completely checked whether this works on arbitrary problem
* instances. MK did some adaptations, this should work on real valued problems now. * instances. MK did some adaptations, this should work on real valued problems
* now.
* *
* This is a implementation of Genetic Algorithms. * This is a implementation of Genetic Algorithms. Copyright: Copyright (c) 2003
* Copyright: Copyright (c) 2003
* Company: University of Tuebingen, Computer Architecture * Company: University of Tuebingen, Computer Architecture
*
* @author Felix Streichert * @author Felix Streichert
* @version: $Revision: 307 $ * @version: $Revision: 307 $ $Date: 2007-12-04 14:31:47 +0100 (Tue, 04 Dec
* $Date: 2007-12-04 14:31:47 +0100 (Tue, 04 Dec 2007) $ * 2007) $ $Author: mkron $
* $Author: mkron $
*/ */
public class ParticleFilterOptimization implements InterfaceOptimizer, java.io.Serializable { public class ParticleFilterOptimization implements InterfaceOptimizer, java.io.Serializable {
/** /**
* Comment for <code>serialVersionUID</code> * Comment for
* <code>serialVersionUID</code>
*/ */
private static final long serialVersionUID = 1L; private static final long serialVersionUID = 1L;
private Population m_Population = new Population(); private Population m_Population = new Population();
private InterfaceOptimizationProblem m_Problem = new F1Problem(); private InterfaceOptimizationProblem m_Problem = new F1Problem();
private InterfaceSelection m_ParentSelection = new SelectParticleWheel(0.5); private InterfaceSelection m_ParentSelection = new SelectParticleWheel(0.5);
//private boolean m_UseElitism = true; //private boolean m_UseElitism = true;
private String m_Identifier = ""; private String m_Identifier = "";
private boolean withShow = false; private boolean withShow = false;
private double mutationSigma = 0.01; private double mutationSigma = 0.01;
@@ -51,9 +49,7 @@ public class ParticleFilterOptimization implements InterfaceOptimizer, java.io.S
private double initialVelocity = 0.02; private double initialVelocity = 0.02;
private double rotationDeg = 20.; private double rotationDeg = 20.;
private int popSize = 300; private int popSize = 300;
private int sleepTime = 0; private int sleepTime = 0;
transient private int indCount = 0; transient private int indCount = 0;
transient private InterfacePopulationChangedEventListener m_Listener; transient private InterfacePopulationChangedEventListener m_Listener;
transient Plot myPlot = null; transient Plot myPlot = null;
@@ -77,13 +73,13 @@ public class ParticleFilterOptimization implements InterfaceOptimizer, java.io.S
} }
public ParticleFilterOptimization(ParticleFilterOptimization a) { public ParticleFilterOptimization(ParticleFilterOptimization a) {
this.m_Population = (Population)a.m_Population.clone(); this.m_Population = (Population) a.m_Population.clone();
this.m_Problem = (InterfaceOptimizationProblem)a.m_Problem.clone(); this.m_Problem = (InterfaceOptimizationProblem) a.m_Problem.clone();
this.m_Identifier = a.m_Identifier; this.m_Identifier = a.m_Identifier;
//this.m_Plague = a.m_Plague; //this.m_Plague = a.m_Plague;
//this.m_NumberOfPartners = a.m_NumberOfPartners; //this.m_NumberOfPartners = a.m_NumberOfPartners;
//this.m_UseElitism = a.m_UseElitism; //this.m_UseElitism = a.m_UseElitism;
this.m_ParentSelection = (InterfaceSelection)a.m_ParentSelection.clone(); this.m_ParentSelection = (InterfaceSelection) a.m_ParentSelection.clone();
if (a.withShow) { if (a.withShow) {
setWithShow(true); setWithShow(true);
} }
@@ -104,9 +100,9 @@ public class ParticleFilterOptimization implements InterfaceOptimizer, java.io.S
//System.out.println("pops targ is " + m_Population.getPopulationSize()); //System.out.println("pops targ is " + m_Population.getPopulationSize());
if (initialVelocity <= 0.) { if (initialVelocity <= 0.) {
(((AbstractOptimizationProblem)m_Problem).getIndividualTemplate()).setMutationOperator(new MutateESFixedStepSize(mutationSigma)); (((AbstractOptimizationProblem) m_Problem).getIndividualTemplate()).setMutationOperator(new MutateESFixedStepSize(mutationSigma));
} else { } else {
(((AbstractOptimizationProblem)m_Problem).getIndividualTemplate()).setMutationOperator(new MutateESCorrVector(mutationSigma, initialVelocity, rotationDeg)); (((AbstractOptimizationProblem) m_Problem).getIndividualTemplate()).setMutationOperator(new MutateESCorrVector(mutationSigma, initialVelocity, rotationDeg));
} }
m_Population.setTargetSize(popSize); m_Population.setTargetSize(popSize);
this.m_Problem.initPopulation(this.m_Population); this.m_Problem.initPopulation(this.m_Population);
@@ -117,13 +113,15 @@ public class ParticleFilterOptimization implements InterfaceOptimizer, java.io.S
this.firePropertyChangedEvent(Population.nextGenerationPerformed); this.firePropertyChangedEvent(Population.nextGenerationPerformed);
} }
/** 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 pop The initial population
* @param reset If true the population is reset. * @param reset If true the population is reset.
*/ */
@Override @Override
public void initByPopulation(Population pop, boolean reset) { public void initByPopulation(Population pop, boolean reset) {
this.m_Population = (Population)pop.clone(); this.m_Population = (Population) pop.clone();
if (reset) { if (reset) {
this.m_Population.init(); this.m_Population.init();
this.evaluatePopulation(this.m_Population); this.evaluatePopulation(this.m_Population);
@@ -131,8 +129,9 @@ public class ParticleFilterOptimization implements InterfaceOptimizer, java.io.S
} }
} }
/** This method will evaluate the current population using the /**
* given problem. * This method will evaluate the current population using the given problem.
*
* @param population The population that is to be evaluated * @param population The population that is to be evaluated
*/ */
private Population evaluatePopulation(Population population) { private Population evaluatePopulation(Population population) {
@@ -147,34 +146,33 @@ public class ParticleFilterOptimization implements InterfaceOptimizer, java.io.S
*/ */
protected Population resample(Population pop) { protected Population resample(Population pop) {
Population parents; Population parents;
boolean doImmigr=false; boolean doImmigr = false;
this.m_ParentSelection.prepareSelection(pop); this.m_ParentSelection.prepareSelection(pop);
// Generate a Population of Parents with Parantselectionmethod. // Generate a Population of Parents with Parantselectionmethod.
// DONT forget cloning -> selection does only shallow copies! // DONT forget cloning -> selection does only shallow copies!
int targetSize = this.m_Population.getTargetSize(); int targetSize = this.m_Population.getTargetSize();
if (randomImmigrationQuota>0) { if (randomImmigrationQuota > 0) {
if (randomImmigrationQuota>1.) { if (randomImmigrationQuota > 1.) {
System.err.println("Error, invalid immigration quota!"); System.err.println("Error, invalid immigration quota!");
} } else {
else { targetSize = (int) (this.m_Population.getTargetSize() * (1. - randomImmigrationQuota));
targetSize = (int)(this.m_Population.getTargetSize() * (1.-randomImmigrationQuota));
targetSize = Math.max(1, targetSize); // guarantee at least one to be selected targetSize = Math.max(1, targetSize); // guarantee at least one to be selected
if (targetSize < this.m_Population.getTargetSize()) { if (targetSize < this.m_Population.getTargetSize()) {
doImmigr=true; doImmigr = true;
} }
} }
} }
parents = (Population)(this.m_ParentSelection.selectFrom(pop, targetSize)).clone(); parents = (Population) (this.m_ParentSelection.selectFrom(pop, targetSize)).clone();
if (doImmigr) { if (doImmigr) {
// add immigrants // add immigrants
AbstractEAIndividual immi; AbstractEAIndividual immi;
int i; int i;
for (i=0; (i+parents.getTargetSize())<pop.getTargetSize(); i++) { for (i = 0; (i + parents.getTargetSize()) < pop.getTargetSize(); i++) {
immi = (AbstractEAIndividual)pop.getEAIndividual(0).clone(); immi = (AbstractEAIndividual) pop.getEAIndividual(0).clone();
immi.init(getProblem()); immi.init(getProblem());
parents.add(immi); parents.add(immi);
} }
@@ -199,7 +197,7 @@ public class ParticleFilterOptimization implements InterfaceOptimizer, java.io.S
drawPop(pop, 0, false); drawPop(pop, 0, false);
} }
for (int i = 0; i < pop.getTargetSize(); i++) { for (int i = 0; i < pop.getTargetSize(); i++) {
applyMotionModel((AbstractEAIndividual)((AbstractEAIndividual)pop.get(i)), 0.); applyMotionModel((AbstractEAIndividual) ((AbstractEAIndividual) pop.get(i)), 0.);
indCount++; indCount++;
} }
if (withShow) { if (withShow) {
@@ -212,14 +210,13 @@ public class ParticleFilterOptimization implements InterfaceOptimizer, java.io.S
if (graphLabel < 0) { if (graphLabel < 0) {
graphLabel = indCount; graphLabel = indCount;
} }
for (int i=0; i<pop.size(); i++) { for (int i = 0; i < pop.size(); i++) {
InterfaceDataTypeDouble endy = (InterfaceDataTypeDouble) pop.getEAIndividual(i); InterfaceDataTypeDouble endy = (InterfaceDataTypeDouble) pop.getEAIndividual(i);
double[] curPosition = endy.getDoubleData(); double[] curPosition = endy.getDoubleData();
if (useCircles) { if (useCircles) {
myPlot.getFunctionArea().drawCircle("", curPosition, graphLabel); myPlot.getFunctionArea().drawCircle("", curPosition, graphLabel);
} } else {
else {
myPlot.setUnconnectedPoint(curPosition[0], curPosition[1], graphLabel); myPlot.setUnconnectedPoint(curPosition[0], curPosition[1], graphLabel);
} }
// myPlot.setConnectedPoint(curPosition[0], curPosition[1], graphLabel); // myPlot.setConnectedPoint(curPosition[0], curPosition[1], graphLabel);
@@ -251,8 +248,11 @@ public class ParticleFilterOptimization implements InterfaceOptimizer, java.io.S
// resample using selection // resample using selection
nextGeneration = resample(m_Population); nextGeneration = resample(m_Population);
if (sleepTime > 0 ) { if (sleepTime > 0) {
try { Thread.sleep(sleepTime); } catch(Exception e) {} try {
Thread.sleep(sleepTime);
} catch (Exception e) {
}
} }
if (withShow) { if (withShow) {
clearPlot(); clearPlot();
@@ -276,79 +276,89 @@ public class ParticleFilterOptimization implements InterfaceOptimizer, java.io.S
public void addPopulationChangedEventListener(InterfacePopulationChangedEventListener ea) { public void addPopulationChangedEventListener(InterfacePopulationChangedEventListener ea) {
this.m_Listener = ea; this.m_Listener = ea;
} }
@Override @Override
public boolean removePopulationChangedEventListener( public boolean removePopulationChangedEventListener(
InterfacePopulationChangedEventListener ea) { InterfacePopulationChangedEventListener ea) {
if (m_Listener==ea) { if (m_Listener == ea) {
m_Listener=null; m_Listener = null;
return true; return true;
} else { } else {
return false; return false;
} }
} }
protected void firePropertyChangedEvent (String name) {
protected void firePropertyChangedEvent(String name) {
if (this.m_Listener != null) { if (this.m_Listener != null) {
this.m_Listener.registerPopulationStateChanged(this, name); this.m_Listener.registerPopulationStateChanged(this, name);
} }
} }
/** This method will set the problem that is to be optimized /**
* This method will set the problem that is to be optimized
*
* @param problem * @param problem
*/ */
@Override @Override
public void setProblem (InterfaceOptimizationProblem problem) { public void setProblem(InterfaceOptimizationProblem problem) {
this.m_Problem = problem; this.m_Problem = problem;
if (problem instanceof AbstractOptimizationProblem) { if (problem instanceof AbstractOptimizationProblem) {
((AbstractOptimizationProblem)problem).informAboutOptimizer(this); ((AbstractOptimizationProblem) problem).informAboutOptimizer(this);
} }
} }
@Override @Override
public InterfaceOptimizationProblem getProblem () { public InterfaceOptimizationProblem getProblem() {
return this.m_Problem; return this.m_Problem;
} }
/** This method will return a string describing all properties of the optimizer /**
* and the applied methods. * This method will return a string describing all properties of the
* optimizer and the applied methods.
*
* @return A descriptive string * @return A descriptive string
*/ */
@Override @Override
public String getStringRepresentation() { public String getStringRepresentation() {
StringBuilder strB=new StringBuilder(200); StringBuilder strB = new StringBuilder(200);
strB.append("Particle Filter:\nOptimization Problem: "); strB.append("Particle Filter:\nOptimization Problem: ");
strB.append(this.m_Problem.getStringRepresentationForProblem(this)); strB.append(this.m_Problem.getStringRepresentationForProblem(this));
strB.append("\n"); strB.append("\n");
strB.append(this.m_Population.getStringRepresentation()); strB.append(this.m_Population.getStringRepresentation());
return strB.toString(); return strB.toString();
} }
/** 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 * @param name The indenifier
*/ */
@Override @Override
public void setIdentifier(String name) { public void setIdentifier(String name) {
this.m_Identifier = name; this.m_Identifier = name;
} }
@Override @Override
public String getIdentifier() { public String getIdentifier() {
return this.m_Identifier; return this.m_Identifier;
} }
/** This method is required to free the memory on a RMIServer, /**
* but there is nothing to implement. * ********************************************************************************************************************
*/
@Override
public void freeWilly() {
}
/**********************************************************************************************************************
* These are for GUI * These are for GUI
*/ */
/** This method returns a global info string /**
* This method returns a global info string
*
* @return description * @return description
*/ */
public static String globalInfo() { public static String globalInfo() {
return "This is a Particle Filter Algorithm."; return "This is a Particle Filter Algorithm.";
} }
/** This method will return a naming String
/**
* This method will return a naming String
*
* @return The name of the algorithm * @return The name of the algorithm
*/ */
@Override @Override
@@ -356,19 +366,23 @@ public class ParticleFilterOptimization implements InterfaceOptimizer, java.io.S
return "PF"; return "PF";
} }
/** Assuming that all optimizer will store thier data in a population /**
* we will allow acess to this population to query to current state * Assuming that all optimizer will store thier data in a population we will
* of the optimizer. * allow acess to this population to query to current state of the
* optimizer.
*
* @return The population of current solutions to a given problem. * @return The population of current solutions to a given problem.
*/ */
@Override @Override
public Population getPopulation() { public Population getPopulation() {
return this.m_Population; return this.m_Population;
} }
@Override @Override
public void setPopulation(Population pop){ public void setPopulation(Population pop) {
this.m_Population = pop; this.m_Population = pop;
} }
public String populationTipText() { public String populationTipText() {
return "Edit the properties of the population used."; return "Edit the properties of the population used.";
} }
@@ -377,22 +391,28 @@ public class ParticleFilterOptimization implements InterfaceOptimizer, java.io.S
public InterfaceSolutionSet getAllSolutions() { public InterfaceSolutionSet getAllSolutions() {
return new SolutionSet(getPopulation()); return new SolutionSet(getPopulation());
} }
/** 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 * @param selection
*/ */
public void setParentSelection(InterfaceSelection selection) { public void setParentSelection(InterfaceSelection selection) {
this.m_ParentSelection = selection; this.m_ParentSelection = selection;
} }
public InterfaceSelection getParentSelection() { public InterfaceSelection getParentSelection() {
return this.m_ParentSelection; return this.m_ParentSelection;
} }
public String parentSelectionTipText() { public String parentSelectionTipText() {
return "Choose a parent selection method."; return "Choose a parent selection method.";
} }
/** /**
* @return the withShow * @return the withShow
**/ *
*/
public boolean isWithShow() { public boolean isWithShow() {
return withShow; return withShow;
} }
@@ -402,11 +422,11 @@ public class ParticleFilterOptimization implements InterfaceOptimizer, java.io.S
} }
protected void clearPlot() { protected void clearPlot() {
if (myPlot!=null) { if (myPlot != null) {
myPlot.clearAll(); myPlot.clearAll();
double[][] range = null; double[][] range = null;
if ((m_Population != null) && (m_Population.size() > 0)) { if ((m_Population != null) && (m_Population.size() > 0)) {
range = ((InterfaceDataTypeDouble)this.m_Population.get(0)).getDoubleRange(); range = ((InterfaceDataTypeDouble) this.m_Population.get(0)).getDoubleRange();
} }
if (range != null) { if (range != null) {
myPlot.setCornerPoints(range, 0); myPlot.setCornerPoints(range, 0);
@@ -416,18 +436,17 @@ public class ParticleFilterOptimization implements InterfaceOptimizer, java.io.S
/** /**
* @param withShow the withShow to set * @param withShow the withShow to set
**/ *
*/
public void setWithShow(boolean wShow) { public void setWithShow(boolean wShow) {
this.withShow = wShow; this.withShow = wShow;
if (!withShow) { if (!withShow) {
myPlot = null; myPlot = null;
} } else {
else {
double[][] range; double[][] range;
if ((m_Population != null) && (m_Population.size() > 0)) { if ((m_Population != null) && (m_Population.size() > 0)) {
range = ((InterfaceDataTypeDouble)this.m_Population.get(0)).getDoubleRange(); range = ((InterfaceDataTypeDouble) this.m_Population.get(0)).getDoubleRange();
} } else {
else {
range = new double[2][]; range = new double[2][];
range[0] = new double[2]; range[0] = new double[2];
range[0][0] = 0; range[0][0] = 0;
@@ -440,28 +459,32 @@ public class ParticleFilterOptimization implements InterfaceOptimizer, java.io.S
/** /**
* @return the sleepTime * @return the sleepTime
**/ *
*/
public int getSleepTime() { public int getSleepTime() {
return sleepTime; return sleepTime;
} }
/** /**
* @param sleepTime the sleepTime to set * @param sleepTime the sleepTime to set
**/ *
*/
public void setSleepTime(int sleepTime) { public void setSleepTime(int sleepTime) {
this.sleepTime = sleepTime; this.sleepTime = sleepTime;
} }
/** /**
* @return the mutationSigma * @return the mutationSigma
**/ *
*/
public double getMutationSigma() { public double getMutationSigma() {
return mutationSigma; return mutationSigma;
} }
/** /**
* @param mutationSigma the mutationSigma to set * @param mutationSigma the mutationSigma to set
**/ *
*/
public void setMutationSigma(double mutationSigma) { public void setMutationSigma(double mutationSigma) {
this.mutationSigma = mutationSigma; this.mutationSigma = mutationSigma;
} }

View File

@@ -1731,14 +1731,6 @@ public class ParticleSwarmOptimization implements InterfaceOptimizer, java.io.Se
return this.m_Identifier; return this.m_Identifier;
} }
/**
* This method is required to free the memory on a RMIServer, but there is
* nothing to implement.
*/
@Override
public void freeWilly() {
}
/** /**
* ******************************************************************************************************************** * ********************************************************************************************************************
* These are for GUI * These are for GUI

View File

@@ -13,23 +13,23 @@ import eva2.server.go.problems.AbstractOptimizationProblem;
import eva2.server.go.problems.B1Problem; import eva2.server.go.problems.B1Problem;
import eva2.server.go.problems.InterfaceOptimizationProblem; import eva2.server.go.problems.InterfaceOptimizationProblem;
/** Population based incremental learning in the PSM by Monmarche /**
* version with also allows to simulate ant systems due to the flexible * Population based incremental learning in the PSM by Monmarche version with
* update rule of V. But both are limited to binary genotypes. * also allows to simulate ant systems due to the flexible update rule of V. But
* This is a simple implementation of Population Based Incremental Learning. * both are limited to binary genotypes. This is a simple implementation of
* Population Based Incremental Learning.
* *
* Nicolas Monmarché , Eric Ramat , Guillaume Dromel , Mohamed Slimane , Gilles Venturini: * Nicolas Monmarché , Eric Ramat , Guillaume Dromel , Mohamed Slimane , Gilles
* On the similarities between AS, BSC and PBIL: toward the birth of a new meta-heuristic. * Venturini: On the similarities between AS, BSC and PBIL: toward the birth of
* TecReport 215. Univ. de Tours, 1999. * a new meta-heuristic. TecReport 215. Univ. de Tours, 1999.
*
* Copyright: Copyright (c) 2003 Company: University of Tuebingen, Computer
* Architecture
* *
* Copyright: Copyright (c) 2003
* Company: University of Tuebingen, Computer Architecture
* @author Felix Streichert * @author Felix Streichert
* @version: $Revision: 307 $ * @version: $Revision: 307 $ $Date: 2007-12-04 14:31:47 +0100 (Tue, 04 Dec
* $Date: 2007-12-04 14:31:47 +0100 (Tue, 04 Dec 2007) $ * 2007) $ $Author: mkron $
* $Author: mkron $
*/ */
public class PopulationBasedIncrementalLearning implements InterfaceOptimizer, java.io.Serializable { public class PopulationBasedIncrementalLearning implements InterfaceOptimizer, java.io.Serializable {
// These variables are necessary for the simple testcase // These variables are necessary for the simple testcase
@@ -43,20 +43,20 @@ public class PopulationBasedIncrementalLearning implements InterfaceOptimizer, j
private double m_MutationRate = 0.5; private double m_MutationRate = 0.5;
private double m_MutateSigma = 0.01; private double m_MutateSigma = 0.01;
private int m_NumberOfPositiveSamples = 1; private int m_NumberOfPositiveSamples = 1;
private double[] m_initialProbabilities = ((PBILPopulation)m_Population).getProbabilityVector(); private double[] m_initialProbabilities = ((PBILPopulation) m_Population).getProbabilityVector();
public PopulationBasedIncrementalLearning() { public PopulationBasedIncrementalLearning() {
} }
public PopulationBasedIncrementalLearning(PopulationBasedIncrementalLearning a) { public PopulationBasedIncrementalLearning(PopulationBasedIncrementalLearning a) {
this.m_Population = (Population)a.m_Population.clone(); this.m_Population = (Population) a.m_Population.clone();
this.m_Problem = (InterfaceOptimizationProblem)a.m_Problem.clone(); this.m_Problem = (InterfaceOptimizationProblem) a.m_Problem.clone();
this.m_LearningRate = a.m_LearningRate; this.m_LearningRate = a.m_LearningRate;
this.m_MutationRate = a.m_MutationRate; this.m_MutationRate = a.m_MutationRate;
this.m_MutateSigma = a.m_MutateSigma; this.m_MutateSigma = a.m_MutateSigma;
this.m_NumberOfPositiveSamples = a.m_NumberOfPositiveSamples; this.m_NumberOfPositiveSamples = a.m_NumberOfPositiveSamples;
this.m_UseElitism = a.m_UseElitism; this.m_UseElitism = a.m_UseElitism;
this.m_SelectionOperator = (InterfaceSelection)a.m_SelectionOperator.clone(); this.m_SelectionOperator = (InterfaceSelection) a.m_SelectionOperator.clone();
} }
@Override @Override
@@ -67,10 +67,10 @@ public class PopulationBasedIncrementalLearning implements InterfaceOptimizer, j
@Override @Override
public void init() { public void init() {
this.m_Problem.initPopulation(this.m_Population); this.m_Problem.initPopulation(this.m_Population);
if ((m_initialProbabilities!=null) && (m_initialProbabilities.length==((PBILPopulation)m_Population).getProbabilityVector().length)) { if ((m_initialProbabilities != null) && (m_initialProbabilities.length == ((PBILPopulation) m_Population).getProbabilityVector().length)) {
((PBILPopulation)m_Population).setProbabilityVector(m_initialProbabilities); ((PBILPopulation) m_Population).setProbabilityVector(m_initialProbabilities);
} else { } else {
if (m_initialProbabilities!=null) { if (m_initialProbabilities != null) {
System.err.println("Warning: initial probability vector doesnt match in length!"); System.err.println("Warning: initial probability vector doesnt match in length!");
} }
} }
@@ -78,7 +78,9 @@ public class PopulationBasedIncrementalLearning implements InterfaceOptimizer, j
this.firePropertyChangedEvent(Population.nextGenerationPerformed); this.firePropertyChangedEvent(Population.nextGenerationPerformed);
} }
/** 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 pop The initial population
* @param reset If true the population is reset. * @param reset If true the population is reset.
*/ */
@@ -88,17 +90,18 @@ public class PopulationBasedIncrementalLearning implements InterfaceOptimizer, j
System.err.println("Error: PBIL only works with GAIndividuals!"); System.err.println("Error: PBIL only works with GAIndividuals!");
} }
this.m_Population = new PBILPopulation(); this.m_Population = new PBILPopulation();
this.m_Population.addPopulation((Population)pop.clone()); this.m_Population.addPopulation((Population) pop.clone());
if (reset) { if (reset) {
this.m_Population.init(); this.m_Population.init();
this.evaluatePopulation(this.m_Population); this.evaluatePopulation(this.m_Population);
} }
((PBILPopulation)this.m_Population).buildProbabilityVector(); ((PBILPopulation) this.m_Population).buildProbabilityVector();
this.firePropertyChangedEvent(Population.nextGenerationPerformed); this.firePropertyChangedEvent(Population.nextGenerationPerformed);
} }
/** This method will evaluate the current population using the /**
* given problem. * This method will evaluate the current population using the given problem.
*
* @param population The population that is to be evaluated * @param population The population that is to be evaluated
*/ */
private void evaluatePopulation(Population population) { private void evaluatePopulation(Population population) {
@@ -106,11 +109,12 @@ public class PopulationBasedIncrementalLearning implements InterfaceOptimizer, j
population.incrGeneration(); population.incrGeneration();
} }
/** 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.
*/ */
private Population generateChildren() { private Population generateChildren() {
PBILPopulation result = (PBILPopulation)this.m_Population.clone(); PBILPopulation result = (PBILPopulation) this.m_Population.clone();
Population examples; Population examples;
// this.m_NormationOperator.computeSelectionProbability(this.m_Population, "Fitness"); // this.m_NormationOperator.computeSelectionProbability(this.m_Population, "Fitness");
@@ -141,46 +145,55 @@ public class PopulationBasedIncrementalLearning implements InterfaceOptimizer, j
this.firePropertyChangedEvent(Population.nextGenerationPerformed); this.firePropertyChangedEvent(Population.nextGenerationPerformed);
} }
/** This method will set the problem that is to be optimized /**
* This method will set the problem that is to be optimized
*
* @param problem * @param problem
*/ */
@Override @Override
public void setProblem (InterfaceOptimizationProblem problem) { public void setProblem(InterfaceOptimizationProblem problem) {
this.m_Problem = problem; this.m_Problem = problem;
if (m_Problem instanceof AbstractOptimizationProblem) { if (m_Problem instanceof AbstractOptimizationProblem) {
if (!(((AbstractOptimizationProblem)m_Problem).getIndividualTemplate() instanceof InterfaceGAIndividual)) { if (!(((AbstractOptimizationProblem) m_Problem).getIndividualTemplate() instanceof InterfaceGAIndividual)) {
System.err.println("Error: PBIL only works with GAIndividuals!"); System.err.println("Error: PBIL only works with GAIndividuals!");
} }
} }
} }
@Override @Override
public InterfaceOptimizationProblem getProblem () { public InterfaceOptimizationProblem getProblem() {
return this.m_Problem; return this.m_Problem;
} }
@Override @Override
public void addPopulationChangedEventListener(InterfacePopulationChangedEventListener ea) { public void addPopulationChangedEventListener(InterfacePopulationChangedEventListener ea) {
this.m_Listener = ea; this.m_Listener = ea;
} }
@Override @Override
public boolean removePopulationChangedEventListener( public boolean removePopulationChangedEventListener(
InterfacePopulationChangedEventListener ea) { InterfacePopulationChangedEventListener ea) {
if (m_Listener==ea) { if (m_Listener == ea) {
m_Listener=null; m_Listener = null;
return true; return true;
} else { } else {
return false; return false;
} }
} }
/** Something has changed
/**
* Something has changed
*/ */
protected void firePropertyChangedEvent (String name) { protected void firePropertyChangedEvent(String name) {
if (this.m_Listener != null) { if (this.m_Listener != null) {
this.m_Listener.registerPopulationStateChanged(this, name); this.m_Listener.registerPopulationStateChanged(this, name);
} }
} }
/** This method will return a string describing all properties of the optimizer /**
* and the applied methods. * This method will return a string describing all properties of the
* optimizer and the applied methods.
*
* @return A descriptive string * @return A descriptive string
*/ */
@Override @Override
@@ -188,39 +201,42 @@ public class PopulationBasedIncrementalLearning implements InterfaceOptimizer, j
String result = ""; String result = "";
result += "Population Based Incremental Learning:\n"; result += "Population Based Incremental Learning:\n";
result += "Optimization Problem: "; result += "Optimization Problem: ";
result += this.m_Problem.getStringRepresentationForProblem(this) +"\n"; result += this.m_Problem.getStringRepresentationForProblem(this) + "\n";
result += this.m_Population.getStringRepresentation(); result += this.m_Population.getStringRepresentation();
return result; return result;
} }
/** 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 * @param name The indenifier
*/ */
@Override @Override
public void setIdentifier(String name) { public void setIdentifier(String name) {
this.m_Identifier = name; this.m_Identifier = name;
} }
@Override @Override
public String getIdentifier() { public String getIdentifier() {
return this.m_Identifier; return this.m_Identifier;
} }
/** This method is required to free the memory on a RMIServer, /**
* but there is nothing to implement. * ********************************************************************************************************************
*/
@Override
public void freeWilly() {
}
/**********************************************************************************************************************
* These are for GUI * These are for GUI
*/ */
/** This method returns a global info string /**
* This method returns a global info string
*
* @return description * @return description
*/ */
public static String globalInfo() { public static String globalInfo() {
return "The Population based incremental learning is based on a statistical distribution of bit positions. Please note: This optimizer requires a binary genotype!"; return "The Population based incremental learning is based on a statistical distribution of bit positions. Please note: This optimizer requires a binary genotype!";
} }
/** This method will return a naming String
/**
* This method will return a naming String
*
* @return The name of the algorithm * @return The name of the algorithm
*/ */
@Override @Override
@@ -228,19 +244,23 @@ public class PopulationBasedIncrementalLearning implements InterfaceOptimizer, j
return "PBIL"; return "PBIL";
} }
/** Assuming that all optimizer will store thier data in a population /**
* we will allow acess to this population to query to current state * Assuming that all optimizer will store thier data in a population we will
* of the optimizer. * allow acess to this population to query to current state of the
* optimizer.
*
* @return The population of current solutions to a given problem. * @return The population of current solutions to a given problem.
*/ */
@Override @Override
public Population getPopulation() { public Population getPopulation() {
return this.m_Population; return this.m_Population;
} }
@Override @Override
public void setPopulation(Population pop){ public void setPopulation(Population pop) {
this.m_Population = pop; this.m_Population = pop;
} }
public String populationTipText() { public String populationTipText() {
return "Edit the properties of the PBIL population used."; return "Edit the properties of the PBIL population used.";
} }
@@ -262,52 +282,66 @@ public class PopulationBasedIncrementalLearning implements InterfaceOptimizer, j
// return "Select the normation method."; // 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 * @param selection
*/ */
public void setSelectionMethod(InterfaceSelection selection) { public void setSelectionMethod(InterfaceSelection selection) {
this.m_SelectionOperator = selection; this.m_SelectionOperator = selection;
} }
public InterfaceSelection getSelectionMethod() { public InterfaceSelection getSelectionMethod() {
return this.m_SelectionOperator; return this.m_SelectionOperator;
} }
public String selectionMethodTipText() { public String selectionMethodTipText() {
return "Choose a selection method."; return "Choose a selection method.";
} }
/** This method will set the problem that is to be optimized /**
* This method will set the problem that is to be optimized
*
* @param elitism * @param elitism
*/ */
public void setElitism (boolean elitism) { public void setElitism(boolean elitism) {
this.m_UseElitism = elitism; this.m_UseElitism = elitism;
} }
public boolean getElitism() { public boolean getElitism() {
return this.m_UseElitism; return this.m_UseElitism;
} }
public String elitismTipText() { public String elitismTipText() {
return "Enable/disable elitism."; return "Enable/disable elitism.";
} }
/** This method will set the learning rate for PBIL /**
* This method will set the learning rate for PBIL
*
* @param LearningRate * @param LearningRate
*/ */
public void setLearningRate (double LearningRate) { public void setLearningRate(double LearningRate) {
this.m_LearningRate = LearningRate; this.m_LearningRate = LearningRate;
if (this.m_LearningRate < 0) { if (this.m_LearningRate < 0) {
this.m_LearningRate = 0; this.m_LearningRate = 0;
} }
} }
public double getLearningRate() { public double getLearningRate() {
return this.m_LearningRate; return this.m_LearningRate;
} }
public String learningRateTipText() { public String learningRateTipText() {
return "The learing rate of PBIL."; return "The learing rate of PBIL.";
} }
/** This method will set the mutation rate for PBIL /**
* This method will set the mutation rate for PBIL
*
* @param m * @param m
*/ */
public void setMutationRate (double m) { public void setMutationRate(double m) {
this.m_MutationRate = m; this.m_MutationRate = m;
if (this.m_MutationRate < 0) { if (this.m_MutationRate < 0) {
this.m_MutationRate = 0; this.m_MutationRate = 0;
@@ -316,41 +350,51 @@ public class PopulationBasedIncrementalLearning implements InterfaceOptimizer, j
this.m_MutationRate = 1; this.m_MutationRate = 1;
} }
} }
public double getMutationRate() { public double getMutationRate() {
return this.m_MutationRate; return this.m_MutationRate;
} }
public String mutationRateTipText() { public String mutationRateTipText() {
return "The mutation rate of PBIL."; return "The mutation rate of PBIL.";
} }
/** This method will set the mutation sigma for PBIL /**
* This method will set the mutation sigma for PBIL
*
* @param m * @param m
*/ */
public void setMutateSigma (double m) { public void setMutateSigma(double m) {
this.m_MutateSigma = m; this.m_MutateSigma = m;
if (this.m_MutateSigma < 0) { if (this.m_MutateSigma < 0) {
this.m_MutateSigma = 0; this.m_MutateSigma = 0;
} }
} }
public double getMutateSigma() { public double getMutateSigma() {
return this.m_MutateSigma; return this.m_MutateSigma;
} }
public String mutateSigmaTipText() { public String mutateSigmaTipText() {
return "Set the sigma for the mutation of the probability vector."; return "Set the sigma for the mutation of the probability vector.";
} }
/** This method will set the number of positive samples for PBIL /**
* This method will set the number of positive samples for PBIL
*
* @param PositiveSamples * @param PositiveSamples
*/ */
public void setPositiveSamples (int PositiveSamples) { public void setPositiveSamples(int PositiveSamples) {
this.m_NumberOfPositiveSamples = PositiveSamples; this.m_NumberOfPositiveSamples = PositiveSamples;
if (this.m_NumberOfPositiveSamples < 1) { if (this.m_NumberOfPositiveSamples < 1) {
this.m_NumberOfPositiveSamples = 1; this.m_NumberOfPositiveSamples = 1;
} }
} }
public int getPositiveSamples() { public int getPositiveSamples() {
return this.m_NumberOfPositiveSamples; return this.m_NumberOfPositiveSamples;
} }
public String positiveSamplesTipText() { public String positiveSamplesTipText() {
return "The number of positive samples that update the PBIL vector."; return "The number of positive samples that update the PBIL vector.";
} }

View File

@@ -25,19 +25,23 @@ import eva2.tools.math.RNG;
import java.util.ArrayList; import java.util.ArrayList;
/** /**
* A ScatterSearch implementation taken mainly from [1]. Unfortunately, some parameters as well as * A ScatterSearch implementation taken mainly from [1]. Unfortunately, some
* the local search method are not well defined in [1], so this implementation allows HC and Nelder-Mead * parameters as well as the local search method are not well defined in [1], so
* as local search. If local search is activated, an additional filter is defined, meaning that only those * this implementation allows HC and Nelder-Mead as local search. If local
* search is activated, an additional filter is defined, meaning that only those
* individuals with a high quality fitness are further improved by local search. * individuals with a high quality fitness are further improved by local search.
* The threshold fitness is either defined relatively to the best/worst fitness values in the reference set * The threshold fitness is either defined relatively to the best/worst fitness
* or as an absolute value (in both cases only the first fitness criterion is regarded). * values in the reference set or as an absolute value (in both cases only the
* first fitness criterion is regarded).
* *
* @author mkron * @author mkron
* *
* [1] M.Rodiguez-Fernandez, J.Egea, J.Banga: Novel metaheuristic for parameter estimation in nonlinear dynamic biological systems. * [1] M.Rodiguez-Fernandez, J.Egea, J.Banga: Novel metaheuristic for parameter
* BMC Bioinformatics 2006, 7:483. BioMed Central 2006. * estimation in nonlinear dynamic biological systems. BMC Bioinformatics 2006,
* 7:483. BioMed Central 2006.
*/ */
public class ScatterSearch implements InterfaceOptimizer, java.io.Serializable, InterfacePopulationChangedEventListener { public class ScatterSearch implements InterfaceOptimizer, java.io.Serializable, InterfacePopulationChangedEventListener {
transient private InterfacePopulationChangedEventListener m_Listener = null; transient private InterfacePopulationChangedEventListener m_Listener = null;
private String m_Identifier = "ScatterSearch"; private String m_Identifier = "ScatterSearch";
private AbstractOptimizationProblem problem = new F1Problem(); private AbstractOptimizationProblem problem = new F1Problem();
@@ -58,9 +62,7 @@ public class ScatterSearch implements InterfaceOptimizer, java.io.Serializable,
// simulate an EvA generational cycle // simulate an EvA generational cycle
private int generationCycle = 50; private int generationCycle = 50;
private int fitCrit = -1; private int fitCrit = -1;
protected boolean checkRange = true; protected boolean checkRange = true;
// private int lastLocalSearch = -1; // private int lastLocalSearch = -1;
// // nr of generations between local searches // // nr of generations between local searches
// protected int localSearchInterval = 10; // protected int localSearchInterval = 10;
@@ -71,7 +73,6 @@ public class ScatterSearch implements InterfaceOptimizer, java.io.Serializable,
private double nelderMeadInitPerturbation = 0.01; private double nelderMeadInitPerturbation = 0.01;
private double improvementEpsilon = 0.1; // minimal relative fitness improvement for a candidate to be taken over into the refset private double improvementEpsilon = 0.1; // minimal relative fitness improvement for a candidate to be taken over into the refset
private double minDiversityEpsilon = 0.0001; // minimal phenotypic distance for a candidate to be taken over into the refset private double minDiversityEpsilon = 0.0001; // minimal phenotypic distance for a candidate to be taken over into the refset
private static boolean TRACE = false; private static boolean TRACE = false;
public ScatterSearch() { public ScatterSearch() {
@@ -80,10 +81,10 @@ public class ScatterSearch implements InterfaceOptimizer, java.io.Serializable,
} }
public ScatterSearch(ScatterSearch o) { public ScatterSearch(ScatterSearch o) {
this.refSet = (Population)o.refSet.clone(); this.refSet = (Population) o.refSet.clone();
this.problem = (AbstractOptimizationProblem)o.problem.clone(); this.problem = (AbstractOptimizationProblem) o.problem.clone();
this.template = (AbstractEAIndividual)o.template.clone(); this.template = (AbstractEAIndividual) o.template.clone();
this.range = ((InterfaceDataTypeDouble)template).getDoubleRange(); this.range = ((InterfaceDataTypeDouble) template).getDoubleRange();
this.refSetSize = o.refSetSize; this.refSetSize = o.refSetSize;
this.poolSize = o.poolSize; this.poolSize = o.poolSize;
this.intervals = o.intervals; this.intervals = o.intervals;
@@ -106,7 +107,7 @@ public class ScatterSearch implements InterfaceOptimizer, java.io.Serializable,
@Override @Override
public void setProblem(InterfaceOptimizationProblem problem) { public void setProblem(InterfaceOptimizationProblem problem) {
this.problem = (AbstractOptimizationProblem)problem; this.problem = (AbstractOptimizationProblem) problem;
} }
@Override @Override
@@ -134,6 +135,7 @@ public class ScatterSearch implements InterfaceOptimizer, java.io.Serializable,
/** /**
* Eval an initial population and extract the first refset. * Eval an initial population and extract the first refset.
*
* @param pop * @param pop
*/ */
private void initRefSet(Population pop) { private void initRefSet(Population pop) {
@@ -154,29 +156,29 @@ public class ScatterSearch implements InterfaceOptimizer, java.io.Serializable,
* Do default initialization. * Do default initialization.
*/ */
private void defaultInit() { private void defaultInit() {
firstTime=true; firstTime = true;
refSet = null; refSet = null;
combinations = null; combinations = null;
template = problem.getIndividualTemplate(); template = problem.getIndividualTemplate();
if (!(template instanceof InterfaceDataTypeDouble)) { if (!(template instanceof InterfaceDataTypeDouble)) {
System.err.println("Requiring double data!"); System.err.println("Requiring double data!");
} } else {
else {
Object dim = BeanInspector.callIfAvailable(problem, "getProblemDimension", null); Object dim = BeanInspector.callIfAvailable(problem, "getProblemDimension", null);
if (dim==null) { if (dim == null) {
System.err.println("Couldnt get problem dimension!"); System.err.println("Couldnt get problem dimension!");
} }
probDim = (Integer)dim; probDim = (Integer) dim;
range = ((InterfaceDataTypeDouble)template).getDoubleRange(); range = ((InterfaceDataTypeDouble) template).getDoubleRange();
if (TRACE) { if (TRACE) {
System.out.println("Range is " + BeanInspector.toString(range)); System.out.println("Range is " + BeanInspector.toString(range));
} }
} }
} }
/** Something has changed /**
* Something has changed
*/ */
protected void firePropertyChangedEvent (String name) { protected void firePropertyChangedEvent(String name) {
if (this.m_Listener != null) { if (this.m_Listener != null) {
this.m_Listener.registerPopulationStateChanged(this, name); this.m_Listener.registerPopulationStateChanged(this, name);
} }
@@ -188,7 +190,6 @@ public class ScatterSearch implements InterfaceOptimizer, java.io.Serializable,
// problem.evaluate(indy); // problem.evaluate(indy);
// return indy.getFitness(0); // return indy.getFitness(0);
// } // }
@Override @Override
public void registerPopulationStateChanged(Object source, String name) { public void registerPopulationStateChanged(Object source, String name) {
// The events of the interim hill climbing population will be caught here // The events of the interim hill climbing population will be caught here
@@ -197,7 +198,7 @@ public class ScatterSearch implements InterfaceOptimizer, java.io.Serializable,
// System.out.println("bla"); // System.out.println("bla");
// } // }
// set funcalls to real value // set funcalls to real value
refSet.SetFunctionCalls(((Population)source).getFunctionCalls()); refSet.SetFunctionCalls(((Population) source).getFunctionCalls());
// System.out.println("FunCallIntervalReached at " + (((Population)source).getFunctionCalls())); // System.out.println("FunCallIntervalReached at " + (((Population)source).getFunctionCalls()));
@@ -241,10 +242,10 @@ public class ScatterSearch implements InterfaceOptimizer, java.io.Serializable,
if (TRACE) { if (TRACE) {
System.out.println("No combinations: " + combinations.size()); System.out.println("No combinations: " + combinations.size());
} }
if (combinations.size()>0) { if (combinations.size() > 0) {
updateRefSet(refSet, combinations, oldRefSet); updateRefSet(refSet, combinations, oldRefSet);
} }
} while (refSet.getFunctionCalls()-funCallsStart < generationCycle); } while (refSet.getFunctionCalls() - funCallsStart < generationCycle);
problem.evaluatePopulationEnd(refSet); problem.evaluatePopulationEnd(refSet);
if (TRACE) { if (TRACE) {
@@ -259,7 +260,7 @@ public class ScatterSearch implements InterfaceOptimizer, java.io.Serializable,
// filter: only check those within 50% of the worst indy relative to the best. // filter: only check those within 50% of the worst indy relative to the best.
if (relativeFitCriterion) { if (relativeFitCriterion) {
double fitRange = refSet.getWorstFitness()[0] - refSet.getBestFitness()[0]; double fitRange = refSet.getWorstFitness()[0] - refSet.getBestFitness()[0];
return (cand.getFitness(0) < (refSet.getBestFitness()[0]+(fitRange*localSearchFitnessFilter))); return (cand.getFitness(0) < (refSet.getBestFitness()[0] + (fitRange * localSearchFitnessFilter)));
} else { } else {
// absolute fitness criterion // absolute fitness criterion
return (cand.getFitness(0) < localSearchFitnessFilter); return (cand.getFitness(0) < localSearchFitnessFilter);
@@ -271,7 +272,7 @@ public class ScatterSearch implements InterfaceOptimizer, java.io.Serializable,
private Population regenerateRefSet() { private Population regenerateRefSet() {
Population diversifiedPop = diversify(); Population diversifiedPop = diversify();
int keep = refSetSize/2; int keep = refSetSize / 2;
Population newRefSet = refSet.cloneWithoutInds(); Population newRefSet = refSet.cloneWithoutInds();
if (TRACE) { if (TRACE) {
System.out.println("regen after " + refSet.getFunctionCalls() + ", best is " + refSet.getBestEAIndividual().getFitness(0)); System.out.println("regen after " + refSet.getFunctionCalls() + ", best is " + refSet.getBestEAIndividual().getFitness(0));
@@ -283,20 +284,20 @@ public class ScatterSearch implements InterfaceOptimizer, java.io.Serializable,
System.out.println("keeping " + keep + " indies from former ref set, best is " + newRefSet.getBestEAIndividual().getFitness(0)); System.out.println("keeping " + keep + " indies from former ref set, best is " + newRefSet.getBestEAIndividual().getFitness(0));
} }
int h=newRefSet.size(); int h = newRefSet.size();
ArrayList<double[]> distVects = new ArrayList<double[]>(); ArrayList<double[]> distVects = new ArrayList<double[]>();
for (int i=1; i<h; i++) { for (int i = 1; i < h; i++) {
distVects.add(getDiffVect(newRefSet.getEAIndividual(0), newRefSet.getEAIndividual(i))); distVects.add(getDiffVect(newRefSet.getEAIndividual(0), newRefSet.getEAIndividual(i)));
} }
double maxSP = -1; double maxSP = -1;
int sel = -1; int sel = -1;
while (h<refSetSize) { while (h < refSetSize) {
for (int i=0; i<diversifiedPop.size(); i++) { for (int i = 0; i < diversifiedPop.size(); i++) {
// the difference of cand and best is multiplied by each earlier difference from refSet indies // the difference of cand and best is multiplied by each earlier difference from refSet indies
double[] vP = calcVectP(diversifiedPop.getEAIndividual(i), newRefSet.getEAIndividual(0), distVects); double[] vP = calcVectP(diversifiedPop.getEAIndividual(i), newRefSet.getEAIndividual(0), distVects);
double maxTmp = getMaxInVect(vP); double maxTmp = getMaxInVect(vP);
if ((i==0) || (maxTmp < maxSP)) { if ((i == 0) || (maxTmp < maxSP)) {
maxSP = maxTmp; maxSP = maxTmp;
sel = i; sel = i;
} }
@@ -321,7 +322,7 @@ public class ScatterSearch implements InterfaceOptimizer, java.io.Serializable,
private double getMaxInVect(double[] vals) { private double getMaxInVect(double[] vals) {
double dmax = vals[0]; double dmax = vals[0];
for (int j=1; j<vals.length; j++) { for (int j = 1; j < vals.length; j++) {
if (vals[j] > dmax) { if (vals[j] > dmax) {
dmax = vals[j]; dmax = vals[j];
} }
@@ -338,23 +339,24 @@ public class ScatterSearch implements InterfaceOptimizer, java.io.Serializable,
private double[] multScalarTransposed(double[] diff, ArrayList<double[]> distVects) { private double[] multScalarTransposed(double[] diff, ArrayList<double[]> distVects) {
// d[0]*m[0][0], d[1]*m[0][1] etc. // d[0]*m[0][0], d[1]*m[0][1] etc.
double[] res = new double[distVects.size()]; double[] res = new double[distVects.size()];
for (int i=0; i<distVects.size(); i++) { for (int i = 0; i < distVects.size(); i++) {
res[i] = Mathematics.vvMult(diff, distVects.get(i)); res[i] = Mathematics.vvMult(diff, distVects.get(i));
} }
return res; return res;
} }
private double[] getDiffVect(AbstractEAIndividual indy1, AbstractEAIndividual indy2) { private double[] getDiffVect(AbstractEAIndividual indy1, AbstractEAIndividual indy2) {
double[] v1 = ((InterfaceDataTypeDouble)indy1).getDoubleData(); double[] v1 = ((InterfaceDataTypeDouble) indy1).getDoubleData();
double[] v2 = ((InterfaceDataTypeDouble)indy2).getDoubleData(); double[] v2 = ((InterfaceDataTypeDouble) indy2).getDoubleData();
return Mathematics.vvSub(v1, v2); return Mathematics.vvSub(v1, v2);
} }
/** /**
* Maybe replace the single worst indy in the refset by the best candidate, which may * Maybe replace the single worst indy in the refset by the best candidate,
* be locally optimized in a local search step. * which may be locally optimized in a local search step. The best candidate
* The best candidate is removed from the candidate set in any case. The candidate set * is removed from the candidate set in any case. The candidate set may be
* may be cleared if all following individuals would never be taken over to the refset. * cleared if all following individuals would never be taken over to the
* refset.
* *
* @param refSet * @param refSet
* @param candidates * @param candidates
@@ -371,7 +373,7 @@ public class ScatterSearch implements InterfaceOptimizer, java.io.Serializable,
if (isDoLocalSolver(bestCand, refSet)) { if (isDoLocalSolver(bestCand, refSet)) {
Pair<AbstractEAIndividual, Integer> lsRet = localSolver(bestCand, localSearchSteps); Pair<AbstractEAIndividual, Integer> lsRet = localSolver(bestCand, localSearchSteps);
if ((Math.abs(lsRet.tail() - localSearchSteps)/localSearchSteps) > 0.05) { if ((Math.abs(lsRet.tail() - localSearchSteps) / localSearchSteps) > 0.05) {
System.err.println("Warning, more than 5% difference in local search step"); System.err.println("Warning, more than 5% difference in local search step");
} }
bestCand = lsRet.head(); bestCand = lsRet.head();
@@ -407,18 +409,16 @@ public class ScatterSearch implements InterfaceOptimizer, java.io.Serializable,
// so we can just clear the rest of the candidates // so we can just clear the rest of the candidates
if (!doLocalSearch && (bestCand.getFitness().length == 1)) { if (!doLocalSearch && (bestCand.getFitness().length == 1)) {
candidates.clear(); candidates.clear();
} } else {
else {
candidates.remove(bestIndex); candidates.remove(bestIndex);
} }
} }
} }
private Pair<AbstractEAIndividual, Integer> localSolver(AbstractEAIndividual cand, int hcSteps) { private Pair<AbstractEAIndividual, Integer> localSolver(AbstractEAIndividual cand, int hcSteps) {
if (localSearchMethod.getSelectedTagID()==0) { if (localSearchMethod.getSelectedTagID() == 0) {
return localSolverHC(cand, hcSteps); return localSolverHC(cand, hcSteps);
} } else {
else {
return PostProcess.localSolverNMS(cand, hcSteps, nelderMeadInitPerturbation, problem); return PostProcess.localSolverNMS(cand, hcSteps, nelderMeadInitPerturbation, problem);
} }
} }
@@ -438,7 +438,7 @@ public class ScatterSearch implements InterfaceOptimizer, java.io.Serializable,
private int getClosestIndy(AbstractEAIndividual indy, Population refSet) { private int getClosestIndy(AbstractEAIndividual indy, Population refSet) {
double tmpDst, dist = PhenotypeMetric.dist(indy, refSet.getEAIndividual(0)); double tmpDst, dist = PhenotypeMetric.dist(indy, refSet.getEAIndividual(0));
int sel = 0; int sel = 0;
for (int i=1; i<refSet.size(); i++) { for (int i = 1; i < refSet.size(); i++) {
tmpDst = PhenotypeMetric.dist(indy, refSet.getEAIndividual(i)); tmpDst = PhenotypeMetric.dist(indy, refSet.getEAIndividual(i));
if (tmpDst < dist) { if (tmpDst < dist) {
tmpDst = dist; tmpDst = dist;
@@ -449,8 +449,8 @@ public class ScatterSearch implements InterfaceOptimizer, java.io.Serializable,
} }
/** /**
* Check for both a genotype and phenotype diversity criterion which both must * Check for both a genotype and phenotype diversity criterion which both
* be fulfilled for a candidate to be accepted. * must be fulfilled for a candidate to be accepted.
* *
* @param cand * @param cand
* @param popCompGeno * @param popCompGeno
@@ -459,14 +459,14 @@ public class ScatterSearch implements InterfaceOptimizer, java.io.Serializable,
*/ */
private boolean diversityCriterionFulfilled(AbstractEAIndividual cand, Population popCompGeno, Population popComPheno) { private boolean diversityCriterionFulfilled(AbstractEAIndividual cand, Population popCompGeno, Population popComPheno) {
double minDist = PhenotypeMetric.dist(cand, popCompGeno.getEAIndividual(0)); double minDist = PhenotypeMetric.dist(cand, popCompGeno.getEAIndividual(0));
for (int i=1; i<popCompGeno.size(); i++) { for (int i = 1; i < popCompGeno.size(); i++) {
minDist = Math.min(minDist, PhenotypeMetric.dist(cand, popCompGeno.getEAIndividual(i))); minDist = Math.min(minDist, PhenotypeMetric.dist(cand, popCompGeno.getEAIndividual(i)));
} }
boolean minDistFulfilled = ((minDiversityEpsilon<=0) || (minDist > minDiversityEpsilon)); boolean minDistFulfilled = ((minDiversityEpsilon <= 0) || (minDist > minDiversityEpsilon));
if (minDistFulfilled && (improvementEpsilon > 0)) { if (minDistFulfilled && (improvementEpsilon > 0)) {
boolean minImprovementFulfilled = (cand.getFitness(0) < ((1.-improvementEpsilon) * popComPheno.getBestEAIndividual().getFitness(0))); boolean minImprovementFulfilled = (cand.getFitness(0) < ((1. - improvementEpsilon) * popComPheno.getBestEAIndividual().getFitness(0)));
return minImprovementFulfilled; return minImprovementFulfilled;
} else { } else {
return minDistFulfilled; return minDistFulfilled;
@@ -475,6 +475,7 @@ public class ScatterSearch implements InterfaceOptimizer, java.io.Serializable,
/** /**
* Recombines the refset to new indies which are also evaluated. * Recombines the refset to new indies which are also evaluated.
*
* @param refSet * @param refSet
* @return * @return
*/ */
@@ -482,10 +483,10 @@ public class ScatterSearch implements InterfaceOptimizer, java.io.Serializable,
// 3 pair types: better-better, better-worse, worse-worse (half of the pop); // 3 pair types: better-better, better-worse, worse-worse (half of the pop);
Population combs = new Population(); Population combs = new Population();
Population refSorted = refSet.getBestNIndividuals(refSet.size(), fitCrit); Population refSorted = refSet.getBestNIndividuals(refSet.size(), fitCrit);
int half = refSet.size()/2; int half = refSet.size() / 2;
for (int i=0; i<half-1; i++) { // better-better for (int i = 0; i < half - 1; i++) { // better-better
AbstractEAIndividual indy1 = refSorted.getEAIndividual(i); AbstractEAIndividual indy1 = refSorted.getEAIndividual(i);
for (int j=i+1; j<half; j++) { for (int j = i + 1; j < half; j++) {
// if (TRACE) System.out.println("combi T bb, " + i+ "/" + j); // if (TRACE) System.out.println("combi T bb, " + i+ "/" + j);
AbstractEAIndividual indy2 = refSorted.getEAIndividual(j); AbstractEAIndividual indy2 = refSorted.getEAIndividual(j);
combs.add(combineTypeOne(indy1, indy2)); combs.add(combineTypeOne(indy1, indy2));
@@ -495,9 +496,9 @@ public class ScatterSearch implements InterfaceOptimizer, java.io.Serializable,
} }
} }
for (int i=0; i<half; i++) { // better-worse for (int i = 0; i < half; i++) { // better-worse
AbstractEAIndividual indy1 = refSorted.getEAIndividual(i); AbstractEAIndividual indy1 = refSorted.getEAIndividual(i);
for (int j=half; j<refSet.size(); j++) { for (int j = half; j < refSet.size(); j++) {
// if (TRACE) System.out.println("combi T bw, " + i+ "/" + j); // if (TRACE) System.out.println("combi T bw, " + i+ "/" + j);
AbstractEAIndividual indy2 = refSorted.getEAIndividual(j); AbstractEAIndividual indy2 = refSorted.getEAIndividual(j);
combs.add(combineTypeOne(indy1, indy2)); combs.add(combineTypeOne(indy1, indy2));
@@ -506,23 +507,22 @@ public class ScatterSearch implements InterfaceOptimizer, java.io.Serializable,
} }
} }
for (int i=half; i<refSet.size()-1; i++) { // worse-worse for (int i = half; i < refSet.size() - 1; i++) { // worse-worse
AbstractEAIndividual indy1 = refSorted.getEAIndividual(i); AbstractEAIndividual indy1 = refSorted.getEAIndividual(i);
for (int j=i+1; j<refSet.size(); j++) { for (int j = i + 1; j < refSet.size(); j++) {
// if (TRACE) System.out.println("combi T ww, " + i+ "/" + j); // if (TRACE) System.out.println("combi T ww, " + i+ "/" + j);
AbstractEAIndividual indy2 = refSorted.getEAIndividual(j); AbstractEAIndividual indy2 = refSorted.getEAIndividual(j);
combs.add(combineTypeTwo(indy1, indy2)); combs.add(combineTypeTwo(indy1, indy2));
if (RNG.flipCoin(0.5)) { if (RNG.flipCoin(0.5)) {
combs.add(combineTypeOne(indy1, indy2)); combs.add(combineTypeOne(indy1, indy2));
} } else {
else {
combs.add(combineTypeThree(indy1, indy2)); combs.add(combineTypeThree(indy1, indy2));
} }
} }
} }
if (TRACE) { if (TRACE) {
System.out.println("created combinations " + combs.size() + " best is " + combs.getBestEAIndividual().getFitness(0) ); System.out.println("created combinations " + combs.size() + " best is " + combs.getBestEAIndividual().getFitness(0));
} }
return combs; return combs;
} }
@@ -530,28 +530,30 @@ public class ScatterSearch implements InterfaceOptimizer, java.io.Serializable,
private AbstractEAIndividual combineTypeOne(AbstractEAIndividual indy1, AbstractEAIndividual indy2) { private AbstractEAIndividual combineTypeOne(AbstractEAIndividual indy1, AbstractEAIndividual indy2) {
return combine(indy1, indy2, true, false); return combine(indy1, indy2, true, false);
} }
private AbstractEAIndividual combineTypeTwo(AbstractEAIndividual indy1, AbstractEAIndividual indy2) { private AbstractEAIndividual combineTypeTwo(AbstractEAIndividual indy1, AbstractEAIndividual indy2) {
return combine(indy1, indy2, true, true); return combine(indy1, indy2, true, true);
} }
private AbstractEAIndividual combineTypeThree(AbstractEAIndividual indy1, AbstractEAIndividual indy2) { private AbstractEAIndividual combineTypeThree(AbstractEAIndividual indy1, AbstractEAIndividual indy2) {
return combine(indy1, indy2, false, true); return combine(indy1, indy2, false, true);
} }
private AbstractEAIndividual combine(AbstractEAIndividual indy1, AbstractEAIndividual indy2, boolean bFirst, boolean bAdd) { private AbstractEAIndividual combine(AbstractEAIndividual indy1, AbstractEAIndividual indy2, boolean bFirst, boolean bAdd) {
AbstractEAIndividual resIndy = (AbstractEAIndividual)indy1.clone(); AbstractEAIndividual resIndy = (AbstractEAIndividual) indy1.clone();
double[] v1 = ((InterfaceDataTypeDouble)indy1).getDoubleData(); double[] v1 = ((InterfaceDataTypeDouble) indy1).getDoubleData();
double[] v2 = ((InterfaceDataTypeDouble)indy2).getDoubleData(); double[] v2 = ((InterfaceDataTypeDouble) indy2).getDoubleData();
double[] dVect = RNG.randomDoubleArray(0, 1, probDim); double[] dVect = RNG.randomDoubleArray(0, 1, probDim);
for (int i=0; i<probDim; i++) { for (int i = 0; i < probDim; i++) {
dVect[i] *= (v2[i]-v1[i])/2.; dVect[i] *= (v2[i] - v1[i]) / 2.;
} }
double[] candidate = bFirst ? v1 : v2; double[] candidate = bFirst ? v1 : v2;
double[] combi = bAdd ? Mathematics.vvAdd(candidate, dVect) : Mathematics.vvSub(candidate, dVect); double[] combi = bAdd ? Mathematics.vvAdd(candidate, dVect) : Mathematics.vvSub(candidate, dVect);
if (checkRange) { if (checkRange) {
Mathematics.projectToRange(combi, range); Mathematics.projectToRange(combi, range);
} }
((InterfaceDataTypeDouble)resIndy).SetDoubleGenotype(combi); ((InterfaceDataTypeDouble) resIndy).SetDoubleGenotype(combi);
problem.evaluate(resIndy); problem.evaluate(resIndy);
refSet.incrFunctionCalls(); refSet.incrFunctionCalls();
return resIndy; return resIndy;
@@ -563,25 +565,25 @@ public class ScatterSearch implements InterfaceOptimizer, java.io.Serializable,
} }
private Population getRefSetFitBased(Population curRefSet, Population divPop) { private Population getRefSetFitBased(Population curRefSet, Population divPop) {
int h=refSetSize/2; int h = refSetSize / 2;
curRefSet.addAll(divPop.getBestNIndividuals(h, fitCrit)); curRefSet.addAll(divPop.getBestNIndividuals(h, fitCrit));
Population rest = divPop.getWorstNIndividuals(refSetSize-h, fitCrit); Population rest = divPop.getWorstNIndividuals(refSetSize - h, fitCrit);
// contains worst indies // contains worst indies
double[][] distances = new double[rest.size()][refSetSize]; double[][] distances = new double[rest.size()][refSetSize];
for (int i=0; i<distances.length; i++) { // compute euc. distances of all rest indies to all refset indies. for (int i = 0; i < distances.length; i++) { // compute euc. distances of all rest indies to all refset indies.
for (int j=0; j<h; j++) { for (int j = 0; j < h; j++) {
distances[i][j]=PhenotypeMetric.dist(rest.getEAIndividual(i), curRefSet.getEAIndividual(j)); distances[i][j] = PhenotypeMetric.dist(rest.getEAIndividual(i), curRefSet.getEAIndividual(j));
} }
} }
while (curRefSet.size()<refSetSize) { while (curRefSet.size() < refSetSize) {
// "the vector having highest minimum distance will join the refset." // "the vector having highest minimum distance will join the refset."
int sel=selectHighestMinDistance(distances, h); int sel = selectHighestMinDistance(distances, h);
// add the selected diverse indy // add the selected diverse indy
curRefSet.add(rest.getEAIndividual(sel)); curRefSet.add(rest.getEAIndividual(sel));
// compute distances // compute distances
for (int i=0; i<distances.length; i++) { for (int i = 0; i < distances.length; i++) {
distances[i][h]=PhenotypeMetric.dist(rest.getEAIndividual(i), curRefSet.getEAIndividual(h)); distances[i][h] = PhenotypeMetric.dist(rest.getEAIndividual(i), curRefSet.getEAIndividual(h));
} }
// dont! remove it from the rest indi set // dont! remove it from the rest indi set
//rest.remove(sel); //rest.remove(sel);
@@ -599,7 +601,7 @@ public class ScatterSearch implements InterfaceOptimizer, java.io.Serializable,
if (dmin < 0) { if (dmin < 0) {
return dmin; return dmin;
} // tweak for trick } // tweak for trick
for (int j=1; j<maxRow; j++) { for (int j = 1; j < maxRow; j++) {
if (vals[col][j] < dmin) { if (vals[col][j] < dmin) {
dmin = vals[col][j]; dmin = vals[col][j];
} }
@@ -612,8 +614,8 @@ public class ScatterSearch implements InterfaceOptimizer, java.io.Serializable,
// select the first index with highest minimum. // select the first index with highest minimum.
double highestMin = getMinInCol(0, maxRow, distances); double highestMin = getMinInCol(0, maxRow, distances);
int sel = 0; int sel = 0;
for (int i=1; i<distances.length; i++) { for (int i = 1; i < distances.length; i++) {
double dtmp = getMinInCol(i,maxRow,distances); double dtmp = getMinInCol(i, maxRow, distances);
if (dtmp > highestMin) { if (dtmp > highestMin) {
highestMin = dtmp; highestMin = dtmp;
sel = i; sel = i;
@@ -629,10 +631,10 @@ public class ScatterSearch implements InterfaceOptimizer, java.io.Serializable,
private Population diversify(Population pop) { private Population diversify(Population pop) {
int[][] freq = new int[probDim][intervals]; int[][] freq = new int[probDim][intervals];
if (pop.size() > 0) { // count the interval appearances of already given individuals. if (pop.size() > 0) { // count the interval appearances of already given individuals.
for (int k=0; k<pop.size(); k++) { for (int k = 0; k < pop.size(); k++) {
double[] params = ((InterfaceDataTypeDouble)pop.getEAIndividual(k)).getDoubleData(); double[] params = ((InterfaceDataTypeDouble) pop.getEAIndividual(k)).getDoubleData();
for (int j=0; j<probDim; j++) { for (int j = 0; j < probDim; j++) {
for (int iv = 0; iv<intervals; iv++) { for (int iv = 0; iv < intervals; iv++) {
if (isInRangeInterval(params[j], j, iv)) { if (isInRangeInterval(params[j], j, iv)) {
freq[j][iv]++; freq[j][iv]++;
} }
@@ -641,16 +643,16 @@ public class ScatterSearch implements InterfaceOptimizer, java.io.Serializable,
} }
} else { } else {
// or start with diagonals // or start with diagonals
for (int i=0; i<intervals; i++) { for (int i = 0; i < intervals; i++) {
pop.add(createDiagIndies(i)); pop.add(createDiagIndies(i));
for (int j=0; j<probDim; j++) { for (int j = 0; j < probDim; j++) {
freq[j][i]=1; freq[j][i] = 1;
} }
} }
} }
while (pop.size() < poolSize) { while (pop.size() < poolSize) {
pop.add( createDiverseIndy(freq) ); pop.add(createDiverseIndy(freq));
} }
pop.setTargetSize(poolSize); pop.setTargetSize(poolSize);
if (TRACE) { if (TRACE) {
@@ -660,11 +662,11 @@ public class ScatterSearch implements InterfaceOptimizer, java.io.Serializable,
} }
private AbstractEAIndividual createDiverseIndy(int freq[][]) { private AbstractEAIndividual createDiverseIndy(int freq[][]) {
AbstractEAIndividual indy = (AbstractEAIndividual)template.clone(); AbstractEAIndividual indy = (AbstractEAIndividual) template.clone();
InterfaceDataTypeDouble dblIndy = (InterfaceDataTypeDouble)indy; InterfaceDataTypeDouble dblIndy = (InterfaceDataTypeDouble) indy;
double[] genes = dblIndy.getDoubleData(); double[] genes = dblIndy.getDoubleData();
for (int i=0; i<probDim; i++) { for (int i = 0; i < probDim; i++) {
int interv = selectInterv(i, freq); int interv = selectInterv(i, freq);
genes[i] = randInRangeInterval(i, interv); genes[i] = randInRangeInterval(i, interv);
freq[i][interv]++; freq[i][interv]++;
@@ -676,15 +678,15 @@ public class ScatterSearch implements InterfaceOptimizer, java.io.Serializable,
private double getFreqDepProb(int dim, int interv, int freq[][]) { private double getFreqDepProb(int dim, int interv, int freq[][]) {
double sum = 0; double sum = 0;
for (int k=0; k<intervals; k++) { for (int k = 0; k < intervals; k++) {
sum += (double)freq[dim][k]; sum += (double) freq[dim][k];
} }
return freq[dim][interv]/sum; return freq[dim][interv] / sum;
} }
private int selectInterv(int dim, int freq[][]) { private int selectInterv(int dim, int freq[][]) {
double[] probs = new double[intervals]; double[] probs = new double[intervals];
for (int i=0; i<intervals; i++) { for (int i = 0; i < intervals; i++) {
probs[i] = getFreqDepProb(dim, i, freq); probs[i] = getFreqDepProb(dim, i, freq);
} }
double rnd = RNG.randomDouble(); double rnd = RNG.randomDouble();
@@ -692,7 +694,7 @@ public class ScatterSearch implements InterfaceOptimizer, java.io.Serializable,
double sum = probs[0]; double sum = probs[0];
while (sum < rnd) { while (sum < rnd) {
sel++; sel++;
sum+=probs[sel]; sum += probs[sel];
} }
if (sum >= 1.0000001) { if (sum >= 1.0000001) {
System.err.println("Check this: sum>=1 in selectInterv"); System.err.println("Check this: sum>=1 in selectInterv");
@@ -708,10 +710,10 @@ public class ScatterSearch implements InterfaceOptimizer, java.io.Serializable,
* @return * @return
*/ */
private AbstractEAIndividual createDiagIndies(int interval) { private AbstractEAIndividual createDiagIndies(int interval) {
AbstractEAIndividual indy = (AbstractEAIndividual)template.clone(); AbstractEAIndividual indy = (AbstractEAIndividual) template.clone();
InterfaceDataTypeDouble dblIndy = (InterfaceDataTypeDouble)indy; InterfaceDataTypeDouble dblIndy = (InterfaceDataTypeDouble) indy;
double[] genes = dblIndy.getDoubleData(); double[] genes = dblIndy.getDoubleData();
for (int i=0; i<probDim; i++) { for (int i = 0; i < probDim; i++) {
genes[i] = randInRangeInterval(i, interval); genes[i] = randInRangeInterval(i, interval);
} }
dblIndy.SetDoubleGenotype(genes); dblIndy.SetDoubleGenotype(genes);
@@ -719,9 +721,9 @@ public class ScatterSearch implements InterfaceOptimizer, java.io.Serializable,
} }
private boolean isInRangeInterval(double d, int dim, int interval) { private boolean isInRangeInterval(double d, int dim, int interval) {
double dimStep = (range[dim][1]-range[dim][0])/intervals; double dimStep = (range[dim][1] - range[dim][0]) / intervals;
double lowB = range[dim][0]+(dimStep*interval); double lowB = range[dim][0] + (dimStep * interval);
double upB = lowB+dimStep; double upB = lowB + dimStep;
return isInRange(d, lowB, upB); return isInRange(d, lowB, upB);
} }
@@ -730,14 +732,13 @@ public class ScatterSearch implements InterfaceOptimizer, java.io.Serializable,
} }
private double randInRangeInterval(int dim, int interval) { private double randInRangeInterval(int dim, int interval) {
double dimStep = (range[dim][1]-range[dim][0])/intervals; double dimStep = (range[dim][1] - range[dim][0]) / intervals;
double lowB = range[dim][0]+(dimStep*interval); double lowB = range[dim][0] + (dimStep * interval);
double upB = lowB+dimStep; double upB = lowB + dimStep;
return RNG.randomDouble(lowB, upB); return RNG.randomDouble(lowB, upB);
} }
///////////// Trivials... ///////////// Trivials...
@Override @Override
public void setIdentifier(String name) { public void setIdentifier(String name) {
m_Identifier = name; m_Identifier = name;
@@ -758,18 +759,17 @@ public class ScatterSearch implements InterfaceOptimizer, java.io.Serializable,
InterfacePopulationChangedEventListener ea) { InterfacePopulationChangedEventListener ea) {
m_Listener = ea; m_Listener = ea;
} }
@Override @Override
public boolean removePopulationChangedEventListener( public boolean removePopulationChangedEventListener(
InterfacePopulationChangedEventListener ea) { InterfacePopulationChangedEventListener ea) {
if (m_Listener==ea) { if (m_Listener == ea) {
m_Listener=null; m_Listener = null;
return true; return true;
} else { } else {
return false; return false;
} }
} }
@Override
public void freeWilly() {}
@Override @Override
public String getIdentifier() { public String getIdentifier() {
@@ -786,7 +786,7 @@ public class ScatterSearch implements InterfaceOptimizer, java.io.Serializable,
} }
private boolean useLSHC() { private boolean useLSHC() {
return localSearchMethod.getSelectedTagID()==0; return localSearchMethod.getSelectedTagID() == 0;
} }
/** /**
@@ -871,7 +871,6 @@ public class ScatterSearch implements InterfaceOptimizer, java.io.Serializable,
} }
////////////////////////////////////////////7 ////////////////////////////////////////////7
/** /**
* This method performs a scatter search runnable. * This method performs a scatter search runnable.
*/ */
@@ -998,9 +997,11 @@ public class ScatterSearch implements InterfaceOptimizer, java.io.Serializable,
public double getImprovementEpsilon() { public double getImprovementEpsilon() {
return improvementEpsilon; return improvementEpsilon;
} }
public void setImprovementEpsilon(double improvementEpsilon) { public void setImprovementEpsilon(double improvementEpsilon) {
this.improvementEpsilon = improvementEpsilon; this.improvementEpsilon = improvementEpsilon;
} }
public String improvementEpsilonTipText() { public String improvementEpsilonTipText() {
return "Minimal relative fitness improvement for a candidate to enter the refSet - set to zero to deactivate."; return "Minimal relative fitness improvement for a candidate to enter the refSet - set to zero to deactivate.";
} }
@@ -1008,9 +1009,11 @@ public class ScatterSearch implements InterfaceOptimizer, java.io.Serializable,
public double getMinDiversityEpsilon() { public double getMinDiversityEpsilon() {
return minDiversityEpsilon; return minDiversityEpsilon;
} }
public void setMinDiversityEpsilon(double minDiversityEpsilon) { public void setMinDiversityEpsilon(double minDiversityEpsilon) {
this.minDiversityEpsilon = minDiversityEpsilon; this.minDiversityEpsilon = minDiversityEpsilon;
} }
public String minDiversityEpsilonTipText() { public String minDiversityEpsilonTipText() {
return "Minimal distance to other individuals in the refSet for a candidate to enter the refSet - set to zero to deactivate."; return "Minimal distance to other individuals in the refSet for a candidate to enter the refSet - set to zero to deactivate.";
} }

View File

@@ -10,18 +10,17 @@ import eva2.server.go.problems.B1Problem;
import eva2.server.go.problems.InterfaceOptimizationProblem; import eva2.server.go.problems.InterfaceOptimizationProblem;
import eva2.tools.math.RNG; import eva2.tools.math.RNG;
/** Simulated Annealing by Nelder and Mead, a simple yet efficient local search /**
* Simulated Annealing by Nelder and Mead, a simple yet efficient local search
* method. But to become less prone to premature convergence the cooling rate * method. But to become less prone to premature convergence the cooling rate
* has to be tuned to the optimization problem at hand. Again the population size * has to be tuned to the optimization problem at hand. Again the population
* gives the number of multi-starts. * size gives the number of multi-starts. Created by IntelliJ IDEA. User:
* Created by IntelliJ IDEA. * streiche Date: 13.05.2004 Time: 10:30:26 To change this template use File |
* User: streiche * Settings | File Templates.
* Date: 13.05.2004
* Time: 10:30:26
* To change this template use File | Settings | File Templates.
*/ */
public class SimulatedAnnealing implements InterfaceOptimizer, java.io.Serializable { public class SimulatedAnnealing implements InterfaceOptimizer, java.io.Serializable {
// These variables are necessary for the simple testcase // These variables are necessary for the simple testcase
private InterfaceOptimizationProblem m_Problem = new B1Problem(); private InterfaceOptimizationProblem m_Problem = new B1Problem();
private int m_MultiRuns = 100; private int m_MultiRuns = 100;
private int m_FitnessCalls = 100; private int m_FitnessCalls = 100;
@@ -29,7 +28,6 @@ public class SimulatedAnnealing implements InterfaceOptimizer, java.io.Serializa
GAIndividualBinaryData m_Best, m_Test; GAIndividualBinaryData m_Best, m_Test;
public double m_InitialTemperature = 2, m_CurrentTemperature; public double m_InitialTemperature = 2, m_CurrentTemperature;
public double m_Alpha = 0.9; public double m_Alpha = 0.9;
// These variables are necessary for the more complex LectureGUI enviroment // These variables are necessary for the more complex LectureGUI enviroment
transient private String m_Identifier = ""; transient private String m_Identifier = "";
transient private InterfacePopulationChangedEventListener m_Listener; transient private InterfacePopulationChangedEventListener m_Listener;
@@ -41,8 +39,8 @@ public class SimulatedAnnealing implements InterfaceOptimizer, java.io.Serializa
} }
public SimulatedAnnealing(SimulatedAnnealing a) { public SimulatedAnnealing(SimulatedAnnealing a) {
this.m_Population = (Population)a.m_Population.clone(); this.m_Population = (Population) a.m_Population.clone();
this.m_Problem = (InterfaceOptimizationProblem)a.m_Problem.clone(); this.m_Problem = (InterfaceOptimizationProblem) a.m_Problem.clone();
this.m_InitialTemperature = a.m_InitialTemperature; this.m_InitialTemperature = a.m_InitialTemperature;
this.m_CurrentTemperature = a.m_CurrentTemperature; this.m_CurrentTemperature = a.m_CurrentTemperature;
this.m_Alpha = a.m_Alpha; this.m_Alpha = a.m_Alpha;
@@ -53,7 +51,8 @@ public class SimulatedAnnealing implements InterfaceOptimizer, java.io.Serializa
return (Object) new SimulatedAnnealing(this); return (Object) new SimulatedAnnealing(this);
} }
/** This method will init the HillClimber /**
* This method will init the HillClimber
*/ */
@Override @Override
public void init() { public void init() {
@@ -63,13 +62,15 @@ public class SimulatedAnnealing implements InterfaceOptimizer, java.io.Serializa
this.firePropertyChangedEvent(Population.nextGenerationPerformed); this.firePropertyChangedEvent(Population.nextGenerationPerformed);
} }
/** 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 pop The initial population
* @param reset If true the population is reset. * @param reset If true the population is reset.
*/ */
@Override @Override
public void initByPopulation(Population pop, boolean reset) { public void initByPopulation(Population pop, boolean reset) {
this.m_Population = (Population)pop.clone(); this.m_Population = (Population) pop.clone();
this.m_CurrentTemperature = this.m_InitialTemperature; this.m_CurrentTemperature = this.m_InitialTemperature;
if (reset) { if (reset) {
this.m_Population.init(); this.m_Population.init();
@@ -78,12 +79,13 @@ public class SimulatedAnnealing implements InterfaceOptimizer, java.io.Serializa
} }
} }
/** This method will optimize /**
* This method will optimize
*/ */
@Override @Override
public void optimize() { public void optimize() {
AbstractEAIndividual indy; AbstractEAIndividual indy;
Population original = (Population)this.m_Population.clone(); Population original = (Population) this.m_Population.clone();
double delta; double delta;
for (int i = 0; i < this.m_Population.size(); i++) { for (int i = 0; i < this.m_Population.size(); i++) {
@@ -95,13 +97,13 @@ public class SimulatedAnnealing implements InterfaceOptimizer, java.io.Serializa
} }
this.m_Problem.evaluate(this.m_Population); this.m_Problem.evaluate(this.m_Population);
for (int i = 0; i < this.m_Population.size(); i++) { for (int i = 0; i < this.m_Population.size(); i++) {
if (((AbstractEAIndividual)original.get(i)).isDominatingDebConstraints(((AbstractEAIndividual)this.m_Population.get(i)))) { if (((AbstractEAIndividual) original.get(i)).isDominatingDebConstraints(((AbstractEAIndividual) this.m_Population.get(i)))) {
this.m_Population.remove(i); this.m_Population.remove(i);
this.m_Population.add(i, original.get(i)); this.m_Population.add(i, original.get(i));
} else { } else {
delta = this.calculateDelta(((AbstractEAIndividual)original.get(i)), ((AbstractEAIndividual)this.m_Population.get(i))); delta = this.calculateDelta(((AbstractEAIndividual) original.get(i)), ((AbstractEAIndividual) this.m_Population.get(i)));
//System.out.println("delta: " + delta); //System.out.println("delta: " + delta);
if (Math.exp(-delta/this.m_CurrentTemperature) > RNG.randomInt(0,1)) { if (Math.exp(-delta / this.m_CurrentTemperature) > RNG.randomInt(0, 1)) {
this.m_Population.remove(i); this.m_Population.remove(i);
this.m_Population.add(i, original.get(i)); this.m_Population.add(i, original.get(i));
} }
@@ -112,7 +114,9 @@ public class SimulatedAnnealing implements InterfaceOptimizer, java.io.Serializa
this.firePropertyChangedEvent(Population.nextGenerationPerformed); this.firePropertyChangedEvent(Population.nextGenerationPerformed);
} }
/** This method calculates the difference between the fitness values /**
* This method calculates the difference between the fitness values
*
* @param org The original * @param org The original
* @param mut The mutant * @param mut The mutant
*/ */
@@ -127,19 +131,23 @@ public class SimulatedAnnealing implements InterfaceOptimizer, java.io.Serializa
return result; return result;
} }
/** This method will set the problem that is to be optimized /**
* This method will set the problem that is to be optimized
*
* @param problem * @param problem
*/ */
@Override @Override
public void setProblem (InterfaceOptimizationProblem problem) { public void setProblem(InterfaceOptimizationProblem problem) {
this.m_Problem = problem; this.m_Problem = problem;
} }
@Override @Override
public InterfaceOptimizationProblem getProblem () { public InterfaceOptimizationProblem getProblem() {
return this.m_Problem; return this.m_Problem;
} }
/** This method will init the HillClimber /**
* This method will init the HillClimber
*/ */
public void defaultInit() { public void defaultInit() {
this.m_FitnessCallsNeeded = 0; this.m_FitnessCallsNeeded = 0;
@@ -147,24 +155,26 @@ public class SimulatedAnnealing implements InterfaceOptimizer, java.io.Serializa
this.m_Best.defaultInit(m_Problem); this.m_Best.defaultInit(m_Problem);
} }
/** This method will optimize /**
* This method will optimize
*/ */
public void defaultOptimize() { public void defaultOptimize() {
for (int i = 0; i < m_FitnessCalls; i++) { for (int i = 0; i < m_FitnessCalls; i++) {
this.m_Test = (GAIndividualBinaryData)((this.m_Best).clone()); this.m_Test = (GAIndividualBinaryData) ((this.m_Best).clone());
this.m_Test.defaultMutate(); this.m_Test.defaultMutate();
if (this.m_Test.defaultEvaulateAsMiniBits() < this.m_Best.defaultEvaulateAsMiniBits()) { if (this.m_Test.defaultEvaulateAsMiniBits() < this.m_Best.defaultEvaulateAsMiniBits()) {
this.m_Best = this.m_Test; this.m_Best = this.m_Test;
} }
this.m_FitnessCallsNeeded = i; this.m_FitnessCallsNeeded = i;
if (this.m_Best.defaultEvaulateAsMiniBits() == 0) { if (this.m_Best.defaultEvaulateAsMiniBits() == 0) {
i = this.m_FitnessCalls +1; i = this.m_FitnessCalls + 1;
} }
} }
} }
/** This main method will start a simple hillclimber. /**
* No arguments necessary. * This main method will start a simple hillclimber. No arguments necessary.
*
* @param args * @param args
*/ */
public static void main(String[] args) { public static void main(String[] args) {
@@ -178,31 +188,35 @@ public class SimulatedAnnealing implements InterfaceOptimizer, java.io.Serializa
} }
TmpMeanCalls /= program.m_MultiRuns; TmpMeanCalls /= program.m_MultiRuns;
TmpMeanFitness /= program.m_MultiRuns; TmpMeanFitness /= program.m_MultiRuns;
System.out.println("("+program.m_MultiRuns+"/"+program.m_FitnessCalls+") Mean Fitness : " + TmpMeanFitness + " Mean Calls needed: " + TmpMeanCalls); System.out.println("(" + program.m_MultiRuns + "/" + program.m_FitnessCalls + ") Mean Fitness : " + TmpMeanFitness + " Mean Calls needed: " + TmpMeanCalls);
} }
@Override @Override
public void addPopulationChangedEventListener(InterfacePopulationChangedEventListener ea) { public void addPopulationChangedEventListener(InterfacePopulationChangedEventListener ea) {
this.m_Listener = ea; this.m_Listener = ea;
} }
@Override @Override
public boolean removePopulationChangedEventListener( public boolean removePopulationChangedEventListener(
InterfacePopulationChangedEventListener ea) { InterfacePopulationChangedEventListener ea) {
if (m_Listener==ea) { if (m_Listener == ea) {
m_Listener=null; m_Listener = null;
return true; return true;
} else { } else {
return false; return false;
} }
} }
protected void firePropertyChangedEvent (String name) {
protected void firePropertyChangedEvent(String name) {
if (this.m_Listener != null) { if (this.m_Listener != null) {
this.m_Listener.registerPopulationStateChanged(this, name); this.m_Listener.registerPopulationStateChanged(this, name);
} }
} }
/** This method will return a string describing all properties of the optimizer /**
* and the applied methods. * This method will return a string describing all properties of the
* optimizer and the applied methods.
*
* @return A descriptive string * @return A descriptive string
*/ */
@Override @Override
@@ -210,63 +224,70 @@ public class SimulatedAnnealing implements InterfaceOptimizer, java.io.Serializa
String result = ""; String result = "";
if (this.m_Population.size() > 1) { if (this.m_Population.size() > 1) {
result += "Multi(" + this.m_Population.size() + ")-Start Hill Climbing:\n"; result += "Multi(" + this.m_Population.size() + ")-Start Hill Climbing:\n";
} } else {
else {
result += "Simulated Annealing:\n"; result += "Simulated Annealing:\n";
} }
result += "Optimization Problem: "; result += "Optimization Problem: ";
result += this.m_Problem.getStringRepresentationForProblem(this) +"\n"; result += this.m_Problem.getStringRepresentationForProblem(this) + "\n";
result += this.m_Population.getStringRepresentation(); result += this.m_Population.getStringRepresentation();
return result; return result;
} }
/** 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 * @param name The indenifier
*/ */
@Override @Override
public void setIdentifier(String name) { public void setIdentifier(String name) {
this.m_Identifier = name; this.m_Identifier = name;
} }
@Override @Override
public String getIdentifier() { public String getIdentifier() {
return this.m_Identifier; return this.m_Identifier;
} }
/** This method is required to free the memory on a RMIServer, /**
* but there is nothing to implement. * ********************************************************************************************************************
*/
@Override
public void freeWilly() {
}
/**********************************************************************************************************************
* These are for GUI * These are for GUI
*/ */
/** This method returns a global info string /**
* This method returns a global info string
*
* @return description * @return description
*/ */
public static String globalInfo() { public static String globalInfo() {
return "The simulated annealing uses an additional cooling rate instead of a simple dominate criteria to accpect worse solutions by chance."; return "The simulated annealing uses an additional cooling rate instead of a simple dominate criteria to accpect worse solutions by chance.";
} }
/** This method will return a naming String
/**
* This method will return a naming String
*
* @return The name of the algorithm * @return The name of the algorithm
*/ */
@Override @Override
public String getName() { public String getName() {
return "MS-SA"; return "MS-SA";
} }
/** Assuming that all optimizer will store thier data in a population
* we will allow acess to this population to query to current state /**
* of the optimizer. * Assuming that all optimizer will store thier data in a population we will
* allow acess to this population to query to current state of the
* optimizer.
*
* @return The population of current solutions to a given problem. * @return The population of current solutions to a given problem.
*/ */
@Override @Override
public Population getPopulation() { public Population getPopulation() {
return this.m_Population; return this.m_Population;
} }
@Override @Override
public void setPopulation(Population pop){ public void setPopulation(Population pop) {
this.m_Population = pop; this.m_Population = pop;
} }
public String populationTipText() { public String populationTipText() {
return "Change the number of best individuals stored (MS-SA))."; return "Change the number of best individuals stored (MS-SA)).";
} }
@@ -275,31 +296,40 @@ public class SimulatedAnnealing implements InterfaceOptimizer, java.io.Serializa
public InterfaceSolutionSet getAllSolutions() { public InterfaceSolutionSet getAllSolutions() {
return new SolutionSet(getPopulation()); return new SolutionSet(getPopulation());
} }
/** Set the initial temperature
/**
* Set the initial temperature
*
* @return The initial temperature. * @return The initial temperature.
*/ */
public double getInitialTemperature() { public double getInitialTemperature() {
return this.m_InitialTemperature; return this.m_InitialTemperature;
} }
public void setInitialTemperature(double pop){
public void setInitialTemperature(double pop) {
this.m_InitialTemperature = pop; this.m_InitialTemperature = pop;
} }
public String initialTemperatureTipText() { public String initialTemperatureTipText() {
return "Set the initial temperature."; return "Set the initial temperature.";
} }
/** Set alpha, which is used to degrade the temperaure /**
* Set alpha, which is used to degrade the temperaure
*
* @return The cooling rate. * @return The cooling rate.
*/ */
public double getAlpha() { public double getAlpha() {
return this.m_Alpha; return this.m_Alpha;
} }
public void setAlpha(double a){
public void setAlpha(double a) {
this.m_Alpha = a; this.m_Alpha = a;
if (this.m_Alpha > 1) { if (this.m_Alpha > 1) {
this.m_Alpha = 1.0; this.m_Alpha = 1.0;
} }
} }
public String alphaTipText() { public String alphaTipText() {
return "Set alpha, which is used to degrade the temperaure."; return "Set alpha, which is used to degrade the temperaure.";
} }

View File

@@ -13,14 +13,12 @@ import eva2.server.go.populations.SolutionSet;
import eva2.server.go.problems.B1Problem; import eva2.server.go.problems.B1Problem;
import eva2.server.go.problems.InterfaceOptimizationProblem; import eva2.server.go.problems.InterfaceOptimizationProblem;
/** A simple implementation of the steady-state GA with variable /**
* replacement schemes. To reduce the logging effort population.size() * A simple implementation of the steady-state GA with variable replacement
* optimization steps are performed each time optimize() is called. * schemes. To reduce the logging effort population.size() optimization steps
* Created by IntelliJ IDEA. * are performed each time optimize() is called. Created by IntelliJ IDEA. User:
* User: streiche * streiche Date: 19.07.2005 Time: 14:30:20 To change this template use File |
* Date: 19.07.2005 * Settings | File Templates.
* Time: 14:30:20
* To change this template use File | Settings | File Templates.
*/ */
public class SteadyStateGA implements InterfaceOptimizer, java.io.Serializable { public class SteadyStateGA implements InterfaceOptimizer, java.io.Serializable {
@@ -30,7 +28,6 @@ public class SteadyStateGA implements InterfaceOptimizer, java.io.Serializable {
private InterfaceSelection m_PartnerSelection = new SelectTournament(); private InterfaceSelection m_PartnerSelection = new SelectTournament();
private InterfaceReplacement m_ReplacementSelection = new ReplaceWorst(); private InterfaceReplacement m_ReplacementSelection = new ReplaceWorst();
private int m_NumberOfPartners = 1; private int m_NumberOfPartners = 1;
private String m_Identifier = ""; private String m_Identifier = "";
transient private InterfacePopulationChangedEventListener m_Listener; transient private InterfacePopulationChangedEventListener m_Listener;
@@ -38,13 +35,13 @@ public class SteadyStateGA implements InterfaceOptimizer, java.io.Serializable {
} }
public SteadyStateGA(SteadyStateGA a) { public SteadyStateGA(SteadyStateGA a) {
this.m_Population = (Population)a.m_Population.clone(); this.m_Population = (Population) a.m_Population.clone();
this.m_Problem = (InterfaceOptimizationProblem)a.m_Problem.clone(); this.m_Problem = (InterfaceOptimizationProblem) a.m_Problem.clone();
this.m_Identifier = a.m_Identifier; this.m_Identifier = a.m_Identifier;
this.m_NumberOfPartners = a.m_NumberOfPartners; this.m_NumberOfPartners = a.m_NumberOfPartners;
this.m_ParentSelection = (InterfaceSelection)a.m_ParentSelection.clone(); this.m_ParentSelection = (InterfaceSelection) a.m_ParentSelection.clone();
this.m_PartnerSelection = (InterfaceSelection)a.m_PartnerSelection.clone(); this.m_PartnerSelection = (InterfaceSelection) a.m_PartnerSelection.clone();
this.m_ReplacementSelection = (InterfaceReplacement)a.m_ReplacementSelection.clone(); this.m_ReplacementSelection = (InterfaceReplacement) a.m_ReplacementSelection.clone();
} }
@Override @Override
@@ -59,12 +56,14 @@ public class SteadyStateGA implements InterfaceOptimizer, java.io.Serializable {
this.firePropertyChangedEvent(Population.nextGenerationPerformed); this.firePropertyChangedEvent(Population.nextGenerationPerformed);
} }
/** This method will init the optimizer with a given population /**
* This method will init the optimizer with a given population
*
* @param reset If true the population is reset. * @param reset If true the population is reset.
*/ */
@Override @Override
public void initByPopulation(Population pop, boolean reset) { public void initByPopulation(Population pop, boolean reset) {
this.m_Population = (Population)pop.clone(); this.m_Population = (Population) pop.clone();
if (reset) { if (reset) {
this.m_Population.init(); this.m_Population.init();
this.evaluatePopulation(this.m_Population); this.evaluatePopulation(this.m_Population);
@@ -72,8 +71,9 @@ public class SteadyStateGA implements InterfaceOptimizer, java.io.Serializable {
} }
} }
/** This method will evaluate the current population using the /**
* given problem. * This method will evaluate the current population using the given problem.
*
* @param population The population that is to be evaluated * @param population The population that is to be evaluated
*/ */
private void evaluatePopulation(Population population) { private void evaluatePopulation(Population population) {
@@ -81,8 +81,10 @@ public class SteadyStateGA implements InterfaceOptimizer, java.io.Serializable {
population.incrGeneration(); population.incrGeneration();
} }
/** This method will assign fitness values to all individual in the /**
* current population. * This method will assign fitness values to all individual in the current
* population.
*
* @param population The population that is to be evaluated * @param population The population that is to be evaluated
*/ */
private void defaultEvaluatePopulation(Population population) { private void defaultEvaluatePopulation(Population population) {
@@ -95,14 +97,15 @@ public class SteadyStateGA implements InterfaceOptimizer, java.io.Serializable {
population.incrGeneration(); population.incrGeneration();
} }
/** 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.
*/ */
private void generateChildren() { private void generateChildren() {
this.m_ParentSelection.prepareSelection(this.m_Population); this.m_ParentSelection.prepareSelection(this.m_Population);
this.m_PartnerSelection.prepareSelection(this.m_Population); this.m_PartnerSelection.prepareSelection(this.m_Population);
Population parents = this.m_ParentSelection.selectFrom(this.m_Population, 1); Population parents = this.m_ParentSelection.selectFrom(this.m_Population, 1);
AbstractEAIndividual mother = (AbstractEAIndividual)parents.get(0); AbstractEAIndividual mother = (AbstractEAIndividual) parents.get(0);
parents = this.m_PartnerSelection.findPartnerFor(mother, this.m_Population, this.m_NumberOfPartners); parents = this.m_PartnerSelection.findPartnerFor(mother, this.m_Population, this.m_NumberOfPartners);
AbstractEAIndividual[] offSprings = mother.mateWith(parents); AbstractEAIndividual[] offSprings = mother.mateWith(parents);
offSprings[0].mutate(); offSprings[0].mutate();
@@ -119,40 +122,48 @@ public class SteadyStateGA implements InterfaceOptimizer, java.io.Serializable {
this.m_Population.incrGeneration(); this.m_Population.incrGeneration();
this.firePropertyChangedEvent(Population.nextGenerationPerformed); this.firePropertyChangedEvent(Population.nextGenerationPerformed);
} }
@Override @Override
public void addPopulationChangedEventListener(InterfacePopulationChangedEventListener ea) { public void addPopulationChangedEventListener(InterfacePopulationChangedEventListener ea) {
this.m_Listener = ea; this.m_Listener = ea;
} }
@Override @Override
public boolean removePopulationChangedEventListener( public boolean removePopulationChangedEventListener(
InterfacePopulationChangedEventListener ea) { InterfacePopulationChangedEventListener ea) {
if (m_Listener==ea) { if (m_Listener == ea) {
m_Listener=null; m_Listener = null;
return true; return true;
} else { } else {
return false; return false;
} }
} }
protected void firePropertyChangedEvent (String name) {
protected void firePropertyChangedEvent(String name) {
if (this.m_Listener != null) { if (this.m_Listener != null) {
this.m_Listener.registerPopulationStateChanged(this, name); this.m_Listener.registerPopulationStateChanged(this, name);
} }
} }
/** This method will set the problem that is to be optimized /**
* This method will set the problem that is to be optimized
*
* @param problem * @param problem
*/ */
@Override @Override
public void setProblem (InterfaceOptimizationProblem problem) { public void setProblem(InterfaceOptimizationProblem problem) {
this.m_Problem = problem; this.m_Problem = problem;
} }
@Override @Override
public InterfaceOptimizationProblem getProblem () { public InterfaceOptimizationProblem getProblem() {
return this.m_Problem; return this.m_Problem;
} }
/** This method will return a string describing all properties of the optimizer /**
* and the applied methods. * This method will return a string describing all properties of the
* optimizer and the applied methods.
*
* @return A descriptive string * @return A descriptive string
*/ */
@Override @Override
@@ -160,39 +171,42 @@ public class SteadyStateGA implements InterfaceOptimizer, java.io.Serializable {
String result = ""; String result = "";
result += "Genetic Algorithm:\n"; result += "Genetic Algorithm:\n";
result += "Optimization Problem: "; result += "Optimization Problem: ";
result += this.m_Problem.getStringRepresentationForProblem(this) +"\n"; result += this.m_Problem.getStringRepresentationForProblem(this) + "\n";
result += this.m_Population.getStringRepresentation(); result += this.m_Population.getStringRepresentation();
return result; return result;
} }
/** 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 * @param name The indenifier
*/ */
@Override @Override
public void setIdentifier(String name) { public void setIdentifier(String name) {
this.m_Identifier = name; this.m_Identifier = name;
} }
@Override @Override
public String getIdentifier() { public String getIdentifier() {
return this.m_Identifier; return this.m_Identifier;
} }
/** This method is required to free the memory on a RMIServer, /**
* but there is nothing to implement. * ********************************************************************************************************************
*/
@Override
public void freeWilly() {
}
/**********************************************************************************************************************
* These are for GUI * These are for GUI
*/ */
/** This method returns a global info string /**
* This method returns a global info string
*
* @return description * @return description
*/ */
public static String globalInfo() { public static String globalInfo() {
return "This is a Steady-State Genetic Algorithm."; return "This is a Steady-State Genetic Algorithm.";
} }
/** This method will return a naming String
/**
* This method will return a naming String
*
* @return The name of the algorithm * @return The name of the algorithm
*/ */
@Override @Override
@@ -200,19 +214,23 @@ public class SteadyStateGA implements InterfaceOptimizer, java.io.Serializable {
return "SS-GA"; return "SS-GA";
} }
/** Assuming that all optimizer will store thier data in a population /**
* we will allow acess to this population to query to current state * Assuming that all optimizer will store thier data in a population we will
* of the optimizer. * allow acess to this population to query to current state of the
* optimizer.
*
* @return The population of current solutions to a given problem. * @return The population of current solutions to a given problem.
*/ */
@Override @Override
public Population getPopulation() { public Population getPopulation() {
return this.m_Population; return this.m_Population;
} }
@Override @Override
public void setPopulation(Population pop){ public void setPopulation(Population pop) {
this.m_Population = pop; this.m_Population = pop;
} }
public String populationTipText() { public String populationTipText() {
return "Edit the properties of the population used."; return "Edit the properties of the population used.";
} }
@@ -221,21 +239,28 @@ public class SteadyStateGA implements InterfaceOptimizer, java.io.Serializable {
public InterfaceSolutionSet getAllSolutions() { public InterfaceSolutionSet getAllSolutions() {
return new SolutionSet(getPopulation()); return new SolutionSet(getPopulation());
} }
/** This method will set the parent selection method that is to be used
/**
* This method will set the parent selection method that is to be used
*
* @param selection * @param selection
*/ */
public void setParentSelection(InterfaceSelection selection) { public void setParentSelection(InterfaceSelection selection) {
this.m_ParentSelection = selection; this.m_ParentSelection = selection;
} }
public InterfaceSelection getParentSelection() { public InterfaceSelection getParentSelection() {
return this.m_ParentSelection; return this.m_ParentSelection;
} }
public String parentSelectionTipText() { public String parentSelectionTipText() {
return "Choose a parent selection method."; return "Choose a parent selection method.";
} }
/** This method will set the number of partners that are needed to create /**
* This method will set the number of partners that are needed to create
* offsprings by mating * offsprings by mating
*
* @param partners * @param partners
*/ */
public void setNumberOfPartners(int partners) { public void setNumberOfPartners(int partners) {
@@ -244,35 +269,46 @@ public class SteadyStateGA implements InterfaceOptimizer, java.io.Serializable {
} }
this.m_NumberOfPartners = partners; this.m_NumberOfPartners = partners;
} }
public int getNumberOfPartners() { public int getNumberOfPartners() {
return this.m_NumberOfPartners; return this.m_NumberOfPartners;
} }
public String numberOfPartnersTipText() { public String numberOfPartnersTipText() {
return "The number of mating partners needed to create offsprings."; return "The number of mating partners needed to create offsprings.";
} }
/** Choose a selection method for selecting recombination partners for given parents /**
* Choose a selection method for selecting recombination partners for given
* parents
*
* @param selection * @param selection
*/ */
public void setPartnerSelection(InterfaceSelection selection) { public void setPartnerSelection(InterfaceSelection selection) {
this.m_PartnerSelection = selection; this.m_PartnerSelection = selection;
} }
public InterfaceSelection getPartnerSelection() { public InterfaceSelection getPartnerSelection() {
return this.m_PartnerSelection; return this.m_PartnerSelection;
} }
public String partnerSelectionTipText() { public String partnerSelectionTipText() {
return "Choose a selection method for selecting recombination partners for given parents."; return "Choose a selection method for selecting recombination partners for given parents.";
} }
/** Choose a replacement strategy /**
* Choose a replacement strategy
*
* @param selection * @param selection
*/ */
public void setReplacementSelection(InterfaceReplacement selection) { public void setReplacementSelection(InterfaceReplacement selection) {
this.m_ReplacementSelection = selection; this.m_ReplacementSelection = selection;
} }
public InterfaceReplacement getReplacementSelection() { public InterfaceReplacement getReplacementSelection() {
return this.m_ReplacementSelection; return this.m_ReplacementSelection;
} }
public String replacementSelectionTipText() { public String replacementSelectionTipText() {
return "Choose a replacement strategy."; return "Choose a replacement strategy.";
} }

View File

@@ -9,16 +9,14 @@ import eva2.server.go.populations.SolutionSet;
import eva2.server.go.problems.B1Problem; import eva2.server.go.problems.B1Problem;
import eva2.server.go.problems.InterfaceOptimizationProblem; import eva2.server.go.problems.InterfaceOptimizationProblem;
/** Threshold accepting algorithm simliar strategy as the flood /**
* algorithm, similar problems. * Threshold accepting algorithm simliar strategy as the flood algorithm,
* Created by IntelliJ IDEA. * similar problems. Created by IntelliJ IDEA. User: streiche Date: 01.10.2004
* User: streiche * Time: 13:35:49 To change this template use File | Settings | File Templates.
* Date: 01.10.2004
* Time: 13:35:49
* To change this template use File | Settings | File Templates.
*/ */
public class ThresholdAlgorithm implements InterfaceOptimizer, java.io.Serializable { public class ThresholdAlgorithm implements InterfaceOptimizer, java.io.Serializable {
// These variables are necessary for the simple testcase // These variables are necessary for the simple testcase
private InterfaceOptimizationProblem m_Problem = new B1Problem(); private InterfaceOptimizationProblem m_Problem = new B1Problem();
private int m_MultiRuns = 100; private int m_MultiRuns = 100;
private int m_FitnessCalls = 100; private int m_FitnessCalls = 100;
@@ -26,7 +24,6 @@ public class ThresholdAlgorithm implements InterfaceOptimizer, java.io.Serializa
GAIndividualBinaryData m_Best, m_Test; GAIndividualBinaryData m_Best, m_Test;
public double m_InitialT = 2, m_CurrentT; public double m_InitialT = 2, m_CurrentT;
public double m_Alpha = 0.9; public double m_Alpha = 0.9;
// These variables are necessary for the more complex LectureGUI enviroment // These variables are necessary for the more complex LectureGUI enviroment
transient private String m_Identifier = ""; transient private String m_Identifier = "";
transient private InterfacePopulationChangedEventListener m_Listener; transient private InterfacePopulationChangedEventListener m_Listener;
@@ -38,8 +35,8 @@ public class ThresholdAlgorithm implements InterfaceOptimizer, java.io.Serializa
} }
public ThresholdAlgorithm(ThresholdAlgorithm a) { public ThresholdAlgorithm(ThresholdAlgorithm a) {
this.m_Population = (Population)a.m_Population.clone(); this.m_Population = (Population) a.m_Population.clone();
this.m_Problem = (InterfaceOptimizationProblem)a.m_Problem.clone(); this.m_Problem = (InterfaceOptimizationProblem) a.m_Problem.clone();
this.m_InitialT = a.m_InitialT; this.m_InitialT = a.m_InitialT;
this.m_CurrentT = a.m_CurrentT; this.m_CurrentT = a.m_CurrentT;
this.m_Alpha = a.m_Alpha; this.m_Alpha = a.m_Alpha;
@@ -50,7 +47,8 @@ public class ThresholdAlgorithm implements InterfaceOptimizer, java.io.Serializa
return (Object) new ThresholdAlgorithm(this); return (Object) new ThresholdAlgorithm(this);
} }
/** This method will init the HillClimber /**
* This method will init the HillClimber
*/ */
@Override @Override
public void init() { public void init() {
@@ -60,13 +58,15 @@ public class ThresholdAlgorithm implements InterfaceOptimizer, java.io.Serializa
this.firePropertyChangedEvent(Population.nextGenerationPerformed); this.firePropertyChangedEvent(Population.nextGenerationPerformed);
} }
/** 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 pop The initial population
* @param reset If true the population is reset. * @param reset If true the population is reset.
*/ */
@Override @Override
public void initByPopulation(Population pop, boolean reset) { public void initByPopulation(Population pop, boolean reset) {
this.m_Population = (Population)pop.clone(); this.m_Population = (Population) pop.clone();
this.m_CurrentT = this.m_InitialT; this.m_CurrentT = this.m_InitialT;
if (reset) { if (reset) {
this.m_Population.init(); this.m_Population.init();
@@ -75,12 +75,13 @@ public class ThresholdAlgorithm implements InterfaceOptimizer, java.io.Serializa
} }
} }
/** This method will optimize /**
* This method will optimize
*/ */
@Override @Override
public void optimize() { public void optimize() {
AbstractEAIndividual indy; AbstractEAIndividual indy;
Population original = (Population)this.m_Population.clone(); Population original = (Population) this.m_Population.clone();
double delta; double delta;
for (int i = 0; i < this.m_Population.size(); i++) { for (int i = 0; i < this.m_Population.size(); i++) {
@@ -92,7 +93,7 @@ public class ThresholdAlgorithm implements InterfaceOptimizer, java.io.Serializa
} }
this.m_Problem.evaluate(this.m_Population); this.m_Problem.evaluate(this.m_Population);
for (int i = 0; i < this.m_Population.size(); i++) { for (int i = 0; i < this.m_Population.size(); i++) {
delta = this.calculateDelta(((AbstractEAIndividual)original.get(i)), ((AbstractEAIndividual)this.m_Population.get(i))); delta = this.calculateDelta(((AbstractEAIndividual) original.get(i)), ((AbstractEAIndividual) this.m_Population.get(i)));
if (delta < this.m_CurrentT) { if (delta < this.m_CurrentT) {
this.m_Population.remove(i); this.m_Population.remove(i);
this.m_Population.add(i, original.get(i)); this.m_Population.add(i, original.get(i));
@@ -103,7 +104,9 @@ public class ThresholdAlgorithm implements InterfaceOptimizer, java.io.Serializa
this.firePropertyChangedEvent(Population.nextGenerationPerformed); this.firePropertyChangedEvent(Population.nextGenerationPerformed);
} }
/** This method calculates the difference between the fitness values /**
* This method calculates the difference between the fitness values
*
* @param org The original * @param org The original
* @param mut The mutant * @param mut The mutant
*/ */
@@ -118,19 +121,23 @@ public class ThresholdAlgorithm implements InterfaceOptimizer, java.io.Serializa
return result; return result;
} }
/** This method will set the problem that is to be optimized /**
* This method will set the problem that is to be optimized
*
* @param problem * @param problem
*/ */
@Override @Override
public void setProblem (InterfaceOptimizationProblem problem) { public void setProblem(InterfaceOptimizationProblem problem) {
this.m_Problem = problem; this.m_Problem = problem;
} }
@Override @Override
public InterfaceOptimizationProblem getProblem () { public InterfaceOptimizationProblem getProblem() {
return this.m_Problem; return this.m_Problem;
} }
/** This method will init the HillClimber /**
* This method will init the HillClimber
*/ */
public void defaultInit() { public void defaultInit() {
this.m_FitnessCallsNeeded = 0; this.m_FitnessCallsNeeded = 0;
@@ -138,24 +145,26 @@ public class ThresholdAlgorithm implements InterfaceOptimizer, java.io.Serializa
this.m_Best.defaultInit(m_Problem); this.m_Best.defaultInit(m_Problem);
} }
/** This method will optimize /**
* This method will optimize
*/ */
public void defaultOptimize() { public void defaultOptimize() {
for (int i = 0; i < m_FitnessCalls; i++) { for (int i = 0; i < m_FitnessCalls; i++) {
this.m_Test = (GAIndividualBinaryData)((this.m_Best).clone()); this.m_Test = (GAIndividualBinaryData) ((this.m_Best).clone());
this.m_Test.defaultMutate(); this.m_Test.defaultMutate();
if (this.m_Test.defaultEvaulateAsMiniBits() < this.m_Best.defaultEvaulateAsMiniBits()) { if (this.m_Test.defaultEvaulateAsMiniBits() < this.m_Best.defaultEvaulateAsMiniBits()) {
this.m_Best = this.m_Test; this.m_Best = this.m_Test;
} }
this.m_FitnessCallsNeeded = i; this.m_FitnessCallsNeeded = i;
if (this.m_Best.defaultEvaulateAsMiniBits() == 0) { if (this.m_Best.defaultEvaulateAsMiniBits() == 0) {
i = this.m_FitnessCalls +1; i = this.m_FitnessCalls + 1;
} }
} }
} }
/** This main method will start a simple hillclimber. /**
* No arguments necessary. * This main method will start a simple hillclimber. No arguments necessary.
*
* @param args * @param args
*/ */
public static void main(String[] args) { public static void main(String[] args) {
@@ -169,30 +178,35 @@ public class ThresholdAlgorithm implements InterfaceOptimizer, java.io.Serializa
} }
TmpMeanCalls /= program.m_MultiRuns; TmpMeanCalls /= program.m_MultiRuns;
TmpMeanFitness /= program.m_MultiRuns; TmpMeanFitness /= program.m_MultiRuns;
System.out.println("("+program.m_MultiRuns+"/"+program.m_FitnessCalls+") Mean Fitness : " + TmpMeanFitness + " Mean Calls needed: " + TmpMeanCalls); System.out.println("(" + program.m_MultiRuns + "/" + program.m_FitnessCalls + ") Mean Fitness : " + TmpMeanFitness + " Mean Calls needed: " + TmpMeanCalls);
} }
@Override @Override
public void addPopulationChangedEventListener(InterfacePopulationChangedEventListener ea) { public void addPopulationChangedEventListener(InterfacePopulationChangedEventListener ea) {
this.m_Listener = ea; this.m_Listener = ea;
} }
@Override @Override
public boolean removePopulationChangedEventListener( public boolean removePopulationChangedEventListener(
InterfacePopulationChangedEventListener ea) { InterfacePopulationChangedEventListener ea) {
if (m_Listener==ea) { if (m_Listener == ea) {
m_Listener=null; m_Listener = null;
return true; return true;
} else { } else {
return false; return false;
} }
} }
protected void firePropertyChangedEvent (String name) {
protected void firePropertyChangedEvent(String name) {
if (this.m_Listener != null) { if (this.m_Listener != null) {
this.m_Listener.registerPopulationStateChanged(this, name); this.m_Listener.registerPopulationStateChanged(this, name);
} }
} }
/** This method will return a string describing all properties of the optimizer /**
* and the applied methods. * This method will return a string describing all properties of the
* optimizer and the applied methods.
*
* @return A descriptive string * @return A descriptive string
*/ */
@Override @Override
@@ -200,63 +214,70 @@ public class ThresholdAlgorithm implements InterfaceOptimizer, java.io.Serializa
String result = ""; String result = "";
if (this.m_Population.size() > 1) { if (this.m_Population.size() > 1) {
result += "Multi(" + this.m_Population.size() + ")-Start Hill Climbing:\n"; result += "Multi(" + this.m_Population.size() + ")-Start Hill Climbing:\n";
} } else {
else {
result += "Threshold Algorithm:\n"; result += "Threshold Algorithm:\n";
} }
result += "Optimization Problem: "; result += "Optimization Problem: ";
result += this.m_Problem.getStringRepresentationForProblem(this) +"\n"; result += this.m_Problem.getStringRepresentationForProblem(this) + "\n";
result += this.m_Population.getStringRepresentation(); result += this.m_Population.getStringRepresentation();
return result; return result;
} }
/** 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 * @param name The indenifier
*/ */
@Override @Override
public void setIdentifier(String name) { public void setIdentifier(String name) {
this.m_Identifier = name; this.m_Identifier = name;
} }
@Override @Override
public String getIdentifier() { public String getIdentifier() {
return this.m_Identifier; return this.m_Identifier;
} }
/** This method is required to free the memory on a RMIServer, /**
* but there is nothing to implement. * ********************************************************************************************************************
*/
@Override
public void freeWilly() {
}
/**********************************************************************************************************************
* These are for GUI * These are for GUI
*/ */
/** This method returns a global info string /**
* This method returns a global info string
*
* @return description * @return description
*/ */
public static String globalInfo() { public static String globalInfo() {
return "The threshold algorithm uses an declining threshold to accpect new solutions."; return "The threshold algorithm uses an declining threshold to accpect new solutions.";
} }
/** This method will return a naming String
/**
* This method will return a naming String
*
* @return The name of the algorithm * @return The name of the algorithm
*/ */
@Override @Override
public String getName() { public String getName() {
return "MS-TA"; return "MS-TA";
} }
/** Assuming that all optimizer will store thier data in a population
* we will allow acess to this population to query to current state /**
* of the optimizer. * Assuming that all optimizer will store thier data in a population we will
* allow acess to this population to query to current state of the
* optimizer.
*
* @return The population of current solutions to a given problem. * @return The population of current solutions to a given problem.
*/ */
@Override @Override
public Population getPopulation() { public Population getPopulation() {
return this.m_Population; return this.m_Population;
} }
@Override @Override
public void setPopulation(Population pop){ public void setPopulation(Population pop) {
this.m_Population = pop; this.m_Population = pop;
} }
public String populationTipText() { public String populationTipText() {
return "Change the number of best individuals stored (MS-TA)."; return "Change the number of best individuals stored (MS-TA).";
} }
@@ -265,31 +286,40 @@ public class ThresholdAlgorithm implements InterfaceOptimizer, java.io.Serializa
public InterfaceSolutionSet getAllSolutions() { public InterfaceSolutionSet getAllSolutions() {
return new SolutionSet(getPopulation()); return new SolutionSet(getPopulation());
} }
/** Set the initial threshold
/**
* Set the initial threshold
*
* @return The initial temperature. * @return The initial temperature.
*/ */
public double getInitialT() { public double getInitialT() {
return this.m_InitialT; return this.m_InitialT;
} }
public void setInitialT(double pop){
public void setInitialT(double pop) {
this.m_InitialT = pop; this.m_InitialT = pop;
} }
public String initialTTipText() { public String initialTTipText() {
return "Set the initial threshold."; return "Set the initial threshold.";
} }
/** Set alpha, which is used to degrade the threshold /**
* Set alpha, which is used to degrade the threshold
*
* @return The initial temperature. * @return The initial temperature.
*/ */
public double getAlpha() { public double getAlpha() {
return this.m_Alpha; return this.m_Alpha;
} }
public void setAlpha(double a){
public void setAlpha(double a) {
this.m_Alpha = a; this.m_Alpha = a;
if (this.m_Alpha > 1) { if (this.m_Alpha > 1) {
this.m_Alpha = 1.0; this.m_Alpha = 1.0;
} }
} }
public String alphaTipText() { public String alphaTipText() {
return "Set alpha, which is used to degrade the threshold."; return "Set alpha, which is used to degrade the threshold.";
} }

View File

@@ -17,41 +17,41 @@ import eva2.server.go.strategies.tribes.TribesSwarm;
import java.util.Iterator; import java.util.Iterator;
import java.util.List; import java.util.List;
/** /**
* This is the TRIBES algorithm, an adaptive, parameter-less PSO implementation. * This is the TRIBES algorithm, an adaptive, parameter-less PSO implementation.
* I (MK) ported M.Clerc's java version 2006-02 21 and added the original notes below. * I (MK) ported M.Clerc's java version 2006-02 21 and added the original notes
* I had to do some modifications for the EvA framework, namely: * below. I had to do some modifications for the EvA framework, namely: - minor
* - minor adaptations allover the code to fit into the framework * adaptations allover the code to fit into the framework - the objective value
* - the objective value parameter must now be set within the GUI for each problem by hand (EvA doesnt assume to know an objective beforehand) * parameter must now be set within the GUI for each problem by hand (EvA doesnt
* - discrete search spaces are not directly supported any more (no "granularity") * assume to know an objective beforehand) - discrete search spaces are not
* - the benchmark-collection is gone, it might be included into the EvA benchmark set in the future, though * directly supported any more (no "granularity") - the benchmark-collection is
* - fixed two bugs (SunnySpell link generation, findWorst method) * gone, it might be included into the EvA benchmark set in the future, though -
* - fixed bugs in the CEC 2005 benchmarks (see the corresponding class) * fixed two bugs (SunnySpell link generation, findWorst method) - fixed bugs in
* - I widely kept the original comments, except for places I changed the code so much that they might mislead * the CEC 2005 benchmarks (see the corresponding class) - I widely kept the
* - thats all, I think * original comments, except for places I changed the code so much that they
* might mislead - thats all, I think
* *
* I could produce similar results as Clerc's on Rosenbrock and Griewank, (in his book on p. 148), * I could produce similar results as Clerc's on Rosenbrock and Griewank, (in
* I couldnt reproduce the 100% success rate on Ackley, though. * his book on p. 148), I couldnt reproduce the 100% success rate on Ackley,
* though.
* *
* @author Maurice Clerc, Marcel Kronfeld * @author Maurice Clerc, Marcel Kronfeld
* @date 2007-09-13 * @date 2007-09-13
* *
* Original notes: * Original notes:
* @version 2006-02 21 * @version 2006-02 21
* @author Maurice.Clerc@WriteMe.com * @author Maurice.Clerc@WriteMe.com {@link http://mauriceclerc.net}
* {@link http://mauriceclerc.net}
* {@link http://clerc.maurice.free.fr/pso/} * {@link http://clerc.maurice.free.fr/pso/}
* *
*/ */
/* Last updates (M.Clerc) /* Last updates (M.Clerc)
2006-02-21 Added a repelling option (see variable "repel" in Tribes). Not very convincing 2006-02-21 Added a repelling option (see variable "repel" in Tribes). Not very convincing
2006-01-03 Fixed a bug in maxIsolated (the memory was not well updated after improvement) 2006-01-03 Fixed a bug in maxIsolated (the memory was not well updated after improvement)
Also the same bug in "swarm" and "tribe". Thanks to Yann Cooreen. Also the same bug in "swarm" and "tribe". Thanks to Yann Cooreen.
Fortunately it was apparently without incidence Fortunately it was apparently without incidence
2005-12-26 Added items ALL for benchmarks 1 and 2, so that you can launch the whole 2005-12-26 Added items ALL for benchmarks 1 and 2, so that you can launch the whole
benchmark ... and have a cup of tea! benchmark ... and have a cup of tea!
2005-12-26 Fixed a bug. When you launched several optimisations (almost) on the same time 2005-12-26 Fixed a bug. When you launched several optimisations (almost) on the same time
result were not all the same (synchronisation problems) result were not all the same (synchronisation problems)
So you had to launch each problem one at a time. So you had to launch each problem one at a time.
Now it is done automatically. Even if you launch a problem before than the previous Now it is done automatically. Even if you launch a problem before than the previous
@@ -129,47 +129,39 @@ import java.util.List;
2005-11-21. Check if it is possible to easily find just the _value_ of the 2005-11-21. Check if it is possible to easily find just the _value_ of the
global minimum (not the position). "Chinese shadow" method? global minimum (not the position). "Chinese shadow" method?
*/ */
public class Tribes implements InterfaceOptimizer, java.io.Serializable { public class Tribes implements InterfaceOptimizer, java.io.Serializable {
public static final boolean TRACE = false; public static final boolean TRACE = false;
protected String m_Identifier = "TRIBES"; protected String m_Identifier = "TRIBES";
transient private InterfacePopulationChangedEventListener m_Listener = null; transient private InterfacePopulationChangedEventListener m_Listener = null;
protected AbstractOptimizationProblem m_problem; protected AbstractOptimizationProblem m_problem;
protected Population population; protected Population population;
public static int maxExplorerNb = 200; public static int maxExplorerNb = 200;
public static int maxMemoryNb = 300; public static int maxMemoryNb = 300;
public static int maxTribeNb = 300; public static int maxTribeNb = 300;
public static int[] strategies = new int[10]; // Just for information public static int[] strategies = new int[10]; // Just for information
public static int[] status = new int[9]; // Just for information public static int[] status = new int[9]; // Just for information
public static boolean testBC = false; // TODO project to EvA2 public static boolean testBC = false; // TODO project to EvA2
public static int adaptOption = 2; public static int adaptOption = 2;
public static double blind=0; // 0.5 //"Blind" move for very good particles, with a probability Tribes.blind public static double blind = 0; // 0.5 //"Blind" move for very good particles, with a probability Tribes.blind
public static boolean repel=false; // If 1, use a "repelling" strategy (see moveExplorer() ) public static boolean repel = false; // If 1, use a "repelling" strategy (see moveExplorer() )
private boolean checkConstraints=true; private boolean checkConstraints = true;
private static final long serialVersionUID = 1L; private static final long serialVersionUID = 1L;
TribesSwarm swarm = null; TribesSwarm swarm = null;
private int iter; private int iter;
protected double objectiveFirstDim = 0.; protected double objectiveFirstDim = 0.;
protected double[][] range, initRange; protected double[][] range, initRange;
protected int notifyGenChangedEvery = 10; protected int notifyGenChangedEvery = 10;
protected int problemDim; protected int problemDim;
protected int adaptThreshold, adaptMax, adapt; protected int adaptThreshold, adaptMax, adapt;
protected int informOption; /* For the best informant. protected int informOption; /* For the best informant.
-1 => really the best -1 => really the best
1 => the best according to a pseudo-gradient method 1 => the best according to a pseudo-gradient method
*/ */
protected int initExplorerNb=3; // Number of explorers at the very beginning
// use full range (0) or subspace (1) for init options 0 and 1
protected int rangeInitType=1;
protected int initExplorerNb = 3; // Number of explorers at the very beginning
// use full range (0) or subspace (1) for init options 0 and 1
protected int rangeInitType = 1;
private boolean m_Show = false; private boolean m_Show = false;
transient protected eva2.gui.Plot m_Plot = null; transient protected eva2.gui.Plot m_Plot = null;
// private int useAnchors = 0; // use anchors to detect environment changes? // private int useAnchors = 0; // use anchors to detect environment changes?
@@ -205,10 +197,10 @@ public class Tribes implements InterfaceOptimizer, java.io.Serializable {
@Override @Override
public void setProblem(InterfaceOptimizationProblem problem) { public void setProblem(InterfaceOptimizationProblem problem) {
// System.out.println("TRIBES.SetProblem()"); // System.out.println("TRIBES.SetProblem()");
m_problem = (AbstractOptimizationProblem)problem; m_problem = (AbstractOptimizationProblem) problem;
range = null; range = null;
if (problem instanceof InterfaceHasInitRange) { if (problem instanceof InterfaceHasInitRange) {
initRange = (double[][])((InterfaceHasInitRange)problem).getInitRange(); initRange = (double[][]) ((InterfaceHasInitRange) problem).getInitRange();
} }
Population pop = new Population(1); Population pop = new Population(1);
problem.initPopulation(pop); problem.initPopulation(pop);
@@ -244,9 +236,10 @@ public class Tribes implements InterfaceOptimizer, java.io.Serializable {
} }
/** /**
* As TRIBES manages an own structured set of particles (the list of Tribes containing explorers * As TRIBES manages an own structured set of particles (the list of Tribes
* and memories), the setPopulation method is only telling Tribes the range * containing explorers and memories), the setPopulation method is only
* of the indiviuals in the beginning of the run, the individuals will be discarded. * telling Tribes the range of the indiviuals in the beginning of the run,
* the individuals will be discarded.
*/ */
@Override @Override
public void initByPopulation(Population pop, boolean reset) { public void initByPopulation(Population pop, boolean reset) {
@@ -257,9 +250,9 @@ public class Tribes implements InterfaceOptimizer, java.io.Serializable {
TribesPosition bestMemPos = swarm.getBestMemory().getPos(); TribesPosition bestMemPos = swarm.getBestMemory().getPos();
AbstractEAIndividual bestExp = population.getBestEAIndividual(); AbstractEAIndividual bestExp = population.getBestEAIndividual();
if (bestMemPos.firstIsBetter(bestMemPos.getFitness(), bestExp.getFitness())) { if (bestMemPos.firstIsBetter(bestMemPos.getFitness(), bestExp.getFitness())) {
AbstractEAIndividual indy = (AbstractEAIndividual)bestExp.clone(); AbstractEAIndividual indy = (AbstractEAIndividual) bestExp.clone();
indy.setFitness(bestMemPos.getFitness()); indy.setFitness(bestMemPos.getFitness());
((InterfaceDataTypeDouble)indy).SetDoubleGenotype(bestMemPos.getPos()); ((InterfaceDataTypeDouble) indy).SetDoubleGenotype(bestMemPos.getPos());
return indy; return indy;
} else { } else {
return bestExp; return bestExp;
@@ -296,8 +289,8 @@ public class Tribes implements InterfaceOptimizer, java.io.Serializable {
// adaptMax=swarmSize; // adaptMax=swarmSize;
adaptMax = swarm.linkNb(swarm); adaptMax = swarm.linkNb(swarm);
if (adaptThreshold >= adaptMax) { if (adaptThreshold >= adaptMax) {
if (swarm.getBestMemory().getPrevPos().getTotalError() <= if (swarm.getBestMemory().getPrevPos().getTotalError()
swarm.getBestMemory().getPos().getTotalError()) { <= swarm.getBestMemory().getPos().getTotalError()) {
adapt = iter; // Memorize at which iteration adaptation occurs adapt = iter; // Memorize at which iteration adaptation occurs
for (int i = 0; i < swarm.getTribeCnt(); i++) { for (int i = 0; i < swarm.getTribeCnt(); i++) {
@@ -333,7 +326,7 @@ public class Tribes implements InterfaceOptimizer, java.io.Serializable {
if (TRACE) { if (TRACE) {
System.out.println("loop finished after " + population.getFunctionCalls() + " evaluations"); System.out.println("loop finished after " + population.getFunctionCalls() + " evaluations");
//for (int i=0; i<population.size(); i++) System.out.println(" * "+((TribesExplorer)population.get(i)).getStringRepresentation()); //for (int i=0; i<population.size(); i++) System.out.println(" * "+((TribesExplorer)population.get(i)).getStringRepresentation());
System.out.println(" best: "+population.getBestEAIndividual().getStringRepresentation() + " - " + population.getBestEAIndividual().getFitness(0)); System.out.println(" best: " + population.getBestEAIndividual().getStringRepresentation() + " - " + population.getBestEAIndividual().getFitness(0));
System.out.println("swarm contains " + swarm.numParticles() + " particles in iteration " + iter); System.out.println("swarm contains " + swarm.numParticles() + " particles in iteration " + iter);
} }
} }
@@ -342,9 +335,9 @@ public class Tribes implements InterfaceOptimizer, java.io.Serializable {
// TODO // TODO
double pos[], vel[]; double pos[], vel[];
for (int i=0; i<pop.size(); i++) { for (int i = 0; i < pop.size(); i++) {
pos = ((TribesExplorer)pop.getEAIndividual(i)).getDoubleData(); pos = ((TribesExplorer) pop.getEAIndividual(i)).getDoubleData();
vel = ((TribesExplorer)pop.getEAIndividual(i)).getVelocity(); vel = ((TribesExplorer) pop.getEAIndividual(i)).getVelocity();
plotIndy(pos, vel, i); plotIndy(pos, vel, i);
// hier weiter! // hier weiter!
} }
@@ -372,7 +365,7 @@ public class Tribes implements InterfaceOptimizer, java.io.Serializable {
// double[] tmpD = new double[2]; // double[] tmpD = new double[2];
// tmpD[0] = 0; // tmpD[0] = 0;
// tmpD[1] = 0; // tmpD[1] = 0;
this.m_Plot = new eva2.gui.Plot("TRIBES "+ population.getGeneration(), "x1", "x2", range[0], range[1]); this.m_Plot = new eva2.gui.Plot("TRIBES " + population.getGeneration(), "x1", "x2", range[0], range[1]);
// this.m_Plot.setCornerPoints(range, 0); // this.m_Plot.setCornerPoints(range, 0);
} }
} }
@@ -383,253 +376,161 @@ public class Tribes implements InterfaceOptimizer, java.io.Serializable {
} }
/** /**
*
public synchronized void search(param pb, PrintStream runSave, PrintStream synthSave) { * public synchronized void search(param pb, PrintStream runSave,
* PrintStream synthSave) {
double epsMean, epsMin, epsMax; *
double evalMean; * double epsMean, epsMin, epsMax; double evalMean; int n; int run, run1;
int n; * int successNb;
int run, run1; *
int successNb; * // Exploratrices générées explorer explorer[] = new explorer[
* Tribes.maxExplorerNb];
// Exploratrices générées *
explorer explorer[] = new explorer[ * double[] eps = new double[pb.maxRun]; double[] evalNb = new
Tribes.maxExplorerNb]; * double[pb.maxRun]; double[] temp = new double[3]; successNb = 0; for (n =
* 0; n < 9; n++) { // For information Tribes.strategies[n] = 0;
double[] eps = new double[pb.maxRun]; * Tribes.status[n] = 0; } ; epsMin = Tribes.infinity; epsMax = 0;
double[] evalNb = new double[pb.maxRun]; *
double[] temp = new double[3]; * // Titles
successNb = 0; *
for (n = 0; n < 9; n++) { // For information * print("\nIter. Eval. Best_fitness", displayPb); save("\n\n PROBLEM
Tribes.strategies[n] = 0; * "+pb.function[0],synthSave); save("\nRun Iter. Eval. Best_fitness
Tribes.status[n] = 0; * Position", synthSave); save("\n\n PROBLEM "+pb.function[0],runSave);
} *
; * // ** // * Loop on runs // * for (run = 0; run < pb.maxRun; run++) { run1
epsMin = Tribes.infinity; * = run + 1; save("\n" + run1 + " ", synthSave); temp = solve(pb,
epsMax = 0; * Tribes.initExplorerNb,runSave,synthSave);
*
// Titles * eps[run] = temp[0]; evalNb[run] = temp[1]; successNb = successNb + (int)
* temp[2]; if (eps[run] < epsMin) { epsMin = eps[run]; } if (eps[run] >
print("\nIter. Eval. Best_fitness", displayPb); * epsMax) { epsMax = eps[run]; } }
save("\n\n PROBLEM "+pb.function[0],synthSave); *
save("\nRun Iter. Eval. Best_fitness Position", synthSave); * // Mean values epsMean = 0; evalMean = 0; for (run = 0; run < pb.maxRun;
save("\n\n PROBLEM "+pb.function[0],runSave); * run++) { epsMean = epsMean + eps[run]; evalMean = evalMean + evalNb[run];
* }
// ** *
// * Loop on runs * epsMean = epsMean / pb.maxRun; evalMean = evalMean / pb.maxRun;
// * * print("\nStatuses ", displayPb); for (n = 1; n < 10; n++) { print("\n" +
for (run = 0; run < pb.maxRun; run++) { * n + " " + Tribes.status[n - 1] + " times", displayPb); }
run1 = run + 1; * print("\nStrategies ", displayPb); for (n = 1; n < 10; n++) { print("\n"
save("\n" + run1 + " ", synthSave); * + n + " " + Tribes.strategies[n - 1] + " times", displayPb); }
temp = solve(pb, Tribes.initExplorerNb,runSave,synthSave); * print("\nMIN BEST TOTAL_ERROR " + epsMin, displayPb); print("\nMEAN BEST
* TOTAL_ERROR " + epsMean, displayPb); print("\nMEAN EVAL. NUMBER " +
eps[run] = temp[0]; * evalMean, displayPb); print("\n SUCCESS RATE " + (double) successNb /
evalNb[run] = temp[1]; * pb.maxRun, displayPb);
successNb = successNb + (int) temp[2]; *
if (eps[run] < epsMin) { * save("\nMIN BEST TOTAL_ERROR " + epsMin, synthSave); save("\nMEAN BEST
epsMin = eps[run]; * TOTAL_ERROR " + epsMean, synthSave); save("\nMEAN EVAL. NUMBER " +
} * evalMean, synthSave); save("\n SUCCESS RATE " + (double) successNb /
if (eps[run] > epsMax) { * pb.maxRun, synthSave);
epsMax = eps[run]; *
} * save("\n-1", runSave); // Special value for the end of the file. Used for
} * graphics
*
// Mean values * } // End of search()
epsMean = 0; *
evalMean = 0; * public double[] solve(param pb, int initExplorerNb, PrintStream runSave,
for (run = 0; run < pb.maxRun; run++) { * PrintStream synthSave) { int adapt, adaptMax; int adaptThreshold; int d,
epsMean = epsMean + eps[run]; * D = pb.H.Dimension; int evalF; int iter; int n; boolean stop; double[]
evalMean = evalMean + evalNb[run]; * temp = new double[3]; int informOption; // For the best informant. // -1
} * => really the best // 1 => the best according to a pseudo-gradient method
*
epsMean = epsMean / pb.maxRun; * // -----------INIT START // Generate a swarm evalF=0; swarm swarm = new
evalMean = evalMean / pb.maxRun; * swarm(); evalF=swarm.generateSwarm(pb, initExplorerNb, pb.initType,
print("\nStatuses ", displayPb); * displayPb,evalF);
for (n = 1; n < 10; n++) { *
print("\n" + n + " " + Tribes.status[n - 1] + " times", * // swarm.displaySwarm(swarm,out); // print("\n Best after init:
displayPb); * "+swarm.Best.position.fitness,out);
} *
print("\nStrategies ", displayPb); * // Move the swarm as long as the stop criterion is false iter = 0; adapt
for (n = 1; n < 10; n++) { * = 0; stop = false; informOption = -1; // Hard coded option // -1 =
print("\n" + n + " " + Tribes.strategies[n - 1] + " times", * absolute best informant // 1 = relative (pseudo-gradient) best informant.
displayPb); * For "niching" // See also moveExplorer, which can be modified in order to
} * avoid this parameter // // -----------INIT END
print("\nMIN BEST TOTAL_ERROR " + epsMin, displayPb); *
print("\nMEAN BEST TOTAL_ERROR " + epsMean, displayPb); *
print("\nMEAN EVAL. NUMBER " + evalMean, displayPb); * // -----------OPTIMIZE START iterations:while (!stop) {
print("\n SUCCESS RATE " + (double) successNb / pb.maxRun, *
displayPb); * swarm.size = swarm.swarmSize(swarm); iter++; // swarm.Best.positionPrev =
* swarm.Best.position;
save("\nMIN BEST TOTAL_ERROR " + epsMin, synthSave); *
save("\nMEAN BEST TOTAL_ERROR " + epsMean, synthSave); * evalF=swarm.moveSwarm(pb, swarm, informOption, displayPb, evalF); //***
save("\nMEAN EVAL. NUMBER " + evalMean, synthSave); * HERE IT MOVES
save("\n SUCCESS RATE " + (double) successNb / pb.maxRun, synthSave); *
* // Some display each time there is "enough" improvement // fduring the
save("\n-1", runSave); // Special value for the end of the file. Used for graphics * process
*
} // End of search() * double enough = 0.005; if ((1 - enough) *
* swarm.Best.positionPrev.totalError > swarm.Best.position.totalError) {
public double[] solve(param pb, int initExplorerNb, PrintStream runSave, PrintStream synthSave) { * print("\nIter. " + iter, displayPb); print(" Eval. " + evalF, displayPb);
int adapt, adaptMax; * print(" totalError " + swarm.Best.position.totalError, displayPb);
int adaptThreshold; * print(" " + swarm.size + " particles", displayPb); } // Save run info
int d, D = pb.H.Dimension; * save("\n" + iter + " " + evalF + " " + swarm.Best.position.totalError + "
int evalF; * " + swarm.size, runSave);
int iter; *
int n; * // Evaluate the stop criterion stop = evalF >= pb.maxEval || pb.accuracy
boolean stop; * > swarm.Best.position.totalError;
double[] temp = new double[3]; *
int informOption; * if (Tribes.adaptOption == 0) { continue iterations; }
// For the best informant. *
// -1 => really the best * if (Tribes.adaptOption == 1) { // Just reinitialize the swarm
// 1 => the best according to a pseudo-gradient method * adaptThreshold = iter - adapt; // adaptMax=swarmSize; adaptMax =
* swarm.linkNb(swarm); if (adaptThreshold >= adaptMax) { if
// -----------INIT START * (swarm.Best.positionPrev.totalError <= swarm.Best.position.totalError) {
// Generate a swarm * adapt = iter; // Memorize at which iteration adaptation occurs
evalF=0; *
swarm swarm = new swarm(); * for (n = 0; n < swarm.tribeNb; n++) {
evalF=swarm.generateSwarm(pb, initExplorerNb, pb.initType, displayPb,evalF); * evalF=swarm.tribes[n].reinitTribe(pb,evalF); } } } continue iterations; }
*
// swarm.displaySwarm(swarm,out); * // if(swarm.Best.positionPrev.totalError<=swarm.Best.position.totalError)
// print("\n Best after init: "+swarm.Best.position.fitness,out); * { // Structural adaptations
*
// Move the swarm as long as the stop criterion is false * //swarmSize = swarm.swarmSize(swarm);
iter = 0; *
adapt = 0; * // print("\nSwarm size (explorers): " + swarmSize,out); // print("
stop = false; * Tribes: (explorers/memories) ",out); // for (n = 0; n <
informOption = -1; * swarm.tribeNumber; n++) { // print(swarm.tribes[n].explorerNb + "/" + //
// Hard coded option * swarm.tribes[n].memoryNb + " ",out); // } // // On "laisse le temps" à
// -1 = absolute best informant * chaque tribu de bouger avant éventuelle adaptation // La règle est
// 1 = relative (pseudo-gradient) best informant. For "niching" * empirique et peut être modifiée //
// See also moveExplorer, which can be modified in order to avoid this parameter *
// * adaptThreshold = iter - adapt; // adaptMax=swarmSize; adaptMax =
// -----------INIT END * swarm.linkNb(swarm);
*
* if (adaptThreshold >= adaptMax) { adapt = iter; // Memorize at which
// -----------OPTIMIZE START * iteration adaptation occurs evalF=swarm.adaptSwarm(pb,
iterations:while (!stop) { * Tribes.adaptOption, swarm, displayPb,evalF); // Réalise l'adaptation
*
swarm.size = swarm.swarmSize(swarm); * // Modifie la recherche de la meilleure informatrice // normale (la
iter++; * "vraie" meilleure) ou dépendant d'un pseudo-gradient // (cf.
// swarm.Best.positionPrev = swarm.Best.position; * informExplorer) // // informOption=-informOption; } // print("\n Nb of
* tribes: " + swarm.tribeNumber + // "\n Particles/tribe:",out); // for (n
evalF=swarm.moveSwarm(pb, swarm, informOption, displayPb, evalF); //*** HERE IT MOVES * = 0; n < swarm.tribeNumber; n++) { // print(swarm.tribes[n].explorerNb +
* " ",out); // } // // print("\n Statuses :"); // for (n = 0; n <
// Some display each time there is "enough" improvement * swarm.tribeNumber; n++) { // print(swarm.tribes[n].status + " ",out); //
// fduring the process * }
*
double enough = 0.005; *
if ((1 - enough) * swarm.Best.positionPrev.totalError > * }
swarm.Best.position.totalError) { * // -----------OPTIMIZE END }
print("\nIter. " + iter, displayPb); *
print(" Eval. " + evalF, displayPb); * // Result of the run print("\nBest: eval.= " + evalF + "\n", displayPb);
print(" totalError " + swarm.Best.position.totalError, * swarm.Best.displayMemory(displayPb);
displayPb); *
print(" " + swarm.size + " particles", displayPb); * save(" " + iter + " " + evalF+ " ", synthSave);
} *
// Save run info * for (d = 0; d < pb.fitnessSize; d++) {
save("\n" + iter + " " + evalF + " " + * save(swarm.Best.position.fitness[d] + " ", synthSave); }
swarm.Best.position.totalError + " " + swarm.size, runSave); *
* for (d = 0; d < D; d++) { save(" " + swarm.Best.position.x[d],
// Evaluate the stop criterion * synthSave); }
stop = evalF >= pb.maxEval || *
pb.accuracy > swarm.Best.position.totalError; * // Prepare return temp[0] = swarm.Best.position.totalError; temp[1] =
* evalF; if (evalF < pb.maxEval) { temp[2] = 1; } else { temp[2] = 0; }
if (Tribes.adaptOption == 0) { *
continue iterations; * return temp; }
} *
*/
if (Tribes.adaptOption == 1) { // Just reinitialize the swarm
adaptThreshold = iter - adapt;
// adaptMax=swarmSize;
adaptMax = swarm.linkNb(swarm);
if (adaptThreshold >= adaptMax) {
if (swarm.Best.positionPrev.totalError <=
swarm.Best.position.totalError) {
adapt = iter; // Memorize at which iteration adaptation occurs
for (n = 0; n < swarm.tribeNb; n++) {
evalF=swarm.tribes[n].reinitTribe(pb,evalF);
}
}
}
continue iterations;
}
// if(swarm.Best.positionPrev.totalError<=swarm.Best.position.totalError)
{
// Structural adaptations
//swarmSize = swarm.swarmSize(swarm);
// print("\nSwarm size (explorers): " + swarmSize,out);
// print(" Tribes: (explorers/memories) ",out);
// for (n = 0; n < swarm.tribeNumber; n++) {
// print(swarm.tribes[n].explorerNb + "/" +
// swarm.tribes[n].memoryNb + " ",out);
// }
//
// On "laisse le temps" à chaque tribu de bouger avant éventuelle adaptation
// La règle est empirique et peut être modifiée
//
adaptThreshold = iter - adapt;
// adaptMax=swarmSize;
adaptMax = swarm.linkNb(swarm);
if (adaptThreshold >= adaptMax) {
adapt = iter; // Memorize at which iteration adaptation occurs
evalF=swarm.adaptSwarm(pb, Tribes.adaptOption, swarm,
displayPb,evalF); // Réalise l'adaptation
// Modifie la recherche de la meilleure informatrice
// normale (la "vraie" meilleure) ou dépendant d'un pseudo-gradient
// (cf. informExplorer)
//
// informOption=-informOption;
}
// print("\n Nb of tribes: " + swarm.tribeNumber +
// "\n Particles/tribe:",out);
// for (n = 0; n < swarm.tribeNumber; n++) {
// print(swarm.tribes[n].explorerNb + " ",out);
// }
//
// print("\n Statuses :");
// for (n = 0; n < swarm.tribeNumber; n++) {
// print(swarm.tribes[n].status + " ",out);
// }
}
// -----------OPTIMIZE END
}
// Result of the run
print("\nBest: eval.= " + evalF + "\n", displayPb);
swarm.Best.displayMemory(displayPb);
save(" " + iter + " " + evalF+ " ", synthSave);
for (d = 0; d < pb.fitnessSize; d++) {
save(swarm.Best.position.fitness[d] + " ", synthSave);
}
for (d = 0; d < D; d++) {
save(" " + swarm.Best.position.x[d], synthSave);
}
// Prepare return
temp[0] = swarm.Best.position.totalError;
temp[1] = evalF;
if (evalF < pb.maxEval) {
temp[2] = 1;
} else {
temp[2] = 0;
}
return temp;
}
**/
/** /**
* Population will be hidden. * Population will be hidden.
*/ */
@@ -638,9 +539,10 @@ public class Tribes implements InterfaceOptimizer, java.io.Serializable {
} }
/** /**
* As TRIBES manages an own structured set of particles (the list of Tribes containing explorers * As TRIBES manages an own structured set of particles (the list of Tribes
* and memories), the setPopulation method is only telling Tribes the range * containing explorers and memories), the setPopulation method is only
* of the indiviuals in the beginning of the run, the individuals will be discarded. * telling Tribes the range of the indiviuals in the beginning of the run,
* the individuals will be discarded.
*/ */
@Override @Override
public void setPopulation(Population pop) { public void setPopulation(Population pop) {
@@ -649,7 +551,7 @@ public class Tribes implements InterfaceOptimizer, java.io.Serializable {
} }
population = pop; population = pop;
if (population.get(0) instanceof InterfaceDataTypeDouble) { if (population.get(0) instanceof InterfaceDataTypeDouble) {
range = ((InterfaceDataTypeDouble)population.get(0)).getDoubleRange(); range = ((InterfaceDataTypeDouble) population.get(0)).getDoubleRange();
setDimension(range.length); setDimension(range.length);
} else { } else {
System.err.println("warning, TRIBES requires InterfaceESIndidivual instead of " + population.get(0).getClass() + ". Couldnt correctly init the problem range."); System.err.println("warning, TRIBES requires InterfaceESIndidivual instead of " + population.get(0).getClass() + ". Couldnt correctly init the problem range.");
@@ -666,10 +568,11 @@ public class Tribes implements InterfaceOptimizer, java.io.Serializable {
} }
/** /**
* Be aware that TRIBES uses two kinds of particles: explorers and memories. As memories * Be aware that TRIBES uses two kinds of particles: explorers and memories.
* are inactive in that they dont search the problem space directly, they are not included * As memories are inactive in that they dont search the problem space
* in the returned population. This, however, means that the best found solution might not * directly, they are not included in the returned population. This,
* be inluded as well at several if not most stages of the search. * however, means that the best found solution might not be inluded as well
* at several if not most stages of the search.
*/ */
@Override @Override
public Population getPopulation() { public Population getPopulation() {
@@ -677,15 +580,16 @@ public class Tribes implements InterfaceOptimizer, java.io.Serializable {
} }
/** /**
* Return a SolutionSet of TribesExplorers (AbstractEAIndividuals) of which some where * Return a SolutionSet of TribesExplorers (AbstractEAIndividuals) of which
* memory particles, thus the returned population is larger than the current population. * some where memory particles, thus the returned population is larger than
* the current population.
* *
* @return a population of possible solutions. * @return a population of possible solutions.
*/ */
@Override @Override
public InterfaceSolutionSet getAllSolutions() { public InterfaceSolutionSet getAllSolutions() {
// return population and memories? // return population and memories?
Population all = (Population)population.clone(); Population all = (Population) population.clone();
List<TribesPosition> mems = swarm.collectMem(); List<TribesPosition> mems = swarm.collectMem();
for (Iterator<TribesPosition> iterator = mems.iterator(); iterator.hasNext();) { for (Iterator<TribesPosition> iterator = mems.iterator(); iterator.hasNext();) {
TribesPosition tp = iterator.next(); TribesPosition tp = iterator.next();
@@ -698,7 +602,7 @@ public class Tribes implements InterfaceOptimizer, java.io.Serializable {
} }
protected TribesExplorer positionToExplorer(TribesPosition pos) { protected TribesExplorer positionToExplorer(TribesPosition pos) {
TribesExplorer tmp = (TribesExplorer)population.get(0); TribesExplorer tmp = (TribesExplorer) population.get(0);
if (tmp == null) { if (tmp == null) {
System.err.println("Error in Tribes::positionToExplorer!"); System.err.println("Error in Tribes::positionToExplorer!");
} }
@@ -709,23 +613,27 @@ public class Tribes implements InterfaceOptimizer, java.io.Serializable {
return indy; return indy;
} }
/** 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 * @param ea
*/ */
@Override @Override
public void addPopulationChangedEventListener(InterfacePopulationChangedEventListener ea) { public void addPopulationChangedEventListener(InterfacePopulationChangedEventListener ea) {
this.m_Listener = ea; this.m_Listener = ea;
} }
@Override @Override
public boolean removePopulationChangedEventListener( public boolean removePopulationChangedEventListener(
InterfacePopulationChangedEventListener ea) { InterfacePopulationChangedEventListener ea) {
if (m_Listener==ea) { if (m_Listener == ea) {
m_Listener=null; m_Listener = null;
return true; return true;
} else { } else {
return false; return false;
} }
} }
protected void firePropertyChangedEvent(String name) { protected void firePropertyChangedEvent(String name) {
if (this.m_Listener != null) { if (this.m_Listener != null) {
this.m_Listener.registerPopulationStateChanged(this, name); this.m_Listener.registerPopulationStateChanged(this, name);
@@ -736,13 +644,11 @@ public class Tribes implements InterfaceOptimizer, java.io.Serializable {
return (evals % notifyGenChangedEvery) == 0; return (evals % notifyGenChangedEvery) == 0;
} }
@Override
public void freeWilly() {}
@Override @Override
public void setIdentifier(String name) { public void setIdentifier(String name) {
this.m_Identifier = name; this.m_Identifier = name;
} }
@Override @Override
public String getIdentifier() { public String getIdentifier() {
return m_Identifier; return m_Identifier;
@@ -821,7 +727,6 @@ public class Tribes implements InterfaceOptimizer, java.io.Serializable {
// public void setUseAnchor(boolean useAnchor) { // public void setUseAnchor(boolean useAnchor) {
// this.useAnchor = useAnchor; // this.useAnchor = useAnchor;
// } // }
/** /**
* @return the m_Show * @return the m_Show
*/ */

View File

@@ -11,17 +11,14 @@ import eva2.server.go.problems.AbstractMultiObjectiveOptimizationProblem;
import eva2.server.go.problems.FM0Problem; import eva2.server.go.problems.FM0Problem;
import eva2.server.go.problems.InterfaceOptimizationProblem; import eva2.server.go.problems.InterfaceOptimizationProblem;
/** The winged MOEA was a nice idea, which didn't really work out. /**
* Here a standard MOEA is assisted by n additional local searchers, each * The winged MOEA was a nice idea, which didn't really work out. Here a
* optimizing just one objective. The idea was that these local optimizers * standard MOEA is assisted by n additional local searchers, each optimizing
* would span the search space and would allow the MOEA to converge faster. * just one objective. The idea was that these local optimizers would span the
* But in the end the performance of this algorithm strongly depends on the * search space and would allow the MOEA to converge faster. But in the end the
* optimization problem. * performance of this algorithm strongly depends on the optimization problem.
* Created by IntelliJ IDEA. * Created by IntelliJ IDEA. User: streiche Date: 16.02.2005 Time: 16:34:22 To
* User: streiche * change this template use File | Settings | File Templates.
* Date: 16.02.2005
* Time: 16:34:22
* To change this template use File | Settings | File Templates.
*/ */
public class WingedMultiObjectiveEA implements InterfaceOptimizer, java.io.Serializable { public class WingedMultiObjectiveEA implements InterfaceOptimizer, java.io.Serializable {
@@ -40,17 +37,17 @@ public class WingedMultiObjectiveEA implements InterfaceOptimizer, java.io.Seria
} }
public WingedMultiObjectiveEA(WingedMultiObjectiveEA a) { public WingedMultiObjectiveEA(WingedMultiObjectiveEA a) {
this.m_Problem = (InterfaceOptimizationProblem)a.m_Problem.clone(); this.m_Problem = (InterfaceOptimizationProblem) a.m_Problem.clone();
this.m_MOOptimizer = (InterfaceOptimizer)a.m_MOOptimizer.clone(); this.m_MOOptimizer = (InterfaceOptimizer) a.m_MOOptimizer.clone();
this.m_SOOptimizer = (InterfaceOptimizer)a.m_SOOptimizer.clone(); this.m_SOOptimizer = (InterfaceOptimizer) a.m_SOOptimizer.clone();
if (a.m_SOOptimizers != null) { if (a.m_SOOptimizers != null) {
this.m_SOOptimizers = new InterfaceOptimizer[a.m_SOOptimizers.length]; this.m_SOOptimizers = new InterfaceOptimizer[a.m_SOOptimizers.length];
for (int i = 0; i < this.m_SOOptimizers.length; i++) { for (int i = 0; i < this.m_SOOptimizers.length; i++) {
this.m_SOOptimizers[i] = (InterfaceOptimizer)a.m_SOOptimizers[i].clone(); this.m_SOOptimizers[i] = (InterfaceOptimizer) a.m_SOOptimizers[i].clone();
} }
} }
this.m_MigrationRate = a.m_MigrationRate; this.m_MigrationRate = a.m_MigrationRate;
this.m_Population = (Population)a.m_Population.clone(); this.m_Population = (Population) a.m_Population.clone();
} }
@Override @Override
@@ -61,18 +58,18 @@ public class WingedMultiObjectiveEA implements InterfaceOptimizer, java.io.Seria
@Override @Override
public void init() { public void init() {
if (this.m_Problem instanceof AbstractMultiObjectiveOptimizationProblem) { if (this.m_Problem instanceof AbstractMultiObjectiveOptimizationProblem) {
AbstractMultiObjectiveOptimizationProblem tmpProb = (AbstractMultiObjectiveOptimizationProblem)this.m_Problem; AbstractMultiObjectiveOptimizationProblem tmpProb = (AbstractMultiObjectiveOptimizationProblem) this.m_Problem;
AbstractMultiObjectiveOptimizationProblem tmpP; AbstractMultiObjectiveOptimizationProblem tmpP;
MOSOWeightedFitness tmpWF; MOSOWeightedFitness tmpWF;
PropertyDoubleArray tmpDA; PropertyDoubleArray tmpDA;
int dim = this.m_OutputDimension; int dim = this.m_OutputDimension;
double[] weights; double[] weights;
// dim = tmpProb.getOutputDimension(); // dim = tmpProb.getOutputDimension();
this.m_MOOptimizer.setProblem((InterfaceOptimizationProblem)this.m_Problem.clone()); this.m_MOOptimizer.setProblem((InterfaceOptimizationProblem) this.m_Problem.clone());
this.m_MOOptimizer.init(); this.m_MOOptimizer.init();
this.m_SOOptimizers = new InterfaceOptimizer[dim]; this.m_SOOptimizers = new InterfaceOptimizer[dim];
for (int i = 0; i < dim; i++) { for (int i = 0; i < dim; i++) {
tmpP = (AbstractMultiObjectiveOptimizationProblem)this.m_Problem.clone(); tmpP = (AbstractMultiObjectiveOptimizationProblem) this.m_Problem.clone();
weights = new double[dim]; weights = new double[dim];
for (int j = 0; j < dim; j++) { for (int j = 0; j < dim; j++) {
weights[j] = 0; weights[j] = 0;
@@ -82,7 +79,7 @@ public class WingedMultiObjectiveEA implements InterfaceOptimizer, java.io.Seria
tmpWF = new MOSOWeightedFitness(); tmpWF = new MOSOWeightedFitness();
tmpWF.setWeights(tmpDA); tmpWF.setWeights(tmpDA);
tmpP.setMOSOConverter(tmpWF); tmpP.setMOSOConverter(tmpWF);
this.m_SOOptimizers[i] = (InterfaceOptimizer)this.m_SOOptimizer.clone(); this.m_SOOptimizers[i] = (InterfaceOptimizer) this.m_SOOptimizer.clone();
this.m_SOOptimizers[i].setProblem(tmpP); this.m_SOOptimizers[i].setProblem(tmpP);
this.m_SOOptimizers[i].init(); this.m_SOOptimizers[i].init();
} }
@@ -94,26 +91,27 @@ public class WingedMultiObjectiveEA implements InterfaceOptimizer, java.io.Seria
this.firePropertyChangedEvent(Population.nextGenerationPerformed); this.firePropertyChangedEvent(Population.nextGenerationPerformed);
} }
/**
/** 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 pop The initial population
* @param reset If true the population is reset. * @param reset If true the population is reset.
*/ */
@Override @Override
public void initByPopulation(Population pop, boolean reset) { public void initByPopulation(Population pop, boolean reset) {
if (this.m_Problem instanceof AbstractMultiObjectiveOptimizationProblem) { if (this.m_Problem instanceof AbstractMultiObjectiveOptimizationProblem) {
AbstractMultiObjectiveOptimizationProblem tmpProb = (AbstractMultiObjectiveOptimizationProblem)this.m_Problem; AbstractMultiObjectiveOptimizationProblem tmpProb = (AbstractMultiObjectiveOptimizationProblem) this.m_Problem;
AbstractMultiObjectiveOptimizationProblem tmpP; AbstractMultiObjectiveOptimizationProblem tmpP;
MOSOWeightedFitness tmpWF; MOSOWeightedFitness tmpWF;
PropertyDoubleArray tmpDA; PropertyDoubleArray tmpDA;
int dim = 2; int dim = 2;
double[] weights; double[] weights;
// dim = tmpProb.getOutputDimension(); // dim = tmpProb.getOutputDimension();
this.m_MOOptimizer.setProblem((InterfaceOptimizationProblem)this.m_Problem.clone()); this.m_MOOptimizer.setProblem((InterfaceOptimizationProblem) this.m_Problem.clone());
this.m_MOOptimizer.initByPopulation(pop, reset); this.m_MOOptimizer.initByPopulation(pop, reset);
this.m_SOOptimizers = new InterfaceOptimizer[dim]; this.m_SOOptimizers = new InterfaceOptimizer[dim];
for (int i = 0; i < dim; i++) { for (int i = 0; i < dim; i++) {
tmpP = (AbstractMultiObjectiveOptimizationProblem)this.m_Problem.clone(); tmpP = (AbstractMultiObjectiveOptimizationProblem) this.m_Problem.clone();
weights = new double[dim]; weights = new double[dim];
for (int j = 0; j < dim; j++) { for (int j = 0; j < dim; j++) {
weights[j] = 0; weights[j] = 0;
@@ -123,7 +121,7 @@ public class WingedMultiObjectiveEA implements InterfaceOptimizer, java.io.Seria
tmpWF = new MOSOWeightedFitness(); tmpWF = new MOSOWeightedFitness();
tmpWF.setWeights(tmpDA); tmpWF.setWeights(tmpDA);
tmpP.setMOSOConverter(tmpWF); tmpP.setMOSOConverter(tmpWF);
this.m_SOOptimizers[i] = (InterfaceOptimizer)this.m_SOOptimizer.clone(); this.m_SOOptimizers[i] = (InterfaceOptimizer) this.m_SOOptimizer.clone();
this.m_SOOptimizers[i].setProblem(tmpP); this.m_SOOptimizers[i].setProblem(tmpP);
this.m_SOOptimizers[i].initByPopulation(pop, reset); this.m_SOOptimizers[i].initByPopulation(pop, reset);
} }
@@ -135,7 +133,8 @@ public class WingedMultiObjectiveEA implements InterfaceOptimizer, java.io.Seria
this.firePropertyChangedEvent(Population.nextGenerationPerformed); this.firePropertyChangedEvent(Population.nextGenerationPerformed);
} }
/** The optimize method will compute a 'improved' and evaluated population /**
* The optimize method will compute a 'improved' and evaluated population
*/ */
@Override @Override
public void optimize() { public void optimize() {
@@ -154,8 +153,8 @@ public class WingedMultiObjectiveEA implements InterfaceOptimizer, java.io.Seria
this.firePropertyChangedEvent(Population.nextGenerationPerformed); this.firePropertyChangedEvent(Population.nextGenerationPerformed);
} }
/** This method will manage comunication between the /**
* islands * This method will manage comunication between the islands
*/ */
private void communicate() { private void communicate() {
int oldFunctionCalls; int oldFunctionCalls;
@@ -163,11 +162,11 @@ public class WingedMultiObjectiveEA implements InterfaceOptimizer, java.io.Seria
this.m_Population.SetFunctionCalls(0); this.m_Population.SetFunctionCalls(0);
Population pop; Population pop;
// first collect all the data // first collect all the data
pop = (Population)this.m_MOOptimizer.getPopulation().clone(); pop = (Population) this.m_MOOptimizer.getPopulation().clone();
this.m_Population.addPopulation(pop); this.m_Population.addPopulation(pop);
this.m_Population.incrFunctionCallsBy(pop.getFunctionCalls()); this.m_Population.incrFunctionCallsBy(pop.getFunctionCalls());
for (int i = 0; i < this.m_SOOptimizers.length; i++) { for (int i = 0; i < this.m_SOOptimizers.length; i++) {
pop = (Population)this.m_SOOptimizers[i].getPopulation().clone(); pop = (Population) this.m_SOOptimizers[i].getPopulation().clone();
this.m_Population.addPopulation(pop); this.m_Population.addPopulation(pop);
this.m_Population.incrFunctionCallsBy(pop.getFunctionCalls()); this.m_Population.incrFunctionCallsBy(pop.getFunctionCalls());
} }
@@ -180,7 +179,8 @@ public class WingedMultiObjectiveEA implements InterfaceOptimizer, java.io.Seria
this.migrate(); this.migrate();
} }
/** This method implements the migration between the optimzers /**
* This method implements the migration between the optimzers
* *
*/ */
private void migrate() { private void migrate() {
@@ -188,12 +188,12 @@ public class WingedMultiObjectiveEA implements InterfaceOptimizer, java.io.Seria
double tmpF1, tmpF2; double tmpF1, tmpF2;
// for each dimension find the best // for each dimension find the best
for (int i = 0; i < this.m_OutputDimension; i++) { for (int i = 0; i < this.m_OutputDimension; i++) {
bestIndys[i] = (AbstractEAIndividual)((AbstractEAIndividual)this.m_Population.get(0)).clone(); bestIndys[i] = (AbstractEAIndividual) ((AbstractEAIndividual) this.m_Population.get(0)).clone();
tmpF1 = bestIndys[i].getFitness(i); tmpF1 = bestIndys[i].getFitness(i);
// for each individual find the best // for each individual find the best
for (int j = 0; j < this.m_Population.size(); j++) { for (int j = 0; j < this.m_Population.size(); j++) {
if (((AbstractEAIndividual)this.m_Population.get(j)).getFitness(i) < tmpF1) { if (((AbstractEAIndividual) this.m_Population.get(j)).getFitness(i) < tmpF1) {
bestIndys[i] = (AbstractEAIndividual)((AbstractEAIndividual)this.m_Population.get(j)).clone(); bestIndys[i] = (AbstractEAIndividual) ((AbstractEAIndividual) this.m_Population.get(j)).clone();
tmpF1 = bestIndys[i].getFitness(i); tmpF1 = bestIndys[i].getFitness(i);
} }
} }
@@ -201,54 +201,64 @@ public class WingedMultiObjectiveEA implements InterfaceOptimizer, java.io.Seria
// now perform the migration // now perform the migration
AbstractEAIndividual tmpIndy; AbstractEAIndividual tmpIndy;
for (int i = 0; i < this.m_OutputDimension; i++) { for (int i = 0; i < this.m_OutputDimension; i++) {
tmpIndy = (AbstractEAIndividual)bestIndys[i].clone(); tmpIndy = (AbstractEAIndividual) bestIndys[i].clone();
this.m_MOOptimizer.getProblem().evaluate(tmpIndy); this.m_MOOptimizer.getProblem().evaluate(tmpIndy);
this.m_MOOptimizer.getPopulation().set(i, tmpIndy); this.m_MOOptimizer.getPopulation().set(i, tmpIndy);
tmpIndy = (AbstractEAIndividual)bestIndys[i].clone(); tmpIndy = (AbstractEAIndividual) bestIndys[i].clone();
this.m_SOOptimizers[i].getProblem().evaluate(tmpIndy); this.m_SOOptimizers[i].getProblem().evaluate(tmpIndy);
this.m_SOOptimizers[i].getPopulation().set(0, bestIndys[i]); this.m_SOOptimizers[i].getPopulation().set(0, bestIndys[i]);
} }
} }
/** 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 * @param ea
*/ */
@Override @Override
public void addPopulationChangedEventListener(InterfacePopulationChangedEventListener ea) { public void addPopulationChangedEventListener(InterfacePopulationChangedEventListener ea) {
this.m_Listener = ea; this.m_Listener = ea;
} }
@Override @Override
public boolean removePopulationChangedEventListener( public boolean removePopulationChangedEventListener(
InterfacePopulationChangedEventListener ea) { InterfacePopulationChangedEventListener ea) {
if (m_Listener==ea) { if (m_Listener == ea) {
m_Listener=null; m_Listener = null;
return true; return true;
} else { } else {
return false; return false;
} }
} }
/** Something has changed
/**
* Something has changed
*/ */
protected void firePropertyChangedEvent (String name) { protected void firePropertyChangedEvent(String name) {
if (this.m_Listener != null) { if (this.m_Listener != null) {
this.m_Listener.registerPopulationStateChanged(this, name); this.m_Listener.registerPopulationStateChanged(this, name);
} }
} }
/** This method will set the problem that is to be optimized /**
* This method will set the problem that is to be optimized
*
* @param problem * @param problem
*/ */
@Override @Override
public void setProblem (InterfaceOptimizationProblem problem) { public void setProblem(InterfaceOptimizationProblem problem) {
this.m_Problem = problem; this.m_Problem = problem;
} }
@Override @Override
public InterfaceOptimizationProblem getProblem () { public InterfaceOptimizationProblem getProblem() {
return this.m_Problem; return this.m_Problem;
} }
/** This method will return a string describing all properties of the optimizer /**
* and the applied methods. * This method will return a string describing all properties of the
* optimizer and the applied methods.
*
* @return A descriptive string * @return A descriptive string
*/ */
@Override @Override
@@ -256,39 +266,42 @@ public class WingedMultiObjectiveEA implements InterfaceOptimizer, java.io.Seria
String result = ""; String result = "";
result += "EMO:\n"; result += "EMO:\n";
result += "Optimization Problem: "; result += "Optimization Problem: ";
result += this.m_Problem.getStringRepresentationForProblem(this) +"\n"; result += this.m_Problem.getStringRepresentationForProblem(this) + "\n";
result += this.m_Population.getStringRepresentation(); result += this.m_Population.getStringRepresentation();
return result; return result;
} }
/** 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 * @param name The indenifier
*/ */
@Override @Override
public void setIdentifier(String name) { public void setIdentifier(String name) {
this.m_Identifier = name; this.m_Identifier = name;
} }
@Override @Override
public String getIdentifier() { public String getIdentifier() {
return this.m_Identifier; return this.m_Identifier;
} }
/** This method is required to free the memory on a RMIServer, /**
* but there is nothing to implement. * ********************************************************************************************************************
*/
@Override
public void freeWilly() {
}
/**********************************************************************************************************************
* These are for GUI * These are for GUI
*/ */
/** This method returns a global info string /**
* This method returns a global info string
*
* @return description * @return description
*/ */
public static String globalInfo() { public static String globalInfo() {
return "This is Evolutionary Multi-Criteria Optimization Algorithm hybridized with Local Searchers to span the Pareto-Front."; return "This is Evolutionary Multi-Criteria Optimization Algorithm hybridized with Local Searchers to span the Pareto-Front.";
} }
/** This method will return a naming String
/**
* This method will return a naming String
*
* @return The name of the algorithm * @return The name of the algorithm
*/ */
@Override @Override
@@ -296,19 +309,23 @@ public class WingedMultiObjectiveEA implements InterfaceOptimizer, java.io.Seria
return "EMO-LS"; return "EMO-LS";
} }
/** Assuming that all optimizer will store their data in a population /**
* we will allow access to this population to query to current state * Assuming that all optimizer will store their data in a population we will
* of the optimizer. * allow access to this population to query to current state of the
* optimizer.
*
* @return The population of current solutions to a given problem. * @return The population of current solutions to a given problem.
*/ */
@Override @Override
public Population getPopulation() { public Population getPopulation() {
return this.m_Population; return this.m_Population;
} }
@Override @Override
public void setPopulation(Population pop){ public void setPopulation(Population pop) {
this.m_Population = pop; this.m_Population = pop;
} }
public String populationTipText() { public String populationTipText() {
return "(Defunct)"; return "(Defunct)";
} }
@@ -317,41 +334,54 @@ public class WingedMultiObjectiveEA implements InterfaceOptimizer, java.io.Seria
public InterfaceSolutionSet getAllSolutions() { public InterfaceSolutionSet getAllSolutions() {
return new SolutionSet(getPopulation()); return new SolutionSet(getPopulation());
} }
/** This method allows you to set/get the optimizing technique to use.
/**
* This method allows you to set/get the optimizing technique to use.
*
* @return The current optimizing method * @return The current optimizing method
*/ */
public InterfaceOptimizer getMOOptimizer() { public InterfaceOptimizer getMOOptimizer() {
return this.m_MOOptimizer; return this.m_MOOptimizer;
} }
public void setMOOptimizer(InterfaceOptimizer b){
public void setMOOptimizer(InterfaceOptimizer b) {
this.m_MOOptimizer = b; this.m_MOOptimizer = b;
} }
public String mOOptimizerTipText() { public String mOOptimizerTipText() {
return "Choose a population based optimizing technique to use."; return "Choose a population based optimizing technique to use.";
} }
/** This method allows you to set/get the optimizing technique to use. /**
* This method allows you to set/get the optimizing technique to use.
*
* @return The current optimizing method * @return The current optimizing method
*/ */
public InterfaceOptimizer getSOOptimizer() { public InterfaceOptimizer getSOOptimizer() {
return this.m_SOOptimizer; return this.m_SOOptimizer;
} }
public void setSOOptimizer(InterfaceOptimizer b){
public void setSOOptimizer(InterfaceOptimizer b) {
this.m_SOOptimizer = b; this.m_SOOptimizer = b;
} }
public String sOOptimizerTipText() { public String sOOptimizerTipText() {
return "Choose a population based optimizing technique to use."; return "Choose a population based optimizing technique to use.";
} }
/** This method allows you to set/get the archiving strategy to use. /**
* This method allows you to set/get the archiving strategy to use.
*
* @return The current optimizing method * @return The current optimizing method
*/ */
public int getMigrationRate() { public int getMigrationRate() {
return this.m_MigrationRate; return this.m_MigrationRate;
} }
public void setMigrationRate(int b){
public void setMigrationRate(int b) {
this.m_MigrationRate = b; this.m_MigrationRate = b;
} }
public String migrationRateTipText() { public String migrationRateTipText() {
return "Choose a proper migration rate."; return "Choose a proper migration rate.";
} }