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);
} }

File diff suppressed because it is too large Load Diff

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.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,50 +14,49 @@ 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 *
* @version: $Revision: 307 $ * @author Felix Streichert
* $Date: 2007-12-04 14:31:47 +0100 (Tue, 04 Dec 2007) $ * @version: $Revision: 307 $ $Date: 2007-12-04 14:31:47 +0100 (Tue, 04 Dec
* $Author: mkron $ * 2007) $ $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;
private int m_DifferenceThreshold; private int m_DifferenceThreshold;
private double m_DivergenceRate = 0.35; private double m_DivergenceRate = 0.35;
private boolean m_UseElitism = true; private boolean m_UseElitism = true;
private int m_NumberOfPartners = 1; private int m_NumberOfPartners = 1;
private Population m_Population = new Population(); private Population m_Population = new Population();
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;
public CHCAdaptiveSearchAlgorithm() { public CHCAdaptiveSearchAlgorithm() {
} }
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,31 +78,34 @@ 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 /**
* @param pop The initial population * This method will init the optimizer with a given population
* @param reset If true the population is reset. *
* @param pop The initial population
* @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!");
} }
if (reset) { if (reset) {
this.evaluatePopulation(this.m_Population); this.evaluatePopulation(this.m_Population);
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) {
@@ -112,29 +113,30 @@ 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;
AbstractEAIndividual[] offSprings; AbstractEAIndividual[] offSprings;
AbstractEAIndividual tmpIndy; AbstractEAIndividual tmpIndy;
result.clear(); result.clear();
// this.m_NormationOperator.computeSelectionProbability(this.m_Population, "Fitness"); // this.m_NormationOperator.computeSelectionProbability(this.m_Population, "Fitness");
//System.out.println("Population:"+this.m_Population.getSolutionRepresentationFor()); //System.out.println("Population:"+this.m_Population.getSolutionRepresentationFor());
this.m_PopulSelectionOperator.prepareSelection(this.m_Population); this.m_PopulSelectionOperator.prepareSelection(this.m_Population);
this.m_RecombSelectionOperator.prepareSelection(this.m_Population); this.m_RecombSelectionOperator.prepareSelection(this.m_Population);
parents = this.m_PopulSelectionOperator.selectFrom(this.m_Population, this.m_Population.getTargetSize()); parents = this.m_PopulSelectionOperator.selectFrom(this.m_Population, this.m_Population.getTargetSize());
//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,20 +151,22 @@ 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
*/ */
private int computeHammingDistance(AbstractEAIndividual dad, Population partners) { private int computeHammingDistance(AbstractEAIndividual dad, Population partners) {
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,25 +176,26 @@ 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();
InterfaceGAIndividual mutant; InterfaceGAIndividual mutant;
BitSet tmpBitSet; BitSet tmpBitSet;
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
public boolean removePopulationChangedEventListener(
InterfacePopulationChangedEventListener ea) {
if (m_Listener==ea) {
m_Listener=null;
return true;
} else {
return false;
}
}
/** Something has changed @Override
public boolean removePopulationChangedEventListener(
InterfacePopulationChangedEventListener ea) {
if (m_Listener == ea) {
m_Listener = null;
return true;
} else {
return false;
}
}
/**
* Something has changed
*/ */
protected void firePropertyChangedEvent (String name) { 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 /**
* @param name The indenifier * This method allows you to set an identifier for the algorithm
*
* @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
public String getIdentifier() {
return this.m_Identifier;
}
/** This method is required to free the memory on a RMIServer,
* but there is nothing to implement.
*/
@Override @Override
public void freeWilly() { public String getIdentifier() {
return this.m_Identifier;
} }
/********************************************************************************************************************** /**
* 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,26 +332,30 @@ 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.";
} }
@Override @Override
public InterfaceSolutionSet getAllSolutions() { public InterfaceSolutionSet getAllSolutions() {
return new SolutionSet(getPopulation()); return new SolutionSet(getPopulation());
} }
// /** This method will set the normation method that is to be used. // /** This method will set the normation method that is to be 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,287 +16,303 @@ 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(); private InterfaceOptimizationProblem m_Problem = new F1Problem();
private InterfaceOptimizationProblem m_Problem = new F1Problem(); private int hcEvalCycle = 1000;
private int hcEvalCycle = 1000; private int initialPopSize = 100;
private int initialPopSize = 100; private int loopCnt = 0;
private int loopCnt = 0;
// private int baseEvalCnt = 0; // private int baseEvalCnt = 0;
private int notifyGuiEvery = 50; private int notifyGuiEvery = 50;
private double sigmaClust = 0.01; private double sigmaClust = 0.01;
private double minImprovement = 0.000001; private double minImprovement = 0.000001;
private double stepSizeThreshold = 0.000001; private double stepSizeThreshold = 0.000001;
private double initialStepSize = 0.1; private double initialStepSize = 0.1;
// reduce the step size when there is hardy improvement. // reduce the step size when there is hardy improvement.
private double reduceFactor = 0.2; private double reduceFactor = 0.2;
private MutateESFixedStepSize mutator = new MutateESFixedStepSize(0.1); private MutateESFixedStepSize mutator = new MutateESFixedStepSize(0.1);
private PostProcessMethod localSearchMethod = PostProcessMethod.nelderMead; private PostProcessMethod localSearchMethod = PostProcessMethod.nelderMead;
private boolean doReinitialization = true; private boolean doReinitialization = true;
public ClusteringHillClimbing() { public ClusteringHillClimbing() {
hideHideable(); hideHideable();
} }
public ClusteringHillClimbing(int initialPopSize, PostProcessMethod lsMethod) { public ClusteringHillClimbing(int initialPopSize, PostProcessMethod lsMethod) {
this(); this();
setInitialPopSize(initialPopSize); setInitialPopSize(initialPopSize);
setLocalSearchMethod(lsMethod); setLocalSearchMethod(lsMethod);
} }
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;
notifyGuiEvery = other.notifyGuiEvery; notifyGuiEvery = other.notifyGuiEvery;
sigmaClust = other.sigmaClust; sigmaClust = other.sigmaClust;
minImprovement = other.minImprovement; minImprovement = other.minImprovement;
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;
} }
@Override @Override
public Object clone() { public Object clone() {
return (Object) new ClusteringHillClimbing(this); return (Object) new ClusteringHillClimbing(this);
} }
/** /**
* Hide the population. * Hide the population.
*/ */
public void hideHideable() { public void hideHideable() {
GenericObjectEditor.setHideProperty(getClass(), "population", true); GenericObjectEditor.setHideProperty(getClass(), "population", true);
setDoReinitialization(isDoReinitialization()); setDoReinitialization(isDoReinitialization());
setLocalSearchMethod(getLocalSearchMethod()); setLocalSearchMethod(getLocalSearchMethod());
} }
@Override @Override
public void setIdentifier(String name) { public void setIdentifier(String name) {
this.m_Identifier = name; this.m_Identifier = name;
} }
@Override
public String getIdentifier() {
return this.m_Identifier;
}
/** This method will set the problem that is to be optimized
* @param problem
*/
@Override @Override
public void setProblem (InterfaceOptimizationProblem problem) { public String getIdentifier() {
this.m_Problem = problem; return this.m_Identifier;
} }
/**
* This method will set the problem that is to be optimized
*
* @param problem
*/
@Override @Override
public InterfaceOptimizationProblem getProblem () { public void setProblem(InterfaceOptimizationProblem problem) {
return this.m_Problem; this.m_Problem = problem;
} }
@Override
public InterfaceOptimizationProblem getProblem() {
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;
} }
} }
@Override @Override
public void init() { public void init() {
loopCnt = 0; loopCnt = 0;
mutator = new MutateESFixedStepSize(initialStepSize); mutator = new MutateESFixedStepSize(initialStepSize);
archive = new Population(); archive = new Population();
hideHideable(); hideHideable();
m_Population.setTargetSize(initialPopSize); m_Population.setTargetSize(initialPopSize);
this.m_Problem.initPopulation(this.m_Population); this.m_Problem.initPopulation(this.m_Population);
m_Population.addPopulationChangedEventListener(null); // noone will be notified directly on pop changes m_Population.addPopulationChangedEventListener(null); // noone will be notified directly on pop changes
this.m_Problem.evaluate(this.m_Population); this.m_Problem.evaluate(this.m_Population);
this.firePropertyChangedEvent(Population.nextGenerationPerformed); this.firePropertyChangedEvent(Population.nextGenerationPerformed);
} }
/** This method will init the optimizer with a given population /**
* @param pop The initial population * This method will init the optimizer with a given population
* @param reset If true the population is reset. *
* @param pop The initial population
* @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();
this.m_Problem.evaluate(this.m_Population); this.m_Problem.evaluate(this.m_Population);
this.firePropertyChangedEvent(Population.nextGenerationPerformed); this.firePropertyChangedEvent(Population.nextGenerationPerformed);
} }
} }
/** 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);
} }
} }
@Override @Override
public void optimize() { public void optimize() {
double improvement; double improvement;
loopCnt++; loopCnt++;
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 {
evalsNow = hcEvalCycle;
}
do {
if (TRACE) {
System.out.println("evalCycle: " + hcEvalCycle + ", evals now: " + evalsNow);
} }
else { popD = PostProcess.clusterLocalSearch(localSearchMethod, m_Population, (AbstractOptimizationProblem) m_Problem, sigmaClust, evalsNow, 0.5, mutator);
evalsNow = hcEvalCycle; // (m_Population, (AbstractOptimizationProblem)m_Problem, sigmaClust, hcEvalCycle - (m_Population.getFunctionCalls() % hcEvalCycle), 0.5);
if (popD.head().getFunctionCalls() == funCallsBefore) {
System.err.println("Bad case, increasing allowed evaluations!");
evalsNow = Math.max(evalsNow++, (int) (evalsNow * 1.2));
} }
do { } while (popD.head().getFunctionCalls() == funCallsBefore);
if (TRACE) { improvement = popD.tail();
System.out.println("evalCycle: " + hcEvalCycle + ", evals now: " + evalsNow); m_Population = popD.head();
} if (TRACE) {
popD = PostProcess.clusterLocalSearch(localSearchMethod, m_Population, (AbstractOptimizationProblem)m_Problem, sigmaClust, evalsNow, 0.5, mutator); System.out.println("num inds after clusterLS: " + m_Population.size());
// (m_Population, (AbstractOptimizationProblem)m_Problem, sigmaClust, hcEvalCycle - (m_Population.getFunctionCalls() % hcEvalCycle), 0.5); }
if (popD.head().getFunctionCalls()==funCallsBefore) {
System.err.println("Bad case, increasing allowed evaluations!"); popD.head().setGenerationTo(m_Population.getGeneration() + 1);
evalsNow=Math.max(evalsNow++, (int)(evalsNow*1.2));
} if (doReinitialization && (improvement < minImprovement)) {
} while (popD.head().getFunctionCalls()==funCallsBefore); if (TRACE) {
improvement = popD.tail(); System.out.println("improvement below " + minImprovement);
m_Population = popD.head();
if (TRACE) {
System.out.println("num inds after clusterLS: " + m_Population.size());
} }
if ((localSearchMethod != PostProcessMethod.hillClimber) || (mutator.getSigma() < stepSizeThreshold)) { // reinit!
// is performed for nm and cma, and if hc has too low sigma
if (TRACE) {
System.out.println("REINIT!!");
}
popD.head().setGenerationTo(m_Population.getGeneration()+1); if (localSearchMethod == PostProcessMethod.hillClimber) {
mutator.setSigma(initialStepSize);
}
if (doReinitialization && (improvement < minImprovement)) { // store results
if (TRACE) { archive.SetFunctionCalls(m_Population.getFunctionCalls());
System.out.println("improvement below " + minImprovement); archive.addPopulation(m_Population);
}
if ((localSearchMethod != PostProcessMethod.hillClimber) || (mutator.getSigma() < stepSizeThreshold)) { // reinit!
// is performed for nm and cma, and if hc has too low sigma
if (TRACE) {
System.out.println("REINIT!!");
}
if (localSearchMethod == PostProcessMethod.hillClimber) { Population tmpPop = new Population();
mutator.setSigma(initialStepSize); tmpPop.addPopulationChangedEventListener(null);
} tmpPop.setTargetSize(initialPopSize);
this.m_Problem.initPopulation(tmpPop);
tmpPop.setSameParams(m_Population);
tmpPop.setTargetSize(initialPopSize);
this.m_Problem.evaluate(tmpPop);
// store results // reset population while keeping function calls etc.
archive.SetFunctionCalls(m_Population.getFunctionCalls()); m_Population.clear();
archive.addPopulation(m_Population); m_Population.addPopulation(tmpPop);
m_Population.incrFunctionCallsBy(tmpPop.size());
Population tmpPop = new Population(); } else { // decrease step size for hc
tmpPop.addPopulationChangedEventListener(null); if (localSearchMethod != PostProcessMethod.hillClimber) {
tmpPop.setTargetSize(initialPopSize); System.err.println("Invalid case in ClusteringHillClimbing!");
this.m_Problem.initPopulation(tmpPop); }
tmpPop.setSameParams(m_Population); mutator.setSigma(mutator.getSigma() * reduceFactor);
tmpPop.setTargetSize(initialPopSize); if (TRACE) {
this.m_Problem.evaluate(tmpPop); System.out.println("mutation stepsize reduced to " + mutator.getSigma());
}
// reset population while keeping function calls etc. }
m_Population.clear(); }
m_Population.addPopulation(tmpPop);
m_Population.incrFunctionCallsBy(tmpPop.size());
} else { // decrease step size for hc
if (localSearchMethod != PostProcessMethod.hillClimber) {
System.err.println("Invalid case in ClusteringHillClimbing!");
}
mutator.setSigma(mutator.getSigma()*reduceFactor);
if (TRACE) {
System.out.println("mutation stepsize reduced to " + mutator.getSigma());
}
}
}
// System.out.println("funcalls: " + evalCnt); // System.out.println("funcalls: " + evalCnt);
this.firePropertyChangedEvent(Population.nextGenerationPerformed); this.firePropertyChangedEvent(Population.nextGenerationPerformed);
} }
@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
if (name.compareTo(Population.funCallIntervalReached) == 0) { if (name.compareTo(Population.funCallIntervalReached) == 0) {
// if ((((Population)source).size() % 50) > 0) { // if ((((Population)source).size() % 50) > 0) {
// 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);
} }
// do not react to NextGenerationPerformed // do not react to NextGenerationPerformed
//else System.err.println("ERROR, event was " + name); //else System.err.println("ERROR, event was " + name);
} }
/** Assuming that all optimizer will store thier data in a population /**
* we will allow acess to this population to query to current state * 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).";
} }
@Override @Override
public InterfaceSolutionSet getAllSolutions() { public InterfaceSolutionSet getAllSolutions() {
Population tmp = new Population(); Population tmp = new Population();
tmp.addPopulation(archive); tmp.addPopulation(archive);
tmp.addPopulation(m_Population); tmp.addPopulation(m_Population);
tmp.SetFunctionCalls(m_Population.getFunctionCalls()); tmp.SetFunctionCalls(m_Population.getFunctionCalls());
tmp.setGenerationTo(m_Population.getGeneration()); tmp.setGenerationTo(m_Population.getGeneration());
// tmp = PostProcessInterim.clusterBest(tmp, sigma, 0, PostProcessInterim.KEEP_LONERS, PostProcessInterim.BEST_ONLY); // tmp = PostProcessInterim.clusterBest(tmp, sigma, 0, PostProcessInterim.KEEP_LONERS, PostProcessInterim.BEST_ONLY);
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
@@ -311,183 +327,180 @@ InterfaceOptimizer, Serializable, InterfaceAdditionalPopulationInformer {
} }
@Override @Override
public void freeWilly() {} public String getName() {
return "ClustHC-" + initialPopSize + "-" + localSearchMethod;
}
public static String globalInfo() {
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.";
}
/**
* @return the hcEvalCycle
*/
public int getEvalCycle() {
return hcEvalCycle;
}
/**
* @param hcEvalCycle the hcEvalCycle to set
*/
public void setEvalCycle(int hcEvalCycle) {
this.hcEvalCycle = hcEvalCycle;
}
public String evalCycleTipText() {
return "The number of evaluations between two clustering/adaption steps.";
}
/**
* @return the initialPopSize
*/
public int getInitialPopSize() {
return initialPopSize;
}
/**
* @param initialPopSize the initialPopSize to set
*/
public void setInitialPopSize(int initialPopSize) {
this.initialPopSize = initialPopSize;
}
public String initialPopSizeTipText() {
return "Population size at the start and at reinitialization times.";
}
/**
* @return the sigma
*/
public double getSigmaClust() {
return sigmaClust;
}
/**
* @param sigma the sigma to set
*/
public void setSigmaClust(double sigma) {
this.sigmaClust = sigma;
}
public String sigmaClustTipText() {
return "Defines the sigma distance parameter for density based clustering.";
}
/**
* @return the notifyGuiEvery
*/
public int getNotifyGuiEvery() {
return notifyGuiEvery;
}
/**
* @param notifyGuiEvery the notifyGuiEvery to set
*/
public void setNotifyGuiEvery(int notifyGuiEvery) {
this.notifyGuiEvery = notifyGuiEvery;
}
public String notifyGuiEveryTipText() {
return "How often to notify the GUI to plot the fitness etc.";
}
/**
* @return the minImprovement
*/
public double getMinImprovement() {
return minImprovement;
}
/**
* @param minImprovement the minImprovement to set
*/
public void setMinImprovement(double minImprovement) {
this.minImprovement = minImprovement;
}
public String minImprovementTipText() {
return "Improvement threshold below which the mutation step size is reduced or the population reinitialized.";
}
/**
* @return the reinitForStepSize
*/
public double getStepSizeThreshold() {
return stepSizeThreshold;
}
/**
* @param reinitForStepSize the reinitForStepSize to set
*/
public void setStepSizeThreshold(double reinitForStepSize) {
this.stepSizeThreshold = reinitForStepSize;
}
public String stepSizeThresholdTipText() {
return "Threshold for the mutation step size below which the population is seen as converged and reinitialized.";
}
/**
* @return the initialStepSize
*/
public double getStepSizeInitial() {
return initialStepSize;
}
/**
* @param initialStepSize the initialStepSize to set
*/
public void setStepSizeInitial(double initialStepSize) {
this.initialStepSize = initialStepSize;
}
public String stepSizeInitialTipText() {
return "Initial mutation step size for hill climbing, relative to the problem range.";
}
public PostProcessMethod getLocalSearchMethod() {
return localSearchMethod;
}
public void setLocalSearchMethod(PostProcessMethod localSearchMethod) {
this.localSearchMethod = localSearchMethod;
GenericObjectEditor.setShowProperty(this.getClass(), "stepSizeInitial", localSearchMethod == PostProcessMethod.hillClimber);
GenericObjectEditor.setShowProperty(this.getClass(), "stepSizeThreshold", localSearchMethod == PostProcessMethod.hillClimber);
}
public String localSearchMethodTipText() {
return "Set the method to be used for the hill climbing as local search";
}
@Override @Override
public String getName() { public String[] getAdditionalDataHeader() {
return "ClustHC-"+initialPopSize+"-"+localSearchMethod; return new String[]{"numIndies", "sigma", "numArchived", "archivedMeanDist"};
} }
public static String globalInfo() {
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.";
}
/**
* @return the hcEvalCycle
*/
public int getEvalCycle() {
return hcEvalCycle;
}
/**
* @param hcEvalCycle the hcEvalCycle to set
*/
public void setEvalCycle(int hcEvalCycle) {
this.hcEvalCycle = hcEvalCycle;
}
public String evalCycleTipText() {
return "The number of evaluations between two clustering/adaption steps.";
}
/**
* @return the initialPopSize
*/
public int getInitialPopSize() {
return initialPopSize;
}
/**
* @param initialPopSize the initialPopSize to set
*/
public void setInitialPopSize(int initialPopSize) {
this.initialPopSize = initialPopSize;
}
public String initialPopSizeTipText() {
return "Population size at the start and at reinitialization times.";
}
/**
* @return the sigma
*/
public double getSigmaClust() {
return sigmaClust;
}
/**
* @param sigma the sigma to set
*/
public void setSigmaClust(double sigma) {
this.sigmaClust = sigma;
}
public String sigmaClustTipText() {
return "Defines the sigma distance parameter for density based clustering.";
}
/**
* @return the notifyGuiEvery
*/
public int getNotifyGuiEvery() {
return notifyGuiEvery;
}
/**
* @param notifyGuiEvery the notifyGuiEvery to set
*/
public void setNotifyGuiEvery(int notifyGuiEvery) {
this.notifyGuiEvery = notifyGuiEvery;
}
public String notifyGuiEveryTipText() {
return "How often to notify the GUI to plot the fitness etc.";
}
/**
* @return the minImprovement
*/
public double getMinImprovement() {
return minImprovement;
}
/**
* @param minImprovement the minImprovement to set
*/
public void setMinImprovement(double minImprovement) {
this.minImprovement = minImprovement;
}
public String minImprovementTipText() {
return "Improvement threshold below which the mutation step size is reduced or the population reinitialized.";
}
/**
* @return the reinitForStepSize
*/
public double getStepSizeThreshold() {
return stepSizeThreshold;
}
/**
* @param reinitForStepSize the reinitForStepSize to set
*/
public void setStepSizeThreshold(double reinitForStepSize) {
this.stepSizeThreshold = reinitForStepSize;
}
public String stepSizeThresholdTipText() {
return "Threshold for the mutation step size below which the population is seen as converged and reinitialized.";
}
/**
* @return the initialStepSize
*/
public double getStepSizeInitial() {
return initialStepSize;
}
/**
* @param initialStepSize the initialStepSize to set
*/
public void setStepSizeInitial(double initialStepSize) {
this.initialStepSize = initialStepSize;
}
public String stepSizeInitialTipText() {
return "Initial mutation step size for hill climbing, relative to the problem range.";
}
public PostProcessMethod getLocalSearchMethod() {
return localSearchMethod;
}
public void setLocalSearchMethod(PostProcessMethod localSearchMethod) {
this.localSearchMethod = localSearchMethod;
GenericObjectEditor.setShowProperty(this.getClass(), "stepSizeInitial", localSearchMethod==PostProcessMethod.hillClimber);
GenericObjectEditor.setShowProperty(this.getClass(), "stepSizeThreshold", localSearchMethod==PostProcessMethod.hillClimber);
}
public String localSearchMethodTipText() {
return "Set the method to be used for the hill climbing as local search";
}
@Override @Override
public String[] getAdditionalDataHeader() { public String[] getAdditionalDataInfo() {
return new String[]{"numIndies", "sigma", "numArchived", "archivedMeanDist"}; return new String[]{"The current population size", "Current step size in case of stochastic HC", "Number of archived solutions", "Mean distance of archived solutions"};
} }
@Override @Override
public String[] getAdditionalDataInfo() { public Object[] getAdditionalDataValue(PopulationInterface pop) {
return new String[]{"The current population size", "Current step size in case of stochastic HC", "Number of archived solutions", "Mean distance of archived solutions"}; return new Object[]{m_Population.size(), mutator.getSigma(), archive.size(), archive.getPopulationMeasures()[0]};
} }
@Override public boolean isDoReinitialization() {
public Object[] getAdditionalDataValue(PopulationInterface pop) { return doReinitialization;
return new Object[]{m_Population.size(), mutator.getSigma(), archive.size(), archive.getPopulationMeasures()[0]}; }
}
public boolean isDoReinitialization() { public void setDoReinitialization(boolean doReinitialization) {
return doReinitialization; this.doReinitialization = doReinitialization;
} GenericObjectEditor.setShowProperty(this.getClass(), "minImprovement", doReinitialization);
}
public void setDoReinitialization(boolean doReinitialization) { public String doReinitializationTipText() {
this.doReinitialization = doReinitialization; return "Activate reinitialization if no improvement was achieved.";
GenericObjectEditor.setShowProperty(this.getClass(), "minImprovement", doReinitialization); }
}
public String doReinitializationTipText() {
return "Activate reinitialization if no improvement was achieved.";
}
} }

File diff suppressed because it is too large Load Diff

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,37 +10,36 @@ 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 * Copyright: Copyright (c) 2003 Company: University of Tuebingen, Computer
* Company: University of Tuebingen, Computer Architecture * Architecture
* @author Felix Streichert *
* @version: $Revision: 307 $ * @author Felix Streichert
* $Date: 2007-12-04 14:31:47 +0100 (Tue, 04 Dec 2007) $ * @version: $Revision: 307 $ $Date: 2007-12-04 14:31:47 +0100 (Tue, 04 Dec
* $Author: mkron $ * 2007) $ $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;
public EvolutionaryProgramming() { public EvolutionaryProgramming() {
} }
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
@@ -49,109 +48,123 @@ public class EvolutionaryProgramming implements InterfaceOptimizer, java.io.Seri
} }
@Override @Override
public void init() { public void init() {
this.m_Problem.initPopulation(this.m_Population); this.m_Problem.initPopulation(this.m_Population);
this.evaluatePopulation(this.m_Population);
this.m_PopulationSize = this.m_Population.size();
this.firePropertyChangedEvent(Population.nextGenerationPerformed);
}
/**
* This method will init the optimizer with a given population
*
* @param reset If true the population is reset.
*/
@Override
public void initByPopulation(Population pop, boolean reset) {
this.m_Population = (Population) pop.clone();
if (reset) {
this.m_Population.init();
this.evaluatePopulation(this.m_Population); this.evaluatePopulation(this.m_Population);
this.m_PopulationSize = this.m_Population.size();
this.firePropertyChangedEvent(Population.nextGenerationPerformed); this.firePropertyChangedEvent(Population.nextGenerationPerformed);
} }
}
/** This method will init the optimizer with a given population /**
* @param reset If true the population is reset. * This method will evaluate the current population using the given problem.
*/ *
@Override * @param population The population that is to be evaluated
public void initByPopulation(Population pop, boolean reset) { */
this.m_Population = (Population)pop.clone(); private void evaluatePopulation(Population population) {
if (reset) { this.m_Problem.evaluate(population);
this.m_Population.init(); population.incrGeneration();
this.evaluatePopulation(this.m_Population); }
this.firePropertyChangedEvent(Population.nextGenerationPerformed);
} /**
} * This method will generate the offspring population from the given
* population of evaluated individuals.
/** This method will evaluate the current population using the */
* given problem. private Population generateChildren() {
* @param population The population that is to be evaluated Population result = (Population) this.m_Population.cloneWithoutInds();
*/ AbstractEAIndividual mutant;
private void evaluatePopulation(Population population) {
this.m_Problem.evaluate(population); result.clear();
population.incrGeneration(); for (int i = 0; i < this.m_Population.size(); i++) {
} mutant = (AbstractEAIndividual) ((AbstractEAIndividual) this.m_Population.get(i)).clone();
double tmpD = mutant.getMutationProbability();
/** This method will generate the offspring population from the mutant.setMutationProbability(1.0);
* given population of evaluated individuals. mutant.mutate();
*/ mutant.setMutationProbability(tmpD);
private Population generateChildren() { result.add(mutant);
Population result = (Population)this.m_Population.cloneWithoutInds();
AbstractEAIndividual mutant;
result.clear();
for (int i = 0; i < this.m_Population.size(); i++) {
mutant = (AbstractEAIndividual)((AbstractEAIndividual)this.m_Population.get(i)).clone();
double tmpD = mutant.getMutationProbability();
mutant.setMutationProbability(1.0);
mutant.mutate();
mutant.setMutationProbability(tmpD);
result.add(mutant);
}
return result;
} }
return result;
}
@Override @Override
public void optimize() { public void optimize() {
Population nextGeneration, parents; Population nextGeneration, parents;
this.m_EnvironmentSelection.prepareSelection(this.m_Population); this.m_EnvironmentSelection.prepareSelection(this.m_Population);
parents = this.m_EnvironmentSelection.selectFrom(this.m_Population, this.m_PopulationSize); parents = this.m_EnvironmentSelection.selectFrom(this.m_Population, this.m_PopulationSize);
this.m_Population.clear(); this.m_Population.clear();
this.m_Population.addPopulation(parents); this.m_Population.addPopulation(parents);
nextGeneration = this.generateChildren(); nextGeneration = this.generateChildren();
this.evaluatePopulation(nextGeneration); this.evaluatePopulation(nextGeneration);
nextGeneration.addPopulation(this.m_Population); nextGeneration.addPopulation(this.m_Population);
this.m_Population = nextGeneration; this.m_Population = nextGeneration;
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
* @param name The indenifier /**
* This method allows you to set an identifier for the algorithm
*
* @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,36 +215,45 @@ 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.";
} }
@Override @Override
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,33 +9,31 @@ 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 int m_MultiRuns = 100;
private int m_FitnessCalls = 100;
private int m_FitnessCallsNeeded = 0;
GAIndividualBinaryData m_Best, m_Test;
public double m_InitialFloodPeak = 2000.0, m_CurrentFloodPeak;
public double m_DrainRate = 1.0;
private InterfaceOptimizationProblem m_Problem = new B1Problem();
private int m_MultiRuns = 100;
private int m_FitnessCalls = 100;
private int m_FitnessCallsNeeded = 0;
GAIndividualBinaryData m_Best, m_Test;
public double m_InitialFloodPeak = 2000.0, m_CurrentFloodPeak;
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;
private Population m_Population; private Population m_Population;
public FloodAlgorithm() { public FloodAlgorithm() {
this.m_Population = new Population(); this.m_Population = new Population();
@@ -43,10 +41,10 @@ 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;
} }
@Override @Override
@@ -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,27 +63,30 @@ 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 /**
* @param reset If true the population is reset. * This method will init the optimizer with a given population
*
* @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);
this.firePropertyChangedEvent(Population.nextGenerationPerformed); this.firePropertyChangedEvent(Population.nextGenerationPerformed);
} }
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++) {
indy = ((AbstractEAIndividual) this.m_Population.get(i)); indy = ((AbstractEAIndividual) this.m_Population.get(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,13 +108,15 @@ 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 /**
* @param org The original * This method calculates the difference between the fitness values
* @param mut The mutant *
* @param org The original
* @param mut The mutant
*/ */
private double calculateDelta(AbstractEAIndividual org, AbstractEAIndividual mut) { private double calculateDelta(AbstractEAIndividual org, AbstractEAIndividual mut) {
double result = 0; double result = 0;
double[] fitOrg, fitMut; double[] fitOrg, fitMut;
fitOrg = org.getFitness(); fitOrg = org.getFitness();
fitMut = mut.getFitness(); fitMut = mut.getFitness();
for (int i = 0; i < fitOrg.length; i++) { for (int i = 0; i < fitOrg.length; i++) {
@@ -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
* @param name The indenifier /**
* This method allows you to set an identifier for the algorithm
*
* @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
public String getIdentifier() {
return this.m_Identifier;
}
/** This method is required to free the memory on a RMIServer,
* but there is nothing to implement.
*/
@Override @Override
public void freeWilly() { public String getIdentifier() {
return this.m_Identifier;
} }
/**********************************************************************************************************************
* These are for GUI /**
*/ * ********************************************************************************************************************
/** This method returns a global info string * These are for GUI
*/
/**
* 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

File diff suppressed because it is too large Load Diff

View File

@@ -9,31 +9,29 @@ 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 InterfaceMutation mutator = null; private InterfaceOptimizationProblem m_Problem = new B1Problem();
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;
private Population m_Population; private Population m_Population;
public HillClimbing() { public HillClimbing() {
this.m_Population = new Population(); this.m_Population = new Population();
@@ -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,20 +60,21 @@ 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);
this.firePropertyChangedEvent(Population.nextGenerationPerformed); this.firePropertyChangedEvent(Population.nextGenerationPerformed);
} }
} }
/** 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,20 +84,19 @@ 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));
} else { } else {
// else: mutation improved the individual, so leave the new one // else: mutation improved the individual, so leave the new one
} }
} }
this.m_Population.incrGeneration(); this.m_Population.incrGeneration();
@@ -119,28 +118,32 @@ public class HillClimbing implements InterfaceOptimizer, java.io.Serializable {
} }
public InterfaceMutation getMutationOperator() { public InterfaceMutation getMutationOperator() {
return mutator; return mutator;
} }
/** /**
* 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
*/ */
public void SetMutationOperator(InterfaceMutation mute) { public void SetMutationOperator(InterfaceMutation mute) {
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,63 +224,68 @@ 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
* @param name The indenifier /**
* This method allows you to set an identifier for the algorithm
*
* @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
public String getIdentifier() {
return this.m_Identifier;
}
/** This method is required to free the memory on a RMIServer,
* but there is nothing to implement.
*/
@Override @Override
public void freeWilly() { public String getIdentifier() {
return this.m_Identifier;
} }
/**********************************************************************************************************************
* These are for GUI /**
*/ * ********************************************************************************************************************
/** This method returns a global info string * These are for GUI
*/
/**
* 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;
} }
@Override @Override
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,64 +17,59 @@ 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();
private InterfaceOptimizer m_Optimizer = new GeneticAlgorithm(); private InterfaceOptimizer m_Optimizer = new GeneticAlgorithm();
private InterfaceMigration m_Migration = new SOBestMigration(); private InterfaceMigration m_Migration = new SOBestMigration();
private InterfaceOptimizationProblem m_Problem = new F8Problem(); private InterfaceOptimizationProblem m_Problem = new F8Problem();
// 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;
this.m_localOnly = a.m_localOnly; this.m_localOnly = a.m_localOnly;
} }
@Override @Override
@@ -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);
@@ -115,49 +110,51 @@ public class IslandModelEA implements InterfacePopulationChangedEventListener, I
// this is running on remote machines // this is running on remote machines
// ToDo: Parallelize with Threads?!? // ToDo: Parallelize with Threads?!?
/*if (this.m_LocalServer == null) { /*if (this.m_LocalServer == null) {
this.m_LocalServer = RMIServer.getInstance(); this.m_LocalServer = RMIServer.getInstance();
} }
try { try {
myLocal = (InterfacePopulationChangedEventListener) RMIProxyLocal.newInstance(this); myLocal = (InterfacePopulationChangedEventListener) RMIProxyLocal.newInstance(this);
} catch(Exception e) { } catch(Exception e) {
System.err.println("Island Model EA warning on local RMIServer... but i'll start anyway!"); System.err.println("Island Model EA warning on local RMIServer... but i'll start anyway!");
} }
String[] nodesList = this.m_Servers.getCheckedServerNodes(); String[] nodesList = this.m_Servers.getCheckedServerNodes();
if ((nodesList == null) || (nodesList.length == 0)) { if ((nodesList == null) || (nodesList.length == 0)) {
throw new RuntimeException("Error, no active remote servers available! Activate servers or use localOnly mode."); throw new RuntimeException("Error, no active remote servers available! Activate servers or use localOnly mode.");
} }
this.m_Islands = new InterfaceOptimizer[nodesList.length]; this.m_Islands = new InterfaceOptimizer[nodesList.length];
for (int i = 0; i < nodesList.length; i++) { for (int i = 0; i < nodesList.length; i++) {
this.m_Islands[i] = (InterfaceOptimizer) RMIProxyRemoteThread.newInstance(this.m_Optimizer, nodesList[i]); this.m_Islands[i] = (InterfaceOptimizer) RMIProxyRemoteThread.newInstance(this.m_Optimizer, nodesList[i]);
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(myLocal); this.m_Islands[i].addPopulationChangedEventListener(myLocal);
} }
}*/ }*/
} }
this.m_Migration.initMigration(this.m_Islands); this.m_Migration.initMigration(this.m_Islands);
Population pop; Population pop;
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 /**
* @param reset If true the population is reset. * This method will init the optimizer with a given population
*
* @param reset If true the population is reset.
*/ */
@Override @Override
public void initByPopulation(Population tpop, boolean reset) { public void initByPopulation(Population tpop, boolean reset) {
// TODO this is again evil copy&paste style // TODO this is again evil copy&paste style
if (this.m_Show) { if (this.m_Show) {
if (this.m_Plot == null) { if (this.m_Plot == null) {
double[] tmpD = new double[2]; double[] tmpD = new double[2];
@@ -167,9 +164,9 @@ 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();
} }
this.m_Optimizer.init(); this.m_Optimizer.init();
@@ -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);
@@ -190,47 +187,48 @@ public class IslandModelEA implements InterfacePopulationChangedEventListener, I
// this is running on remote machines // this is running on remote machines
// ToDo: Parallellize with threads?!? // ToDo: Parallellize with threads?!?
/* /*
if (this.m_LocalServer == null) { if (this.m_LocalServer == null) {
this.m_LocalServer = RMIServer.getInstance(); this.m_LocalServer = RMIServer.getInstance();
} }
try { try {
myLocal = (InterfacePopulationChangedEventListener) RMIProxyLocal.newInstance(this); myLocal = (InterfacePopulationChangedEventListener) RMIProxyLocal.newInstance(this);
} catch(Exception e) { } catch(Exception e) {
System.err.println("Island Model EA warning on local RMIServer... but i'll try to start anyway!"); System.err.println("Island Model EA warning on local RMIServer... but i'll try to start anyway!");
} }
String[] nodesList = this.m_Servers.getCheckedServerNodes(); String[] nodesList = this.m_Servers.getCheckedServerNodes();
if ((nodesList == null) || (nodesList.length == 0)) { if ((nodesList == null) || (nodesList.length == 0)) {
return; return;
} }
this.m_Islands = new InterfaceOptimizer[nodesList.length]; this.m_Islands = new InterfaceOptimizer[nodesList.length];
for (int i = 0; i < nodesList.length; i++) { for (int i = 0; i < nodesList.length; i++) {
this.m_Islands[i] = (InterfaceOptimizer) RMIProxyRemoteThread.newInstance(this.m_Optimizer, nodesList[i]); this.m_Islands[i] = (InterfaceOptimizer) RMIProxyRemoteThread.newInstance(this.m_Optimizer, nodesList[i]);
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(myLocal); this.m_Islands[i].addPopulationChangedEventListener(myLocal);
} }
}*/ }*/
} }
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,28 +251,28 @@ 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
boolean allReachedG = false; boolean allReachedG = false;
int G = this.m_Population.getGeneration(); int G = this.m_Population.getGeneration();
while (!allReachedG) { while (!allReachedG) {
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) {
System.err.println("Error in sleep of XThread"); System.err.println("Error in sleep of XThread");
} }
} }
} }
@@ -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,22 +370,23 @@ 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
*/ */
public static void main(String[] args) { public static void main(String[] args) {
// @todo die ServerStarter muss ich noch hin kriegen // @todo die ServerStarter muss ich noch hin kriegen
// @todo Wichtig ich brauche den eva2.tools.jproxy.RMIServer! // @todo Wichtig ich brauche den eva2.tools.jproxy.RMIServer!
IslandModelEA imea = new IslandModelEA(); IslandModelEA imea = new IslandModelEA();
imea.m_Show = true; imea.m_Show = true;
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());
@@ -386,7 +395,7 @@ public class IslandModelEA implements InterfacePopulationChangedEventListener, I
c.getKMeans().setUseSearchSpace(false); c.getKMeans().setUseSearchSpace(false);
c.setUseConstraints(true); c.setUseConstraints(true);
c.m_Debug = true; c.m_Debug = true;
imea.m_Migration = c; imea.m_Migration = c;
} }
if (false) { if (false) {
MOConeSeparation c = new MOConeSeparation(); MOConeSeparation c = new MOConeSeparation();
@@ -395,11 +404,11 @@ public class IslandModelEA implements InterfacePopulationChangedEventListener, I
imea.m_Migration = c; imea.m_Migration = c;
} }
if (true) { if (true) {
imea.m_Migration = new MOBestMigration(); imea.m_Migration = new MOBestMigration();
} }
} 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 /**
* @param name The indenifier * This method allows you to set an identifier for the algorithm
*
* @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
public String getIdentifier() {
return this.m_Identifier;
}
/** This method will return the Optimizers @Override
public String getIdentifier() {
return this.m_Identifier;
}
/**
* 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. * ********************************************************************************************************************
* These are for InterfacePopulationChangedEventListener
*/ */
@Override /**
public void freeWilly() { * This method allows an optimizer to register a change in the EA-lecture
for (int i = 0; i < this.m_Islands.length; i++) { *
this.m_Islands[i].freeWilly(); * @param source The source of the event.
} * @param name Could be used to indicate the nature of the event.
}
/**********************************************************************************************************************
* These are for InterfacePopulationChangedEventListener
*/
/** This method allows an optimizer to register a change in the EA-lecture
* @param source The source 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){
this.m_Show = b; public void setShow(boolean b) {
this.m_LogLocalChanges = b; this.m_Show = 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,36 +594,42 @@ 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)";
} }
@Override @Override
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
* @param n Number of processors. /**
* This method allows you to set the number of processors in local mode
*
* @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);
@@ -265,21 +265,21 @@ public class MLTGA implements InterfaceOptimizer, java.io.Serializable, Interfac
} }
private AbstractEAIndividual buildNewIndy(AbstractEAIndividual indy, private AbstractEAIndividual buildNewIndy(AbstractEAIndividual indy,
Stack<Set<Integer>> linkageTree) { Stack<Set<Integer>> linkageTree) {
for (Set<Integer> mask : linkageTree) { for (Set<Integer> mask : linkageTree) {
BitSet gen = getBinaryData(indy); BitSet gen = getBinaryData(indy);
BitSet newGene = (BitSet) gen.clone(); BitSet newGene = (BitSet) gen.clone();
for (Integer flipID : mask) { for (Integer flipID : mask) {
newGene.flip(flipID); newGene.flip(flipID);
} }
AbstractEAIndividual newIndy = (AbstractEAIndividual) this.template.clone(); AbstractEAIndividual newIndy = (AbstractEAIndividual) this.template.clone();
((InterfaceDataTypeBinary) newIndy).SetBinaryGenotype(newGene); ((InterfaceDataTypeBinary) newIndy).SetBinaryGenotype(newGene);
evaluate(newIndy); evaluate(newIndy);
if (newIndy.getFitness(0) < indy.getFitness(0)) { if (newIndy.getFitness(0) < indy.getFitness(0)) {
indy = newIndy; indy = newIndy;
} }
} }
return indy; return indy;
} }
/** /**
@@ -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,421 +12,400 @@ 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 {
/** /**
* serial version uid. * serial version uid.
*/ */
private static final long serialVersionUID = -1730086430763348568L; private static final long serialVersionUID = -1730086430763348568L;
private int localSearchSteps = 1;
private int subsetsize = 5;
private int globalSearchIterations = 1;
private boolean lamarckism = true;
// int counter = 0; !?
// int maxfunctioncalls = 1000; !?
private boolean TRACE = false;
private String m_Identifier = "";
private InterfaceOptimizationProblem m_Problem = new F1Problem();
private InterfaceOptimizer m_GlobalOptimizer = new GeneticAlgorithm();
private InterfaceSelection selectorPlug = new SelectBestIndividuals();
transient private InterfacePopulationChangedEventListener m_Listener;
private int localSearchSteps = 1; public MemeticAlgorithm() {
}
private int subsetsize = 5; public MemeticAlgorithm(MemeticAlgorithm a) {
// this.m_Population = (Population)a.m_Population.clone();
private int globalSearchIterations = 1; this.m_Problem = (InterfaceLocalSearchable) a.m_Problem.clone();
this.m_GlobalOptimizer = (InterfaceOptimizer) a.m_GlobalOptimizer;
private boolean lamarckism = true; this.selectorPlug = (InterfaceSelection) a.selectorPlug;
this.m_Identifier = a.m_Identifier;
// int counter = 0; !? this.localSearchSteps = a.localSearchSteps;
// int maxfunctioncalls = 1000; !? this.subsetsize = a.subsetsize;
this.globalSearchIterations = a.globalSearchIterations;
private boolean TRACE = false; this.lamarckism = a.lamarckism;
}
private String m_Identifier = "";
private InterfaceOptimizationProblem m_Problem = new F1Problem();
private InterfaceOptimizer m_GlobalOptimizer = new GeneticAlgorithm();
private InterfaceSelection selectorPlug = new SelectBestIndividuals();
transient private InterfacePopulationChangedEventListener m_Listener;
public MemeticAlgorithm() {
}
public MemeticAlgorithm(MemeticAlgorithm a) {
// this.m_Population = (Population)a.m_Population.clone();
this.m_Problem = (InterfaceLocalSearchable) a.m_Problem.clone();
this.m_GlobalOptimizer = (InterfaceOptimizer) a.m_GlobalOptimizer;
this.selectorPlug = (InterfaceSelection) a.selectorPlug;
this.m_Identifier = a.m_Identifier;
this.localSearchSteps = a.localSearchSteps;
this.subsetsize = a.subsetsize;
this.globalSearchIterations = a.globalSearchIterations;
this.lamarckism = a.lamarckism;
}
@Override
public Object clone() {
return new MemeticAlgorithm(this);
}
@Override @Override
public void initByPopulation(Population pop, boolean reset) { public Object clone() {
this.setPopulation((Population) pop.clone()); return new MemeticAlgorithm(this);
if (reset) { }
this.getPopulation().init();
this.m_Problem.evaluate(this.getPopulation());
this.firePropertyChangedEvent(Population.nextGenerationPerformed);
}
}
@Override @Override
public void init() { public void initByPopulation(Population pop, boolean reset) {
// counter = 0; this.setPopulation((Population) pop.clone());
this.m_GlobalOptimizer.setProblem(this.m_Problem); if (reset) {
this.m_GlobalOptimizer.init(); this.getPopulation().init();
this.evaluatePopulation(this.m_GlobalOptimizer.getPopulation()); this.m_Problem.evaluate(this.getPopulation());
this.firePropertyChangedEvent(Population.nextGenerationPerformed); this.firePropertyChangedEvent(Population.nextGenerationPerformed);
} }
}
/**
* This method will evaluate the current population using the given problem.
*
* @param population
* The population that is to be evaluated
*/
private void evaluatePopulation(Population population) {
this.m_Problem.evaluate(population);
population.incrGeneration();
}
@Override @Override
public void optimize() { public void init() {
// counter = 0;
this.m_GlobalOptimizer.setProblem(this.m_Problem);
this.m_GlobalOptimizer.init();
this.evaluatePopulation(this.m_GlobalOptimizer.getPopulation());
this.firePropertyChangedEvent(Population.nextGenerationPerformed);
}
if (TRACE) { /**
System.out.println("global search"); * This method will evaluate the current population using the given problem.
*
* @param population The population that is to be evaluated
*/
private void evaluatePopulation(Population population) {
this.m_Problem.evaluate(population);
population.incrGeneration();
}
@Override
public void optimize() {
if (TRACE) {
System.out.println("global search");
}
this.m_GlobalOptimizer.optimize();
if ((globalSearchIterations > 0) && (((this.m_GlobalOptimizer.getPopulation().getGeneration() % this.globalSearchIterations) == 0))
&& (this.localSearchSteps > 0)
&& (this.m_Problem instanceof InterfaceLocalSearchable)) {
// here the local search is performed
if (TRACE) {
System.out.println("Performing local search on " + subsetsize
+ " individuals.");
} }
this.m_GlobalOptimizer.optimize(); Population gop = this.m_GlobalOptimizer.getPopulation();
Population subset = selectorPlug.selectFrom(gop, subsetsize);
if ((globalSearchIterations>0) && (((this.m_GlobalOptimizer.getPopulation().getGeneration() % this.globalSearchIterations) == 0)) Population subsetclone = new Population();
&& (this.localSearchSteps > 0) for (int i = 0; i < subset.size(); i++) {
&& (this.m_Problem instanceof InterfaceLocalSearchable)) { subsetclone.add(((AbstractEAIndividual) subset.get(i)).clone());
// here the local search is performed }
if (TRACE) { if (subset.size() != subsetsize) {
System.out.println("Performing local search on " + subsetsize System.err.println("ALERT! identical individual instances in subset");
+ " individuals."); }
} Hashtable antilamarckismcache = new Hashtable();
Population gop = this.m_GlobalOptimizer.getPopulation(); if (!this.lamarckism) {
Population subset = selectorPlug.selectFrom(gop, subsetsize); for (int i = 0; i < subset.size(); i++) {
Population subsetclone = new Population(); AbstractEAIndividual indy = (AbstractEAIndividual) subset.get(i);
for (int i = 0; i < subset.size(); i++) { AbstractEAIndividual indyclone = (AbstractEAIndividual) subsetclone
subsetclone.add(((AbstractEAIndividual) subset.get(i)).clone()); .get(i);
} antilamarckismcache.put(indy, indyclone);
if (subset.size() != subsetsize) { }
System.err.println("ALERT! identical individual instances in subset");
}
Hashtable antilamarckismcache = new Hashtable();
if (!this.lamarckism) {
for (int i = 0; i < subset.size(); i++) {
AbstractEAIndividual indy = (AbstractEAIndividual) subset.get(i);
AbstractEAIndividual indyclone = (AbstractEAIndividual) subsetclone
.get(i);
antilamarckismcache.put(indy, indyclone);
}
}
// int dosearchsteps = this.localSearchSteps;
double cost = ((InterfaceLocalSearchable) this.m_Problem)
.getLocalSearchStepFunctionCallEquivalent();
// int calls = gop.getFunctionCalls() + (int) Math.round(localSearchSteps
// * cost * subset.size());
// nett aber total unn<6E>tig-falsch man kann nicht davon ausgehen, dass man
// einen Fitnesscall Terminator hat..
// if (calls > this.maxfunctioncalls) {
// int remainingfunctioncalls = this.maxfunctioncalls -
// gop.getFunctionCalls();
// dosearchsteps = (int)Math.floor(((double) remainingfunctioncalls) /
// (cost * subsetsize));
// stopit = true;
// }
for (int i = 0; i < localSearchSteps; i++) {
((InterfaceLocalSearchable) this.m_Problem).doLocalSearch(subsetclone);
}
this.m_Problem.evaluate(subsetclone);
if (this.lamarckism) {
gop.removeAll(subset);
gop.addPopulation(subsetclone);
} else {
for (int i = 0; i < subset.size(); i++) {
AbstractEAIndividual indy = (AbstractEAIndividual) subset.get(i);
try {
AbstractEAIndividual newindy = (AbstractEAIndividual) antilamarckismcache
.get(indy);
indy.setFitness(newindy.getFitness());
} catch (Exception ex) {
System.err.println("individual not found in antilamarckismcache");
}
}
}
// eigentlich muss hier noch subsetsize drauf, aber lassen wir das
gop.SetFunctionCalls(gop.getFunctionCalls()
+ (int) Math.round(localSearchSteps * cost * subset.size()));
if (TRACE) {
System.out.println("Population size after local search:" + gop.size());
}
this.setPopulation(gop);
}
if (TRACE) {
System.out.println("function calls"
+ this.m_GlobalOptimizer.getPopulation().getFunctionCalls());
} }
this.firePropertyChangedEvent(Population.nextGenerationPerformed);
}
/** // int dosearchsteps = this.localSearchSteps;
* This method allows you to add the LectureGUI as listener to the Optimizer double cost = ((InterfaceLocalSearchable) this.m_Problem)
* .getLocalSearchStepFunctionCallEquivalent();
* @param ea // int calls = gop.getFunctionCalls() + (int) Math.round(localSearchSteps
*/ // * cost * subset.size());
@Override // nett aber total unn<6E>tig-falsch man kann nicht davon ausgehen, dass man
public void addPopulationChangedEventListener( // einen Fitnesscall Terminator hat..
InterfacePopulationChangedEventListener ea) { // if (calls > this.maxfunctioncalls) {
this.m_Listener = ea; // int remainingfunctioncalls = this.maxfunctioncalls -
} // gop.getFunctionCalls();
@Override // dosearchsteps = (int)Math.floor(((double) remainingfunctioncalls) /
public boolean removePopulationChangedEventListener( // (cost * subsetsize));
InterfacePopulationChangedEventListener ea) { // stopit = true;
if (m_Listener==ea) { // }
m_Listener=null; for (int i = 0; i < localSearchSteps; i++) {
return true; ((InterfaceLocalSearchable) this.m_Problem).doLocalSearch(subsetclone);
} else { }
return false; this.m_Problem.evaluate(subsetclone);
} if (this.lamarckism) {
} gop.removeAll(subset);
/** gop.addPopulation(subsetclone);
* Something has changed } else {
*/ for (int i = 0; i < subset.size(); i++) {
protected void firePropertyChangedEvent(String name) { AbstractEAIndividual indy = (AbstractEAIndividual) subset.get(i);
if (this.m_Listener != null) { try {
if (TRACE) { AbstractEAIndividual newindy = (AbstractEAIndividual) antilamarckismcache
System.out.println("firePropertyChangedEvent MA"); .get(indy);
indy.setFitness(newindy.getFitness());
} catch (Exception ex) {
System.err.println("individual not found in antilamarckismcache");
} }
this.m_Listener.registerPopulationStateChanged(this, name); }
} }
} // eigentlich muss hier noch subsetsize drauf, aber lassen wir das
gop.SetFunctionCalls(gop.getFunctionCalls()
+ (int) Math.round(localSearchSteps * cost * subset.size()));
/** if (TRACE) {
* This method will set the problem that is to be optimized System.out.println("Population size after local search:" + gop.size());
* }
* @param problem
*/ this.setPopulation(gop);
}
if (TRACE) {
System.out.println("function calls"
+ this.m_GlobalOptimizer.getPopulation().getFunctionCalls());
}
this.firePropertyChangedEvent(Population.nextGenerationPerformed);
}
/**
* This method allows you to add the LectureGUI as listener to the Optimizer
*
* @param ea
*/
@Override @Override
public void setProblem(InterfaceOptimizationProblem problem) { public void addPopulationChangedEventListener(
this.m_Problem = problem; InterfacePopulationChangedEventListener ea) {
this.m_GlobalOptimizer.setProblem(this.m_Problem); this.m_Listener = ea;
} }
@Override @Override
public InterfaceOptimizationProblem getProblem() { public boolean removePopulationChangedEventListener(
return this.m_Problem; InterfacePopulationChangedEventListener ea) {
} if (m_Listener == ea) {
m_Listener = null;
return true;
} else {
return false;
}
}
/** /**
* This method will return a string describing all properties of the optimizer * Something has changed
* and the applied methods. */
* protected void firePropertyChangedEvent(String name) {
* @return A descriptive string if (this.m_Listener != null) {
*/ if (TRACE) {
@Override System.out.println("firePropertyChangedEvent MA");
public String getStringRepresentation() { }
String result = ""; this.m_Listener.registerPopulationStateChanged(this, name);
result += "Memetic Algorithm:\n"; }
result += "Optimization Problem: "; }
result += this.m_Problem.getStringRepresentationForProblem(this) + "\n";
result += this.m_GlobalOptimizer.getStringRepresentation();
return result;
}
/** /**
* This method allows you to set an identifier for the algorithm * This method will set the problem that is to be optimized
* *
* @param name * @param problem
* The indenifier */
*/
@Override @Override
public void setIdentifier(String name) { public void setProblem(InterfaceOptimizationProblem problem) {
this.m_Identifier = name; this.m_Problem = problem;
} this.m_GlobalOptimizer.setProblem(this.m_Problem);
}
@Override @Override
public String getIdentifier() { public InterfaceOptimizationProblem getProblem() {
return this.m_Identifier; return this.m_Problem;
} }
/** /**
* This method is required to free the memory on a RMIServer, but there is * This method will return a string describing all properties of the
* nothing to implement. * optimizer and the applied methods.
*/ *
* @return A descriptive string
*/
@Override @Override
public void freeWilly() { public String getStringRepresentation() {
String result = "";
result += "Memetic Algorithm:\n";
result += "Optimization Problem: ";
result += this.m_Problem.getStringRepresentationForProblem(this) + "\n";
result += this.m_GlobalOptimizer.getStringRepresentation();
return result;
}
} /**
* This method allows you to set an identifier for the algorithm
/* *
* ======================================================================================== * @param name The indenifier
* These are for GUI */
*/
/**
* This method returns a global info string
*
* @return description
*/
public static String globalInfo() {
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 " +
"that the problem class must implement InterfaceLocalSearchable.";
}
/**
* This method will return a naming String
*
* @return The name of the algorithm
*/
@Override @Override
public String getName() { public void setIdentifier(String name) {
return "MemeticAlgorithm"; this.m_Identifier = name;
} }
/**
* Assuming that all optimizer will store thier data in a population we will
* allow acess to this population to query to current state of the optimizer.
*
* @return The population of current solutions to a given problem.
*/
@Override
public Population getPopulation() {
return this.m_GlobalOptimizer.getPopulation();
}
@Override @Override
public void setPopulation(Population pop) { public String getIdentifier() {
this.m_GlobalOptimizer.setPopulation(pop); return this.m_Identifier;
} }
public String populationTipText() {
return "Edit the properties of the population used.";
}
/** /*
* Choose the global optimization strategy to use * ========================================================================================
* * These are for GUI
* @param m_GlobalOptimizer */
*/ /**
public void setGlobalOptimizer(InterfaceOptimizer m_GlobalOptimizer) { * This method returns a global info string
this.m_GlobalOptimizer = m_GlobalOptimizer; *
this.m_GlobalOptimizer.setProblem(this.getProblem()); * @return description
this.init(); */
} public static String globalInfo() {
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 "
+ "that the problem class must implement InterfaceLocalSearchable.";
}
public InterfaceOptimizer getGlobalOptimizer() { /**
return m_GlobalOptimizer; * This method will return a naming String
} *
* @return The name of the algorithm
*/
@Override
public String getName() {
return "MemeticAlgorithm";
}
public String globalOptimizerTipText() { /**
return "Choose the global optimization strategy to use."; * 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.
*/
@Override
public Population getPopulation() {
return this.m_GlobalOptimizer.getPopulation();
}
/** @Override
* Choose the number of local search steps to perform per selected individual. public void setPopulation(Population pop) {
* this.m_GlobalOptimizer.setPopulation(pop);
* @param localSearchSteps }
*/
public void setLocalSearchSteps(int localSearchSteps) {
this.localSearchSteps = localSearchSteps;
}
public int getLocalSearchSteps() {
return localSearchSteps;
}
public String localSearchStepsTipText() {
return "Choose the number of local search steps to perform per selected individual.";
}
/** public String populationTipText() {
* Choose the interval between the application of the local search return "Edit the properties of the population used.";
* }
* @param globalSearchSteps
*/ /**
public void setGlobalSearchIterations(int globalSearchSteps) { * Choose the global optimization strategy to use
this.globalSearchIterations = globalSearchSteps; *
} * @param m_GlobalOptimizer
public int getGlobalSearchIterations() { */
return globalSearchIterations; public void setGlobalOptimizer(InterfaceOptimizer m_GlobalOptimizer) {
} this.m_GlobalOptimizer = m_GlobalOptimizer;
public String globalSearchIterationsTipText() { this.m_GlobalOptimizer.setProblem(this.getProblem());
return "Choose the interval between the application of the local search."; this.init();
} }
public InterfaceOptimizer getGlobalOptimizer() {
return m_GlobalOptimizer;
}
public String globalOptimizerTipText() {
return "Choose the global optimization strategy to use.";
}
/**
* Choose the number of local search steps to perform per selected
* individual.
*
* @param localSearchSteps
*/
public void setLocalSearchSteps(int localSearchSteps) {
this.localSearchSteps = localSearchSteps;
}
public int getLocalSearchSteps() {
return localSearchSteps;
}
public String localSearchStepsTipText() {
return "Choose the number of local search steps to perform per selected individual.";
}
/**
* Choose the interval between the application of the local search
*
* @param globalSearchSteps
*/
public void setGlobalSearchIterations(int globalSearchSteps) {
this.globalSearchIterations = globalSearchSteps;
}
public int getGlobalSearchIterations() {
return globalSearchIterations;
}
public String globalSearchIterationsTipText() {
return "Choose the interval between the application of the local search.";
}
@Override @Override
public InterfaceSolutionSet getAllSolutions() { public InterfaceSolutionSet getAllSolutions() {
return new SolutionSet(getPopulation()); return new SolutionSet(getPopulation());
}
/**
* Choose the number of individual to be locally optimized
*
* @param subsetsize
*/
public void setSubsetsize(int subsetsize) {
this.subsetsize = subsetsize;
} }
/**
* Choose the number of individual to be locally optimized
*
* @param subsetsize
*/
public void setSubsetsize(int subsetsize) {
this.subsetsize = subsetsize;
}
public int getSubsetsize() { public int getSubsetsize() {
return subsetsize; return subsetsize;
} }
public String subsetsizeTipText() {
return "Choose the number of individuals to be locally optimized.";
}
/** public String subsetsizeTipText() {
* Toggle between Lamarckism and the Baldwin Effect return "Choose the number of individuals to be locally optimized.";
* }
* @param lamarckism
*/
public void setLamarckism(boolean lamarckism) {
this.lamarckism = lamarckism;
}
public String lamarckismTipText() {
return "Toggle between Lamarckism and the Baldwin Effect.";
}
public boolean isLamarckism() {
return lamarckism;
}
public InterfaceSelection getSubSetSelector() { /**
return selectorPlug; * Toggle between Lamarckism and the Baldwin Effect
} *
public void setSubSetSelector(InterfaceSelection selectorPlug) { * @param lamarckism
this.selectorPlug = selectorPlug; */
} public void setLamarckism(boolean lamarckism) {
public String subSetSelectorTipText() { this.lamarckism = lamarckism;
return "Selection method to select the subset on which local search is to be performed."; }
}
public String lamarckismTipText() {
return "Toggle between Lamarckism and the Baldwin Effect.";
}
public boolean isLamarckism() {
return lamarckism;
}
public InterfaceSelection getSubSetSelector() {
return selectorPlug;
}
public void setSubSetSelector(InterfaceSelection selectorPlug) {
this.selectorPlug = selectorPlug;
}
public String subSetSelectorTipText() {
return "Selection method to select the subset on which local search is to be performed.";
}
} }

View File

@@ -10,34 +10,33 @@ 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 * Copyright: Copyright (c) 2003 Company: University of Tuebingen, Computer
* Company: University of Tuebingen, Computer Architecture * Architecture
* @author Felix Streichert *
* @version: $Revision: 307 $ * @author Felix Streichert
* $Date: 2007-12-04 14:31:47 +0100 (Tue, 04 Dec 2007) $ * @version: $Revision: 307 $ $Date: 2007-12-04 14:31:47 +0100 (Tue, 04 Dec
* $Author: mkron $ * 2007) $ $Author: mkron $
*/ */
public class MonteCarloSearch implements InterfaceOptimizer, java.io.Serializable { public class MonteCarloSearch implements InterfaceOptimizer, java.io.Serializable {
/**
* Generated serial version id.
*/
private static final long serialVersionUID = -751760624411490405L;
// These variables are necessary for the simple testcase
private InterfaceOptimizationProblem m_Problem = new B1Problem();
private int m_MultiRuns = 100;
private int m_FitnessCalls = 100;
private int m_FitnessCallsNeeded = 0;
private Population m_Population;
private GAIndividualBinaryData m_Best, m_Test;
/**
* Generated serial version id.
*/
private static final long serialVersionUID = -751760624411490405L;
// These variables are necessary for the simple testcase
private InterfaceOptimizationProblem m_Problem = new B1Problem();
private int m_MultiRuns = 100;
private int m_FitnessCalls = 100;
private int m_FitnessCallsNeeded = 0;
private Population m_Population;
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;
public MonteCarloSearch() { public MonteCarloSearch() {
@@ -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,37 +64,39 @@ 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 /**
* @param pop The initial population * This method will init the optimizer with a given population
* @param reset If true the population is reset. *
* @param pop The initial population
* @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);
this.firePropertyChangedEvent(Population.nextGenerationPerformed); this.firePropertyChangedEvent(Population.nextGenerationPerformed);
} }
} }
/** /**
* 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,64 +206,72 @@ 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
* @param name The indenifier /**
* This method allows you to set an identifier for the algorithm
*
* @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
public String getIdentifier() {
return this.m_Identifier;
}
/** This method is required to free the memory on a RMIServer,
* but there is nothing to implement.
*/
@Override @Override
public void freeWilly() { public String getIdentifier() {
return this.m_Identifier;
} }
/**********************************************************************************************************************
* These are for GUI /**
*/ * ********************************************************************************************************************
/** This method returns a global info string * These are for GUI
*/
/**
* 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.";
} }
@Override @Override
public InterfaceSolutionSet getAllSolutions() { public InterfaceSolutionSet getAllSolutions() {
return new SolutionSet(getPopulation()); return new SolutionSet(getPopulation());
} }
} }

View File

@@ -21,401 +21,386 @@ import java.util.HashMap;
*/ */
public class MultiObjectiveCMAES implements InterfaceOptimizer, Serializable { public class MultiObjectiveCMAES implements InterfaceOptimizer, Serializable {
/** /**
* Generated serial version identifier * Generated serial version identifier
*/ */
private static final long serialVersionUID = 1L; private static final long serialVersionUID = 1L;
/** /**
* *
* @author mkron * @author mkron
* *
*/ */
class CounterClass { class CounterClass {
public CounterClass(int i) {
value = i;
}
public int value; public CounterClass(int i) {
public boolean seen = false; value = i;
} }
public int value;
public boolean seen = false;
}
private String m_Identifier = "MOCMAES";
private Population m_Population;
private AbstractOptimizationProblem m_Problem;
transient private InterfacePopulationChangedEventListener m_Listener;
private int m_lambda = 1;
private int m_lambdamo = 1;
private String m_Identifier = "MOCMAES"; public MultiObjectiveCMAES() {
m_Population = new Population(m_lambdamo);
}
private Population m_Population; public MultiObjectiveCMAES(MultiObjectiveCMAES a) {
private AbstractOptimizationProblem m_Problem; m_Problem = (AbstractOptimizationProblem) a.m_Problem.clone();
setPopulation((Population) a.m_Population.clone());
transient private InterfacePopulationChangedEventListener m_Listener; m_lambda = a.m_lambda;
}
private int m_lambda = 1;
private int m_lambdamo = 1;
public MultiObjectiveCMAES() {
m_Population = new Population(m_lambdamo);
}
public MultiObjectiveCMAES(MultiObjectiveCMAES a) {
m_Problem = (AbstractOptimizationProblem) a.m_Problem.clone();
setPopulation((Population) a.m_Population.clone());
m_lambda = a.m_lambda;
}
@Override @Override
public MultiObjectiveCMAES clone() { public MultiObjectiveCMAES clone() {
return new MultiObjectiveCMAES(this); return new MultiObjectiveCMAES(this);
} }
public void hideHideable() { public void hideHideable() {
GenericObjectEditor GenericObjectEditor
.setHideProperty(this.getClass(), "population", true); .setHideProperty(this.getClass(), "population", true);
} }
/* /*
* (non-Javadoc) * (non-Javadoc)
* *
* @see * @see
* eva2.server.go.strategies.InterfaceOptimizer#setIdentifier(java.lang. * eva2.server.go.strategies.InterfaceOptimizer#setIdentifier(java.lang.
* String) * String)
*/ */
@Override @Override
public void setIdentifier(String name) { public void setIdentifier(String name) {
m_Identifier = name; m_Identifier = name;
} }
/* /*
* (non-Javadoc) * (non-Javadoc)
* *
* @see * @see
* eva2.server.go.strategies.InterfaceOptimizer#SetProblem(eva2.server.go * eva2.server.go.strategies.InterfaceOptimizer#SetProblem(eva2.server.go
* .problems.InterfaceOptimizationProblem) * .problems.InterfaceOptimizationProblem)
*/ */
@Override @Override
public void setProblem(InterfaceOptimizationProblem problem) { public void setProblem(InterfaceOptimizationProblem problem) {
m_Problem = (AbstractOptimizationProblem) problem; m_Problem = (AbstractOptimizationProblem) problem;
} }
/** /**
* 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( public void addPopulationChangedEventListener(
InterfacePopulationChangedEventListener ea) { InterfacePopulationChangedEventListener ea) {
this.m_Listener = ea; this.m_Listener = ea;
} }
/* /*
* (non-Javadoc) * (non-Javadoc)
* *
* @see eva2.server.go.strategies.InterfaceOptimizer#freeWilly() * @see eva2.server.go.strategies.InterfaceOptimizer#getAllSolutions()
*/ */
@Override @Override
public void freeWilly() { public InterfaceSolutionSet getAllSolutions() {
} Population pop = getPopulation();
return new SolutionSet(pop, pop);
}
/* /*
* (non-Javadoc) * (non-Javadoc)
* *
* @see eva2.server.go.strategies.InterfaceOptimizer#getAllSolutions() * @see eva2.server.go.strategies.InterfaceOptimizer#getIdentifier()
*/ */
@Override @Override
public InterfaceSolutionSet getAllSolutions() { public String getIdentifier() {
Population pop = getPopulation(); return m_Identifier;
return new SolutionSet(pop, pop); }
}
/* /*
* (non-Javadoc) * (non-Javadoc)
* *
* @see eva2.server.go.strategies.InterfaceOptimizer#getIdentifier() * @see eva2.server.go.strategies.InterfaceOptimizer#getName()
*/ */
@Override @Override
public String getIdentifier() { public String getName() {
return m_Identifier; return "(1+" + m_lambda + ") MO-CMA-ES";
} }
/* public static String globalInfo() {
* (non-Javadoc) return "A multi-objective CMA-ES variant after Igel, Hansen and Roth 2007 (EC 15(1),1-28).";
* }
* @see eva2.server.go.strategies.InterfaceOptimizer#getName()
*/ /*
* (non-Javadoc)
*
* @see eva2.server.go.strategies.InterfaceOptimizer#getPopulation()
*/
@Override @Override
public String getName() { public Population getPopulation() {
return "(1+" + m_lambda + ") MO-CMA-ES"; return m_Population;
} }
public static String globalInfo() { /*
return "A multi-objective CMA-ES variant after Igel, Hansen and Roth 2007 (EC 15(1),1-28)."; * (non-Javadoc)
} *
* @see eva2.server.go.strategies.InterfaceOptimizer#getProblem()
/* */
* (non-Javadoc)
*
* @see eva2.server.go.strategies.InterfaceOptimizer#getPopulation()
*/
@Override @Override
public Population getPopulation() { public InterfaceOptimizationProblem getProblem() {
return m_Population; return m_Problem;
} }
/* /*
* (non-Javadoc) * (non-Javadoc)
* *
* @see eva2.server.go.strategies.InterfaceOptimizer#getProblem() * @see
*/ * eva2.server.go.strategies.InterfaceOptimizer#getStringRepresentation()
*/
@Override @Override
public InterfaceOptimizationProblem getProblem() { public String getStringRepresentation() {
return m_Problem; StringBuilder strB = new StringBuilder(200);
} strB.append("(1+" + m_lambda + ") MO-CMA-ES:\nOptimization Problem: ");
strB.append(this.m_Problem.getStringRepresentationForProblem(this));
strB.append("\n");
strB.append(this.m_Population.getStringRepresentation());
return strB.toString();
}
/* /*
* (non-Javadoc) * (non-Javadoc)
* *
* @see * @see eva2.server.go.strategies.InterfaceOptimizer#init()
* eva2.server.go.strategies.InterfaceOptimizer#getStringRepresentation() */
*/
@Override @Override
public String getStringRepresentation() { public void init() {
StringBuilder strB = new StringBuilder(200); // initByPopulation(m_Population, true);
strB.append("(1+" + m_lambda + ") MO-CMA-ES:\nOptimization Problem: "); this.m_Population.setTargetSize(m_lambdamo);
strB.append(this.m_Problem.getStringRepresentationForProblem(this)); this.m_Problem.initPopulation(this.m_Population);
strB.append("\n"); // children = new Population(m_Population.size());
strB.append(this.m_Population.getStringRepresentation()); this.evaluatePopulation(this.m_Population);
return strB.toString(); this.firePropertyChangedEvent(Population.nextGenerationPerformed);
}
/* }
* (non-Javadoc)
* /*
* @see eva2.server.go.strategies.InterfaceOptimizer#init() * (non-Javadoc)
*/ *
* @see
* eva2.server.go.strategies.InterfaceOptimizer#initByPopulation(eva2.server
* .go.populations.Population, boolean)
*/
@Override @Override
public void init() { public void initByPopulation(Population pop, boolean reset) {
// initByPopulation(m_Population, true); setPopulation(pop);
this.m_Population.setTargetSize(m_lambdamo); if (reset) {
this.m_Problem.initPopulation(this.m_Population); m_Problem.initPopulation(m_Population);
// children = new Population(m_Population.size()); m_Problem.evaluate(m_Population);
this.evaluatePopulation(this.m_Population);
this.firePropertyChangedEvent(Population.nextGenerationPerformed);
} }
}
/* /**
* (non-Javadoc) * This method will evaluate the current population using the given problem.
* *
* @see * @param population The population that is to be evaluated
* eva2.server.go.strategies.InterfaceOptimizer#initByPopulation(eva2.server */
* .go.populations.Population, boolean) private void evaluatePopulation(Population population) {
*/ this.m_Problem.evaluate(population);
}
/*
* (non-Javadoc)
*
* @see eva2.server.go.strategies.InterfaceOptimizer#optimize()
*/
@Override @Override
public void initByPopulation(Population pop, boolean reset) { public void optimize() {
setPopulation(pop);
if (reset) {
m_Problem.initPopulation(m_Population);
m_Problem.evaluate(m_Population);
} HashMap<Long, CounterClass> SuccessCounterMap = new HashMap<Long, CounterClass>();
}
/** // Eltern markieren und f<>r die Z<>hlung vorbereiten
* This method will evaluate the current population using the given problem. for (int j = 0; j < m_lambdamo && j < m_Population.size(); j++) {
* m_Population.getEAIndividual(j).putData("Parent",
* @param population m_Population.getEAIndividual(j));
* The population that is to be evaluated SuccessCounterMap.put(m_Population.getEAIndividual(j).getIndyID(),
*/ new CounterClass(0));
private void evaluatePopulation(Population population) { }
this.m_Problem.evaluate(population);
}
/* // Kinder erzeugen
* (non-Javadoc) Population children = new Population(m_lambdamo * m_lambda);
* children.setGenerationTo(m_Population.getGeneration());
* @see eva2.server.go.strategies.InterfaceOptimizer#optimize()
*/
@Override
public void optimize() {
HashMap<Long, CounterClass> SuccessCounterMap = new HashMap<Long, CounterClass>(); for (int j = 0; j < children.getTargetSize(); j++) {
AbstractEAIndividual parent = m_Population.getEAIndividual(j
% m_lambdamo);
AbstractEAIndividual indy = (AbstractEAIndividual) parent.clone();
indy.mutate();
indy.putData("Parent", parent);
children.add(indy);
}
evaluatePopulation(children);
// Eltern markieren und f<>r die Z<>hlung vorbereiten m_Population.addPopulation(children);
for (int j = 0; j < m_lambdamo && j < m_Population.size(); j++) { // Ranking
m_Population.getEAIndividual(j).putData("Parent", ArchivingNSGAII dummyArchive = new ArchivingNSGAIISMeasure();
m_Population.getEAIndividual(j)); Population[] store = dummyArchive
SuccessCounterMap.put(m_Population.getEAIndividual(j).getIndyID(), .getNonDominatedSortedFronts(m_Population);
new CounterClass(0)); store = dummyArchive.getNonDominatedSortedFronts(m_Population);
} dummyArchive.calculateCrowdingDistance(store);
// Kinder erzeugen // Vergleichen und den Successcounter hochz<68>hlen wenn wir besser als
Population children = new Population(m_lambdamo * m_lambda); // unser Elter sind
children.setGenerationTo(m_Population.getGeneration()); for (int j = 0; j < m_Population.size(); j++) {
AbstractEAIndividual parent = (AbstractEAIndividual) m_Population
.getEAIndividual(j).getData("Parent");
if (m_Population.getEAIndividual(j) != parent) { // Eltern nicht mit
// sich selber
// vergleichen
int parentParetoLevel = ((Integer) parent
.getData("ParetoLevel")).intValue();
double parentSMeasure = ((Double) parent.getData("HyperCube"))
.doubleValue();
int childParetoLevel = ((Integer) m_Population.getEAIndividual(
j).getData("ParetoLevel")).intValue();
double childSMeasure = ((Double) m_Population
.getEAIndividual(j).getData("HyperCube")).doubleValue();
if (childParetoLevel < parentParetoLevel
|| ((childParetoLevel == parentParetoLevel) && childSMeasure > parentSMeasure)) {
SuccessCounterMap.get(parent.getIndyID()).value++;
}
} else { // Debug
for (int j = 0; j < children.getTargetSize(); j++) { SuccessCounterMap.get(parent.getIndyID()).seen = true;
AbstractEAIndividual parent = m_Population.getEAIndividual(j
% m_lambdamo);
AbstractEAIndividual indy = (AbstractEAIndividual) parent.clone();
indy.mutate();
indy.putData("Parent", parent);
children.add(indy);
}
evaluatePopulation(children);
m_Population.addPopulation(children);
// Ranking
ArchivingNSGAII dummyArchive = new ArchivingNSGAIISMeasure();
Population[] store = dummyArchive
.getNonDominatedSortedFronts(m_Population);
store = dummyArchive.getNonDominatedSortedFronts(m_Population);
dummyArchive.calculateCrowdingDistance(store);
// Vergleichen und den Successcounter hochz<68>hlen wenn wir besser als
// unser Elter sind
for (int j = 0; j < m_Population.size(); j++) {
AbstractEAIndividual parent = (AbstractEAIndividual) m_Population
.getEAIndividual(j).getData("Parent");
if (m_Population.getEAIndividual(j) != parent) { // Eltern nicht mit
// sich selber
// vergleichen
int parentParetoLevel = ((Integer) parent
.getData("ParetoLevel")).intValue();
double parentSMeasure = ((Double) parent.getData("HyperCube"))
.doubleValue();
int childParetoLevel = ((Integer) m_Population.getEAIndividual(
j).getData("ParetoLevel")).intValue();
double childSMeasure = ((Double) m_Population
.getEAIndividual(j).getData("HyperCube")).doubleValue();
if (childParetoLevel < parentParetoLevel
|| ((childParetoLevel == parentParetoLevel) && childSMeasure > parentSMeasure)) {
SuccessCounterMap.get(parent.getIndyID()).value++;
}
} else { // Debug
SuccessCounterMap.get(parent.getIndyID()).seen = true;
}
}
// Selection
m_Population.clear();
for (int i = 0; i < store.length; i++) {
if (m_Population.size() + store[i].size() <= m_lambdamo) { // Die
// Front
// passt
// noch
// komplett
m_Population.addPopulation(store[i]);
} else { // die besten aus der aktuellen Front heraussuchen bis voll
while (store[i].size() > 0 && m_Population.size() < m_lambdamo) {
AbstractEAIndividual indy = store[i].getEAIndividual(0);
double bestMeasure = ((Double) indy.getData("HyperCube"))
.doubleValue(); // TODO mal noch effizient machen
// (sortieren und die besten n
// herausholen)
for (int j = 1; j < store[i].size(); j++) {
if (bestMeasure < ((Double) store[i].getEAIndividual(j)
.getData("HyperCube")).doubleValue()) {
bestMeasure = ((Double) store[i].getEAIndividual(j)
.getData("HyperCube")).doubleValue();
indy = store[i].getEAIndividual(j);
}
}
m_Population.add(indy);
store[i].removeMember(indy);
}
}
}
// Strategieparemeter updaten
for (int j = 0; j < m_Population.size(); j++) {
AbstractEAIndividual indy = m_Population.getEAIndividual(j);
if (indy.getMutationOperator() instanceof MutateESCovarianceMatrixAdaptionPlus) { // Das
// geht
// nur
// wenn
// wir
// auch
// die
// richtige
// Mutation
// haben
AbstractEAIndividual parent = (AbstractEAIndividual) indy
.getData("Parent");
MutateESCovarianceMatrixAdaptionPlus muta = (MutateESCovarianceMatrixAdaptionPlus) indy
.getMutationOperator();
double rate = ((double) SuccessCounterMap.get(parent
.getIndyID()).value)
/ ((double) m_lambda);
if (indy != parent) {
muta.updateCovariance();
}
muta.updateStepSize(rate);
}
}
for (int j = 0; j < children.size(); j++) {
children.getEAIndividual(j).putData("Parent", null);
}
m_Population.incrFunctionCallsBy(children.size());
m_Population.incrGeneration();
this.firePropertyChangedEvent(Population.nextGenerationPerformed);
}
/*
* (non-Javadoc)
*
* @seeeva2.server.go.strategies.InterfaceOptimizer#
* removePopulationChangedEventListener
* (eva2.server.go.InterfacePopulationChangedEventListener)
*/
@Override
public boolean removePopulationChangedEventListener(
InterfacePopulationChangedEventListener ea) {
return false;
}
/*
* (non-Javadoc)
*
* @see
* eva2.server.go.strategies.InterfaceOptimizer#setPopulation(eva2.server
* .go.populations.Population)
*/
@Override
public void setPopulation(Population pop) {
m_Population = pop;
m_Population.setNotifyEvalInterval(1);
m_lambdamo = m_Population.getTargetSize();
}
/**
* Something has changed
*
* @param name
*/
protected void firePropertyChangedEvent(String name) {
if (this.m_Listener != null) {
this.m_Listener.registerPopulationStateChanged(this, name);
} }
} }
public int getLambda() { // Selection
return m_lambda; m_Population.clear();
} for (int i = 0; i < store.length; i++) {
if (m_Population.size() + store[i].size() <= m_lambdamo) { // Die
// Front
// passt
// noch
// komplett
m_Population.addPopulation(store[i]);
public void setLambda(int mLambda) { } else { // die besten aus der aktuellen Front heraussuchen bis voll
m_lambda = mLambda; while (store[i].size() > 0 && m_Population.size() < m_lambdamo) {
} AbstractEAIndividual indy = store[i].getEAIndividual(0);
double bestMeasure = ((Double) indy.getData("HyperCube"))
.doubleValue(); // TODO mal noch effizient machen
// (sortieren und die besten n
// herausholen)
for (int j = 1; j < store[i].size(); j++) {
if (bestMeasure < ((Double) store[i].getEAIndividual(j)
.getData("HyperCube")).doubleValue()) {
bestMeasure = ((Double) store[i].getEAIndividual(j)
.getData("HyperCube")).doubleValue();
indy = store[i].getEAIndividual(j);
}
}
m_Population.add(indy);
store[i].removeMember(indy);
}
}
/* }
* public int getLambdaMo() { return m_lambdamo; }
*
* public void setLambdaMo(int mLambda) { m_lambdamo = mLambda; }
*/
// Strategieparemeter updaten
for (int j = 0; j < m_Population.size(); j++) {
AbstractEAIndividual indy = m_Population.getEAIndividual(j);
if (indy.getMutationOperator() instanceof MutateESCovarianceMatrixAdaptionPlus) { // Das
// geht
// nur
// wenn
// wir
// auch
// die
// richtige
// Mutation
// haben
AbstractEAIndividual parent = (AbstractEAIndividual) indy
.getData("Parent");
MutateESCovarianceMatrixAdaptionPlus muta = (MutateESCovarianceMatrixAdaptionPlus) indy
.getMutationOperator();
double rate = ((double) SuccessCounterMap.get(parent
.getIndyID()).value)
/ ((double) m_lambda);
if (indy != parent) {
muta.updateCovariance();
}
muta.updateStepSize(rate);
}
}
for (int j = 0; j < children.size(); j++) {
children.getEAIndividual(j).putData("Parent", null);
}
m_Population.incrFunctionCallsBy(children.size());
m_Population.incrGeneration();
this.firePropertyChangedEvent(Population.nextGenerationPerformed);
}
/*
* (non-Javadoc)
*
* @seeeva2.server.go.strategies.InterfaceOptimizer#
* removePopulationChangedEventListener
* (eva2.server.go.InterfacePopulationChangedEventListener)
*/
@Override
public boolean removePopulationChangedEventListener(
InterfacePopulationChangedEventListener ea) {
return false;
}
/*
* (non-Javadoc)
*
* @see
* eva2.server.go.strategies.InterfaceOptimizer#setPopulation(eva2.server
* .go.populations.Population)
*/
@Override
public void setPopulation(Population pop) {
m_Population = pop;
m_Population.setNotifyEvalInterval(1);
m_lambdamo = m_Population.getTargetSize();
}
/**
* Something has changed
*
* @param name
*/
protected void firePropertyChangedEvent(String name) {
if (this.m_Listener != null) {
this.m_Listener.registerPopulationStateChanged(this, name);
}
}
public int getLambda() {
return m_lambda;
}
public void setLambda(int mLambda) {
m_lambda = mLambda;
}
/*
* public int getLambdaMo() { return m_lambdamo; }
*
* public void setLambdaMo(int mLambda) { m_lambdamo = mLambda; }
*/
} }

View File

@@ -16,53 +16,42 @@ 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 {
private InterfaceOptimizer m_Optimizer = new GeneticAlgorithm(); private InterfaceOptimizer m_Optimizer = new GeneticAlgorithm();
private InterfaceArchiving m_Archiver = new ArchivingNSGAII(); private InterfaceArchiving m_Archiver = new ArchivingNSGAII();
private InterfaceInformationRetrieval m_InformationRetrieval = new InformationRetrievalInserting(); private InterfaceInformationRetrieval m_InformationRetrieval = new InformationRetrievalInserting();
private InterfaceOptimizationProblem m_Problem = new FM0Problem(); private InterfaceOptimizationProblem m_Problem = new FM0Problem();
private String m_Identifier = ""; private String m_Identifier = "";
transient private InterfacePopulationChangedEventListener m_Listener; transient private InterfacePopulationChangedEventListener m_Listener;
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,
InterfaceInformationRetrieval infoRetrieval, AbstractOptimizationProblem problem) { InterfaceInformationRetrieval infoRetrieval, AbstractOptimizationProblem problem) {
setOptimizer(subOpt); setOptimizer(subOpt);
setArchivingStrategy(archiving); setArchivingStrategy(archiving);
setArchiveSize(archiveSize); setArchiveSize(archiveSize);
@@ -82,10 +71,11 @@ 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 reset If true the population is reset. * @param pop The initial population
* @param reset If true the population is reset.
*/ */
@Override @Override
public void initByPopulation(Population pop, boolean reset) { public void initByPopulation(Population pop, boolean 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];
@@ -170,37 +161,42 @@ 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 /**
* @param name The indenifier * This method allows you to set an identifier for the algorithm
*
* @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
public String getIdentifier() {
return this.m_Identifier;
}
/** This method is required to free the memory on a RMIServer,
* but there is nothing to implement.
*/
@Override @Override
public void freeWilly() { public String getIdentifier() {
return this.m_Identifier;
} }
/**********************************************************************************************************************
* These are for GUI /**
*/ * ********************************************************************************************************************
/** This method returns a global info string * These are for GUI
*/
/**
* 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,69 +253,87 @@ 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.";
} }
@Override @Override
public InterfaceSolutionSet getAllSolutions() { public InterfaceSolutionSet getAllSolutions() {
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,505 +15,497 @@ 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
* *
*/ */
public class NelderMeadSimplex implements InterfaceOptimizer, Serializable, InterfacePopulationChangedEventListener { public class NelderMeadSimplex implements InterfaceOptimizer, Serializable, InterfacePopulationChangedEventListener {
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 Population m_Population;
private AbstractOptimizationProblem m_Problem;
private transient Vector<InterfacePopulationChangedEventListener> m_Listener;
private String m_Identifier = "NelderMeadSimplex";
private boolean checkConstraints = true;
private int fitIndex = 0; // choose criterion for multi objective functions public NelderMeadSimplex() {
setPopulation(new Population(populationSize));
}
private Population m_Population; public NelderMeadSimplex(int popSize) {
private AbstractOptimizationProblem m_Problem; populationSize = popSize;
private transient Vector<InterfacePopulationChangedEventListener> m_Listener; setPopulation(new Population(populationSize));
private String m_Identifier = "NelderMeadSimplex"; }
private boolean checkConstraints = true;
public NelderMeadSimplex() { public NelderMeadSimplex(NelderMeadSimplex a) {
setPopulation(new Population(populationSize)); m_Problem = (AbstractOptimizationProblem) a.m_Problem.clone();
} setPopulation((Population) a.m_Population.clone());
populationSize = a.populationSize;
public NelderMeadSimplex(int popSize) { generationCycle = a.generationCycle;
populationSize=popSize; m_Identifier = a.m_Identifier;
setPopulation(new Population(populationSize)); }
}
public NelderMeadSimplex(NelderMeadSimplex a) {
m_Problem = (AbstractOptimizationProblem)a.m_Problem.clone();
setPopulation((Population)a.m_Population.clone());
populationSize = a.populationSize;
generationCycle = a.generationCycle;
m_Identifier = a.m_Identifier;
}
@Override @Override
public NelderMeadSimplex clone() { public NelderMeadSimplex clone() {
return new NelderMeadSimplex(this); return new NelderMeadSimplex(this);
} }
@Override @Override
public void setIdentifier(String name) { public void setIdentifier(String name) {
m_Identifier = name; m_Identifier = name;
} }
@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;
} }
} }
return false; return false;
} }
@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>();
} }
if (!m_Listener.contains(ea)) { if (!m_Listener.contains(ea)) {
m_Listener.add(ea); m_Listener.add(ea);
} }
} }
} }
@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 protected double[] calcChallengeVect(double[] centroid, double[] refX) {
public void freeWilly() {} double[] r = new double[centroid.length];
for (int i = 0; i < r.length; i++) {
protected double[] calcChallengeVect(double[] centroid, double[] refX) { r[i] = 2 * centroid[i] - refX[i];
double[] r = new double[centroid.length];
for (int i=0; i<r.length; 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]);
return r; return r;
} }
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) {
return firstIsBetter(first.getFitness(), second.getFitness()); return firstIsBetter(first.getFitness(), second.getFitness());
} }
protected boolean firstIsBetterEqual(AbstractEAIndividual first, AbstractEAIndividual second) { protected boolean firstIsBetterEqual(AbstractEAIndividual first, AbstractEAIndividual second) {
return firstIsBetterEqual(first.getFitness(), second.getFitness()); return firstIsBetterEqual(first.getFitness(), second.getFitness());
} }
public AbstractEAIndividual simplexStep(Population subpop) { public AbstractEAIndividual simplexStep(Population subpop) {
// parameter // parameter
// 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();
int dim = x_worst.length; int dim = x_worst.length;
// 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?
} }
} }
// Reflection // Reflection
double[] r = calcChallengeVect(centroid, x_worst); double[] r = calcChallengeVect(centroid, x_worst);
if (checkConstraints) { if (checkConstraints) {
if (!Mathematics.isInRange(r, range)) { if (!Mathematics.isInRange(r, range)) {
Mathematics.reflectBounds(r, range); Mathematics.reflectBounds(r, range);
} }
} }
// AbstractEAIndividual reflectedInd = (AbstractEAIndividual)((AbstractEAIndividual)bestpop.getIndividual(1)).clone(); // AbstractEAIndividual reflectedInd = (AbstractEAIndividual)((AbstractEAIndividual)bestpop.getIndividual(1)).clone();
// ((InterfaceDataTypeDouble)reflectedInd).SetDoubleGenotype(r); // ((InterfaceDataTypeDouble)reflectedInd).SetDoubleGenotype(r);
// //
// m_Problem.evaluate(reflectedInd); // m_Problem.evaluate(reflectedInd);
AbstractEAIndividual reflectedInd = createEvalIndy(bestpop, r); AbstractEAIndividual reflectedInd = createEvalIndy(bestpop, r);
this.m_Population.incrFunctionCalls(); this.m_Population.incrFunctionCalls();
if (firstIsBetter(best, reflectedInd) && firstIsBetter(reflectedInd, bestpop.getWorstEAIndividual(fitIndex))) { if (firstIsBetter(best, reflectedInd) && firstIsBetter(reflectedInd, bestpop.getWorstEAIndividual(fitIndex))) {
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);
} }
AbstractEAIndividual e_ind = createEvalIndy(bestpop, e); AbstractEAIndividual e_ind = createEvalIndy(bestpop, e);
this.m_Population.incrFunctionCalls(); this.m_Population.incrFunctionCalls();
if (firstIsBetter(e_ind, reflectedInd)) { //expandiertes ist besser als reflektiertes if (firstIsBetter(e_ind, reflectedInd)) { //expandiertes ist besser als reflektiertes
return e_ind; return e_ind;
} else { } else {
return reflectedInd; return reflectedInd;
} }
} 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)) {
Mathematics.projectToRange(c, range);
} }
if (checkConstraints && !Mathematics.isInRange(c, range)) {
Mathematics.projectToRange(c, range);
}
// AbstractEAIndividual c_ind = (AbstractEAIndividual)((AbstractEAIndividual)bestpop.getIndividual(1)).clone(); // AbstractEAIndividual c_ind = (AbstractEAIndividual)((AbstractEAIndividual)bestpop.getIndividual(1)).clone();
// ((InterfaceDataTypeDouble)c_ind).SetDoubleGenotype(c); // ((InterfaceDataTypeDouble)c_ind).SetDoubleGenotype(c);
// 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;
} }
} }
return null; return null;
} }
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;
} }
@Override @Override
public String getIdentifier() { public String getIdentifier() {
return m_Identifier; return m_Identifier;
} }
@Override @Override
public String getName() { public String getName() {
return m_Identifier; return m_Identifier;
} }
public static String globalInfo() { public static String globalInfo() {
return "The Nelder-Mead simplex search algorithm for local search. Reflection on bounds may be used for constraint handling."; return "The Nelder-Mead simplex search algorithm for local search. Reflection on bounds may be used for constraint handling.";
} }
@Override @Override
public Population getPopulation() { public Population getPopulation() {
return m_Population; return m_Population;
} }
@Override @Override
public InterfaceOptimizationProblem getProblem() { public InterfaceOptimizationProblem getProblem() {
return m_Problem; return m_Problem;
} }
@Override @Override
public String getStringRepresentation() { public String getStringRepresentation() {
StringBuilder strB = new StringBuilder(200); StringBuilder strB = new StringBuilder(200);
strB.append("Nelder-Mead-Simplex Strategy:\nOptimization Problem: "); strB.append("Nelder-Mead-Simplex Strategy:\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();
} }
@Override @Override
public void init() { public void init() {
initByPopulation(m_Population, true); initByPopulation(m_Population, true);
} }
@Override @Override
public void initByPopulation(Population pop, boolean reset) { public void initByPopulation(Population pop, boolean reset) {
setPopulation(pop); setPopulation(pop);
pop.addPopulationChangedEventListener(this); pop.addPopulationChangedEventListener(this);
if (reset) { if (reset) {
m_Problem.initPopulation(m_Population); m_Problem.initPopulation(m_Population);
m_Problem.evaluate(m_Population); m_Problem.evaluate(m_Population);
} }
// fireNextGenerationPerformed(); // fireNextGenerationPerformed();
} }
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);
} }
} }
} }
@Override @Override
public void optimize() { public void optimize() {
// make at least as many calls as there are individuals within the population. // make at least as many calls as there are individuals within the population.
// this simulates the generational loop expected by some other modules // this simulates the generational loop expected by some other modules
int evalCntStart = m_Population.getFunctionCalls(); int evalCntStart = m_Population.getFunctionCalls();
int evalsDone = 0; int evalsDone = 0;
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);
// ((InterfaceDataTypeDouble)ind).SetDoubleGenotype(x); // ((InterfaceDataTypeDouble)ind).SetDoubleGenotype(x);
// m_Problem.evaluate(ind); // m_Problem.evaluate(ind);
// 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.
}
m_Problem.evaluate(m_Population);
}
evalsDone = m_Population.getFunctionCalls() - evalCntStart;
} while (evalsDone < generationCycle);
m_Problem.evaluatePopulationEnd(m_Population);
this.m_Population.incrGeneration();
}
@Override
public void setPopulation(Population pop) {
m_Population = pop;
m_Population.addPopulationChangedEventListener(this);
m_Population.setNotifyEvalInterval(populationSize);
}
@Override
public InterfaceSolutionSet getAllSolutions() {
Population pop = getPopulation();
return new SolutionSet(pop, pop);
}
/**
* @return the populationSize
*/
public int getPopulationSize() {
return populationSize;
}
/**
* @param populationSize the populationSize to set
*/
public void setPopulationSize(int populationSize) {
this.populationSize = populationSize;
if (m_Population!=null) {
m_Population.setTargetSize(populationSize);
m_Population.setNotifyEvalInterval(m_Population.getTargetSize());
}
}
public String populationSizeTipText() {
return "The population size should be adapted to the dimensions of the problem (e.g. n+1)";
}
@Override
public void registerPopulationStateChanged(Object source, String name) {
if (name.compareTo(Population.funCallIntervalReached) == 0) {
fireNextGenerationPerformed();
}// else System.err.println("unknown event!");
}
/**
* This method creates a Nelder-Mead instance.
*
* @param pop
* The size of the population
* @param problem
* The problem to be optimized
* @param listener
* @return An optimization procedure that performs nelder mead optimization.
*/
public static final NelderMeadSimplex createNelderMeadSimplex(AbstractOptimizationProblem problem,
InterfacePopulationChangedEventListener listener) {
problem.initProblem();
NelderMeadSimplex nms = new NelderMeadSimplex();
nms.setProblemAndPopSize(problem);
if (listener!=null) {
nms.addPopulationChangedEventListener(listener);
} }
nms.init(); m_Problem.evaluate(m_Population);
if (listener!=null) {
listener.registerPopulationStateChanged(nms.getPopulation(), "");
}
return nms;
}
/**
* 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
* perturbation ratio or randomly across the search range if the perturbation ratio is
* zero or below zero.
*
*
* @param problem
* The problem to be optimized
* @param candidate starting point of the search
* @param perturbationRatio perturbation ratio relative to the problem range for the initial simplex creation
* @param listener
* @return An optimization procedure that performs nelder mead optimization.
*/
public static final NelderMeadSimplex createNelderMeadSimplexLocal(AbstractOptimizationProblem problem,
AbstractEAIndividual candidate, double perturbationRatio,
InterfacePopulationChangedEventListener listener) {
// TODO this method might be superfluous when using PostProcess
problem.initProblem();
NelderMeadSimplex nms = new NelderMeadSimplex();
nms.setProblemAndPopSize(problem);
Population initialPop;
if (perturbationRatio <= 0) { // random case
initialPop = new Population(nms.getPopulationSize());
problem.initPopulation(initialPop);
initialPop.set(0, candidate);
} else {
double[][] range = ((InterfaceDataTypeDouble)candidate).getDoubleRange();
if (range.length != nms.getPopulationSize()-1) {
System.err.println("Unexpected population size for nelder mead!");
}
initialPop = createNMSPopulation(candidate, perturbationRatio, range, true);
}
if (listener != null) {
nms.addPopulationChangedEventListener(listener);
}
nms.initByPopulation(initialPop, false);
//nms.setPopulation(initialPop);
return nms;
}
/**
* From a given candidate solution, create n solutions around the candidate, where every i-th
* new candidate differs in i dimensions by a distance of perturbRatio relative to the range in
* that dimension (respecting the range).
* The new solutions are returned as a population, which, if includeCand is true,
* also contains the initial candidate. However, the new candidates have not been evaluated.
*
* @param candidate
* @param perturbRelative
* @param range
* @param includeCand
* @return
*/
public static Population createNMSPopulation(AbstractEAIndividual candidate, double perturbRelative, double[][] range, boolean includeCand) {
Population initPop = new Population();
if (includeCand) {
initPop.add(candidate);
} }
if (perturbRelative >= 1. || (perturbRelative <= 0.)) { evalsDone = m_Population.getFunctionCalls() - evalCntStart;
System.err.println("Warning: perturbation ratio should lie between 0 and 1! (NelderMeadSimplex:createNMSPopulation)"); } while (evalsDone < generationCycle);
} m_Problem.evaluatePopulationEnd(m_Population);
addPerturbedPopulation(perturbRelative, initPop, range, candidate); this.m_Population.incrGeneration();
return initPop; }
}
private static void addPerturbedPopulation(double perturbationRatio, @Override
Population initialPop, double[][] range, AbstractEAIndividual candidate) { public void setPopulation(Population pop) {
AbstractEAIndividual indy = (AbstractEAIndividual)candidate.clone(); m_Population = pop;
// span by perturbation, every new individual i is modified in dimension i by m_Population.addPopulationChangedEventListener(this);
// a value of perturbRatio*range_i such that a simplex of relative side length perturbRatio is created. m_Population.setNotifyEvalInterval(populationSize);
for (int i=0; i<range.length; i+=1) { }
double curPerturb = ((range[i][1]-range[i][0])*perturbationRatio);
double[] dat = ((InterfaceDataTypeDouble)indy).getDoubleData();
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]);
} else {
dat[i] = Math.min(dat[i]+curPerturb, range[i][1]);
}
((InterfaceDataTypeDouble)indy).SetDoubleGenotype(dat);
indy.resetConstraintViolation();
initialPop.add((AbstractEAIndividual)indy.clone());
}
initialPop.synchSize();
}
/** @Override
* @param generationCycle the generationCycle to set public InterfaceSolutionSet getAllSolutions() {
*/ Population pop = getPopulation();
public void setGenerationCycle(int generationCycle) { return new SolutionSet(pop, pop);
this.generationCycle = generationCycle; }
}
public boolean isCheckRange() { /**
return checkConstraints; * @return the populationSize
} */
public int getPopulationSize() {
return populationSize;
}
public void setCheckRange(boolean checkRange) { /**
this.checkConstraints = checkRange; * @param populationSize the populationSize to set
} */
public void setPopulationSize(int populationSize) {
this.populationSize = populationSize;
if (m_Population != null) {
m_Population.setTargetSize(populationSize);
m_Population.setNotifyEvalInterval(m_Population.getTargetSize());
}
}
public String checkRangeTipText() { public String populationSizeTipText() {
return "Mark to check range constraints by reflection/projection"; return "The population size should be adapted to the dimensions of the problem (e.g. n+1)";
} }
public int getCritIndex() { @Override
return fitIndex; public void registerPopulationStateChanged(Object source, String name) {
} if (name.compareTo(Population.funCallIntervalReached) == 0) {
fireNextGenerationPerformed();
}// else System.err.println("unknown event!");
}
public void setCritIndex(int fitIndex) { /**
this.fitIndex = fitIndex; * This method creates a Nelder-Mead instance.
} *
* @param pop The size of the population
* @param problem The problem to be optimized
* @param listener
* @return An optimization procedure that performs nelder mead optimization.
*/
public static final NelderMeadSimplex createNelderMeadSimplex(AbstractOptimizationProblem problem,
InterfacePopulationChangedEventListener listener) {
public String critIndexTipText() { problem.initProblem();
return "For multi-criterial problems, set the index of the fitness to be used in 0..n-1. Default is 0"; NelderMeadSimplex nms = new NelderMeadSimplex();
} nms.setProblemAndPopSize(problem);
if (listener != null) {
nms.addPopulationChangedEventListener(listener);
}
nms.init();
if (listener != null) {
listener.registerPopulationStateChanged(nms.getPopulation(), "");
}
return nms;
}
/**
* 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 perturbation ratio or randomly across the search range if the
* perturbation ratio is zero or below zero.
*
*
* @param problem The problem to be optimized
* @param candidate starting point of the search
* @param perturbationRatio perturbation ratio relative to the problem range
* for the initial simplex creation
* @param listener
* @return An optimization procedure that performs nelder mead optimization.
*/
public static final NelderMeadSimplex createNelderMeadSimplexLocal(AbstractOptimizationProblem problem,
AbstractEAIndividual candidate, double perturbationRatio,
InterfacePopulationChangedEventListener listener) {
// TODO this method might be superfluous when using PostProcess
problem.initProblem();
NelderMeadSimplex nms = new NelderMeadSimplex();
nms.setProblemAndPopSize(problem);
Population initialPop;
if (perturbationRatio <= 0) { // random case
initialPop = new Population(nms.getPopulationSize());
problem.initPopulation(initialPop);
initialPop.set(0, candidate);
} else {
double[][] range = ((InterfaceDataTypeDouble) candidate).getDoubleRange();
if (range.length != nms.getPopulationSize() - 1) {
System.err.println("Unexpected population size for nelder mead!");
}
initialPop = createNMSPopulation(candidate, perturbationRatio, range, true);
}
if (listener != null) {
nms.addPopulationChangedEventListener(listener);
}
nms.initByPopulation(initialPop, false);
//nms.setPopulation(initialPop);
return nms;
}
/**
* From a given candidate solution, create n solutions around the candidate,
* where every i-th new candidate differs in i dimensions by a distance of
* perturbRatio relative to the range in that dimension (respecting the
* range). The new solutions are returned as a population, which, if
* includeCand is true, also contains the initial candidate. However, the
* new candidates have not been evaluated.
*
* @param candidate
* @param perturbRelative
* @param range
* @param includeCand
* @return
*/
public static Population createNMSPopulation(AbstractEAIndividual candidate, double perturbRelative, double[][] range, boolean includeCand) {
Population initPop = new Population();
if (includeCand) {
initPop.add(candidate);
}
if (perturbRelative >= 1. || (perturbRelative <= 0.)) {
System.err.println("Warning: perturbation ratio should lie between 0 and 1! (NelderMeadSimplex:createNMSPopulation)");
}
addPerturbedPopulation(perturbRelative, initPop, range, candidate);
return initPop;
}
private static void addPerturbedPopulation(double perturbationRatio,
Population initialPop, double[][] range, AbstractEAIndividual candidate) {
AbstractEAIndividual indy = (AbstractEAIndividual) candidate.clone();
// 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.
for (int i = 0; i < range.length; i += 1) {
double curPerturb = ((range[i][1] - range[i][0]) * perturbationRatio);
double[] dat = ((InterfaceDataTypeDouble) indy).getDoubleData();
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]);
} else {
dat[i] = Math.min(dat[i] + curPerturb, range[i][1]);
}
((InterfaceDataTypeDouble) indy).SetDoubleGenotype(dat);
indy.resetConstraintViolation();
initialPop.add((AbstractEAIndividual) indy.clone());
}
initialPop.synchSize();
}
/**
* @param generationCycle the generationCycle to set
*/
public void setGenerationCycle(int generationCycle) {
this.generationCycle = generationCycle;
}
public boolean isCheckRange() {
return checkConstraints;
}
public void setCheckRange(boolean checkRange) {
this.checkConstraints = checkRange;
}
public String checkRangeTipText() {
return "Mark to check range constraints by reflection/projection";
}
public int getCritIndex() {
return fitIndex;
}
public void setCritIndex(int fitIndex) {
this.fitIndex = fitIndex;
}
public String critIndexTipText() {
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,38 +21,35 @@ 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 Population m_Population = new Population(); private static final long serialVersionUID = 1L;
private InterfaceOptimizationProblem m_Problem = new F1Problem(); private Population m_Population = new Population();
private InterfaceSelection m_ParentSelection = new SelectParticleWheel(0.5); private InterfaceOptimizationProblem m_Problem = new F1Problem();
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; private double randomImmigrationQuota = 0.05;
private double randomImmigrationQuota = 0.05; 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;
@@ -66,31 +62,31 @@ public class ParticleFilterOptimization implements InterfaceOptimizer, java.io.S
} }
public ParticleFilterOptimization(double vInit, double mute, double immiQuote, double rotDeg, double selScaling) { public ParticleFilterOptimization(double vInit, double mute, double immiQuote, double rotDeg, double selScaling) {
mutationSigma = mute; mutationSigma = mute;
initialVelocity = vInit; initialVelocity = vInit;
randomImmigrationQuota = immiQuote; randomImmigrationQuota = immiQuote;
rotationDeg = rotDeg; rotationDeg = rotDeg;
m_ParentSelection = new SelectParticleWheel(selScaling); m_ParentSelection = new SelectParticleWheel(selScaling);
if (withShow) { if (withShow) {
setWithShow(true); setWithShow(true);
} }
} }
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);
} }
} }
public void hideHideable() { public void hideHideable() {
GenericObjectEditor.setHideProperty(this.getClass(), "population", true); GenericObjectEditor.setHideProperty(this.getClass(), "population", true);
} }
@Override @Override
@@ -103,12 +99,12 @@ public class ParticleFilterOptimization implements InterfaceOptimizer, java.io.S
//System.out.println("popsize is " + m_Population.size()); //System.out.println("popsize is " + m_Population.size());
//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);
setWithShow(withShow); setWithShow(withShow);
@@ -117,22 +113,25 @@ 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 /**
* @param pop The initial population * This method will init the optimizer with a given population
* @param reset If true the population is reset. *
* @param pop The initial population
* @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);
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 Population evaluatePopulation(Population population) { private Population evaluatePopulation(Population population) {
@@ -141,45 +140,44 @@ public class ParticleFilterOptimization implements InterfaceOptimizer, java.io.S
return population; return population;
} }
/** /**
* This method will resample the given population using EA parent selection. * This method will resample the given population using EA parent selection.
* *
*/ */
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 {
targetSize = (int) (this.m_Population.getTargetSize() * (1. - randomImmigrationQuota));
targetSize = Math.max(1, targetSize); // guarantee at least one to be selected
if (targetSize < this.m_Population.getTargetSize()) {
doImmigr = true;
}
} }
else {
targetSize = (int)(this.m_Population.getTargetSize() * (1.-randomImmigrationQuota));
targetSize = Math.max(1, targetSize); // guarantee at least one to be selected
if (targetSize < this.m_Population.getTargetSize()) {
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);
} }
parents.synchSize(); parents.synchSize();
if (TRACE) { if (TRACE) {
System.out.println("Added " + i + " random individuals"); System.out.println("Added " + i + " random individuals");
} }
} }
@@ -194,13 +192,13 @@ public class ParticleFilterOptimization implements InterfaceOptimizer, java.io.S
} }
protected void predict(Population pop) { protected void predict(Population pop) {
indCount = 0; indCount = 0;
if (withShow) { if (withShow) {
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) {
drawPop(pop, 1, false); drawPop(pop, 1, false);
@@ -208,20 +206,19 @@ public class ParticleFilterOptimization implements InterfaceOptimizer, java.io.S
} }
private void drawPop(Population pop, int graphLabel, boolean useCircles) { private void drawPop(Population pop, int graphLabel, boolean useCircles) {
if (myPlot != null) { if (myPlot != null) {
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);
// if ( !useCircles && (pop.getEAIndividual(i).hasData(MutateESCorrVector.vectorKey))) { // if ( !useCircles && (pop.getEAIndividual(i).hasData(MutateESCorrVector.vectorKey))) {
// double[] v=(double[])pop.getEAIndividual(i).getData(MutateESCorrVector.vectorKey); // double[] v=(double[])pop.getEAIndividual(i).getData(MutateESCorrVector.vectorKey);
@@ -229,14 +226,14 @@ public class ParticleFilterOptimization implements InterfaceOptimizer, java.io.S
// curPosition=Mathematics.vvAdd(v, curPosition); // curPosition=Mathematics.vvAdd(v, curPosition);
// myPlot.setConnectedPoint(curPosition[0], curPosition[1], graphLabel+5); // myPlot.setConnectedPoint(curPosition[0], curPosition[1], graphLabel+5);
// } // }
} }
} }
} }
protected void applyMotionModel(AbstractEAIndividual indy, double noise) { protected void applyMotionModel(AbstractEAIndividual indy, double noise) {
// this currently only performs a mutation // this currently only performs a mutation
indy.mutate(); indy.mutate();
indy.resetFitness(0); indy.resetFitness(0);
} }
/** /**
@@ -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
* @param name The indenifier /**
* This method allows you to set an identifier for the algorithm
*
* @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
public String getIdentifier() {
return this.m_Identifier;
}
/** This method is required to free the memory on a RMIServer,
* but there is nothing to implement.
*/
@Override @Override
public void freeWilly() { public String getIdentifier() {
return this.m_Identifier;
} }
/**********************************************************************************************************************
* These are for GUI /**
*/ * ********************************************************************************************************************
/** This method returns a global info string * These are for GUI
*/
/**
* 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,158 +366,171 @@ 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.";
} }
@Override @Override
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() { */
return withShow; public boolean isWithShow() {
} return withShow;
}
public Plot getPlot() { public Plot getPlot() {
return myPlot; return myPlot;
} }
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) {
myPlot.setCornerPoints(range, 0);
}
}
}
/**
* @param withShow the withShow to set
**/
public void setWithShow(boolean wShow) {
this.withShow = wShow;
if (!withShow) {
myPlot = null;
} }
else { if (range != null) {
double[][] range; myPlot.setCornerPoints(range, 0);
if ((m_Population != null) && (m_Population.size() > 0)) { }
range = ((InterfaceDataTypeDouble)this.m_Population.get(0)).getDoubleRange(); }
} }
else {
range = new double[2][];
range[0] = new double[2];
range[0][0] = 0;
range[0][1] = 0;
range[1] = range[0]; // this is evil
}
myPlot = new eva2.gui.Plot("PF", "x1", "x2", range[0], range[1]);
}
}
/** /**
* @return the sleepTime * @param withShow the withShow to set
**/ *
public int getSleepTime() { */
return sleepTime; public void setWithShow(boolean wShow) {
} this.withShow = wShow;
if (!withShow) {
myPlot = null;
} else {
double[][] range;
if ((m_Population != null) && (m_Population.size() > 0)) {
range = ((InterfaceDataTypeDouble) this.m_Population.get(0)).getDoubleRange();
} else {
range = new double[2][];
range[0] = new double[2];
range[0][0] = 0;
range[0][1] = 0;
range[1] = range[0]; // this is evil
}
myPlot = new eva2.gui.Plot("PF", "x1", "x2", range[0], range[1]);
}
}
/** /**
* @param sleepTime the sleepTime to set * @return the sleepTime
**/ *
public void setSleepTime(int sleepTime) { */
this.sleepTime = sleepTime; public int getSleepTime() {
} return sleepTime;
}
/** /**
* @return the mutationSigma * @param sleepTime the sleepTime to set
**/ *
public double getMutationSigma() { */
return mutationSigma; public void setSleepTime(int sleepTime) {
} this.sleepTime = sleepTime;
}
/** /**
* @param mutationSigma the mutationSigma to set * @return the mutationSigma
**/ *
public void setMutationSigma(double mutationSigma) { */
this.mutationSigma = mutationSigma; public double getMutationSigma() {
} return mutationSigma;
}
public String mutationSigmaTipText() { /**
return "The (fixed) mutation step for the gaussian motion model"; * @param mutationSigma the mutationSigma to set
} *
*/
public void setMutationSigma(double mutationSigma) {
this.mutationSigma = mutationSigma;
}
public double getRndImmigrQuota() { public String mutationSigmaTipText() {
return randomImmigrationQuota; return "The (fixed) mutation step for the gaussian motion model";
} }
public void setRndImmigrQuota(double randomImmigrationQuota) { public double getRndImmigrQuota() {
this.randomImmigrationQuota = randomImmigrationQuota; return randomImmigrationQuota;
} }
public String rndImmigrQuotaTipText() { public void setRndImmigrQuota(double randomImmigrationQuota) {
return "The give ratio of the population will be reinitialized randomly in every iteration."; this.randomImmigrationQuota = randomImmigrationQuota;
} }
public double getInitialVelocity() { public String rndImmigrQuotaTipText() {
return initialVelocity; return "The give ratio of the population will be reinitialized randomly in every iteration.";
} }
public void setInitialVelocity(double initialVelocity) { public double getInitialVelocity() {
this.initialVelocity = initialVelocity; return initialVelocity;
} }
public String initialVelocityTipText() { public void setInitialVelocity(double initialVelocity) {
return "If > 0, a linear motion model will be applied, otherwise the gaussian model"; this.initialVelocity = initialVelocity;
} }
public double getRotationDeg() { public String initialVelocityTipText() {
return rotationDeg; return "If > 0, a linear motion model will be applied, otherwise the gaussian model";
} }
public void setRotationDeg(double rotationDeg) { public double getRotationDeg() {
this.rotationDeg = rotationDeg; return rotationDeg;
} }
public int getPopSize() { public void setRotationDeg(double rotationDeg) {
return popSize; this.rotationDeg = rotationDeg;
} }
public void setPopSize(int popSize) { public int getPopSize() {
this.popSize = popSize; return popSize;
m_Population.setTargetSize(popSize); }
}
public void setPopSize(int popSize) {
this.popSize = popSize;
m_Population.setTargetSize(popSize);
}
} }

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
@@ -2063,7 +2055,7 @@ public class ParticleSwarmOptimization implements InterfaceOptimizer, java.io.Se
/** /**
* @return true if swarm visualization is turned on * @return true if swarm visualization is turned on
* *
*/ */
public boolean isShow() { public boolean isShow() {
return m_Show; return m_Show;
@@ -2071,7 +2063,7 @@ public class ParticleSwarmOptimization implements InterfaceOptimizer, java.io.Se
/** /**
* @param set swarm visualization (2D) * @param set swarm visualization (2D)
* *
*/ */
public void setShow(boolean show) { public void setShow(boolean show) {
m_Show = show; m_Show = show;
@@ -2086,7 +2078,7 @@ public class ParticleSwarmOptimization implements InterfaceOptimizer, java.io.Se
/** /**
* @return the checkSpeedLimit * @return the checkSpeedLimit
* *
*/ */
public boolean isCheckSpeedLimit() { public boolean isCheckSpeedLimit() {
return checkSpeedLimit; return checkSpeedLimit;
@@ -2094,7 +2086,7 @@ public class ParticleSwarmOptimization implements InterfaceOptimizer, java.io.Se
/** /**
* @param checkSpeedLimit the checkSpeedLimit to set * @param checkSpeedLimit the checkSpeedLimit to set
* *
*/ */
public void setCheckSpeedLimit(boolean checkSpeedLimit) { public void setCheckSpeedLimit(boolean checkSpeedLimit) {
this.checkSpeedLimit = checkSpeedLimit; this.checkSpeedLimit = checkSpeedLimit;
@@ -2113,7 +2105,7 @@ public class ParticleSwarmOptimization implements InterfaceOptimizer, java.io.Se
// } // }
/** /**
* @return the sleepTime * @return the sleepTime
* *
*/ */
public int getSleepTime() { public int getSleepTime() {
return sleepTime; return sleepTime;
@@ -2121,7 +2113,7 @@ public class ParticleSwarmOptimization implements InterfaceOptimizer, java.io.Se
/** /**
* @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;

View File

@@ -13,50 +13,50 @@ 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 * Copyright: Copyright (c) 2003 Company: University of Tuebingen, Computer
* Company: University of Tuebingen, Computer Architecture * Architecture
* @author Felix Streichert *
* @version: $Revision: 307 $ * @author Felix Streichert
* $Date: 2007-12-04 14:31:47 +0100 (Tue, 04 Dec 2007) $ * @version: $Revision: 307 $ $Date: 2007-12-04 14:31:47 +0100 (Tue, 04 Dec
* $Author: mkron $ * 2007) $ $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
private InterfaceOptimizationProblem m_Problem = new B1Problem(); private InterfaceOptimizationProblem m_Problem = new B1Problem();
private boolean m_UseElitism = true; private boolean m_UseElitism = true;
private InterfaceSelection m_SelectionOperator = new SelectBestIndividuals(); private InterfaceSelection m_SelectionOperator = new SelectBestIndividuals();
transient private String m_Identifier = ""; transient private String m_Identifier = "";
transient private InterfacePopulationChangedEventListener m_Listener; transient private InterfacePopulationChangedEventListener m_Listener;
private Population m_Population = new PBILPopulation(); private Population m_Population = new PBILPopulation();
private double m_LearningRate = 0.04; private double m_LearningRate = 0.04;
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,27 +78,30 @@ public class PopulationBasedIncrementalLearning implements InterfaceOptimizer, j
this.firePropertyChangedEvent(Population.nextGenerationPerformed); this.firePropertyChangedEvent(Population.nextGenerationPerformed);
} }
/** This method will init the optimizer with a given population /**
* @param pop The initial population * This method will init the optimizer with a given population
* @param reset If true the population is reset. *
* @param pop The initial population
* @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 (!(pop.getEAIndividual(0) instanceof InterfaceGAIndividual)) { if (!(pop.getEAIndividual(0) instanceof InterfaceGAIndividual)) {
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,17 +109,18 @@ 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");
//System.out.println("Population:"+this.m_Population.getSolutionRepresentationFor()); //System.out.println("Population:"+this.m_Population.getSolutionRepresentationFor());
this.m_SelectionOperator.prepareSelection(this.m_Population); this.m_SelectionOperator.prepareSelection(this.m_Population);
examples = this.m_SelectionOperator.selectFrom(this.m_Population, this.m_NumberOfPositiveSamples); examples = this.m_SelectionOperator.selectFrom(this.m_Population, this.m_NumberOfPositiveSamples);
//System.out.println("Parents:"+parents.getSolutionRepresentationFor()); //System.out.println("Parents:"+parents.getSolutionRepresentationFor());
result.learnFrom(examples, this.m_LearningRate); result.learnFrom(examples, this.m_LearningRate);
result.mutateProbabilityVector(this.m_MutationRate, this.m_MutateSigma); result.mutateProbabilityVector(this.m_MutationRate, this.m_MutateSigma);
@@ -127,7 +131,7 @@ public class PopulationBasedIncrementalLearning implements InterfaceOptimizer, j
@Override @Override
public void optimize() { public void optimize() {
Population nextGeneration; Population nextGeneration;
AbstractEAIndividual elite; AbstractEAIndividual elite;
nextGeneration = this.generateChildren(); nextGeneration = this.generateChildren();
this.evaluatePopulation(nextGeneration); this.evaluatePopulation(nextGeneration);
@@ -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
* @param name The indenifier /**
* This method allows you to set an identifier for the algorithm
*
* @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
public String getIdentifier() {
return this.m_Identifier;
}
/** This method is required to free the memory on a RMIServer,
* but there is nothing to implement.
*/
@Override @Override
public void freeWilly() { public String getIdentifier() {
return this.m_Identifier;
} }
/**********************************************************************************************************************
* These are for GUI /**
*/ * ********************************************************************************************************************
/** This method returns a global info string * These are for GUI
*/
/**
* 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,26 +244,30 @@ 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.";
} }
@Override @Override
public InterfaceSolutionSet getAllSolutions() { public InterfaceSolutionSet getAllSolutions() {
return new SolutionSet(getPopulation()); return new SolutionSet(getPopulation());
} }
// /** This method will set the normation method that is to be used. // /** This method will set the normation method that is to be used.
// * @param normation // * @param normation
@@ -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;
@@ -315,51 +349,61 @@ public class PopulationBasedIncrementalLearning implements InterfaceOptimizer, j
if (this.m_MutationRate > 1) { if (this.m_MutationRate > 1) {
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.";
} }
public double[] getInitialProbabilities() { public double[] getInitialProbabilities() {
return m_initialProbabilities; return m_initialProbabilities;
} }
public void setInitialProbabilities(double[] probabilities) { public void setInitialProbabilities(double[] probabilities) {
m_initialProbabilities = probabilities; m_initialProbabilities = probabilities;
} }
} }

File diff suppressed because it is too large Load Diff

View File

@@ -10,30 +10,28 @@ 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 int m_MultiRuns = 100;
private int m_FitnessCalls = 100;
private int m_FitnessCallsNeeded = 0;
GAIndividualBinaryData m_Best, m_Test;
public double m_InitialTemperature = 2, m_CurrentTemperature;
public double m_Alpha = 0.9;
private InterfaceOptimizationProblem m_Problem = new B1Problem();
private int m_MultiRuns = 100;
private int m_FitnessCalls = 100;
private int m_FitnessCallsNeeded = 0;
GAIndividualBinaryData m_Best, m_Test;
public double m_InitialTemperature = 2, m_CurrentTemperature;
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;
private Population m_Population; private Population m_Population;
public SimulatedAnnealing() { public SimulatedAnnealing() {
this.m_Population = new Population(); this.m_Population = new Population();
@@ -41,11 +39,11 @@ 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;
} }
@Override @Override
@@ -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,28 +62,31 @@ 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 /**
* @param pop The initial population * This method will init the optimizer with a given population
* @param reset If true the population is reset. *
* @param pop The initial population
* @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();
this.m_Problem.evaluate(this.m_Population); this.m_Problem.evaluate(this.m_Population);
this.firePropertyChangedEvent(Population.nextGenerationPerformed); this.firePropertyChangedEvent(Population.nextGenerationPerformed);
} }
} }
/** 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++) {
indy = ((AbstractEAIndividual) this.m_Population.get(i)); indy = ((AbstractEAIndividual) this.m_Population.get(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,13 +114,15 @@ 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 /**
* @param org The original * This method calculates the difference between the fitness values
* @param mut The mutant *
* @param org The original
* @param mut The mutant
*/ */
private double calculateDelta(AbstractEAIndividual org, AbstractEAIndividual mut) { private double calculateDelta(AbstractEAIndividual org, AbstractEAIndividual mut) {
double result = 0; double result = 0;
double[] fitOrg, fitMut; double[] fitOrg, fitMut;
fitOrg = org.getFitness(); fitOrg = org.getFitness();
fitMut = mut.getFitness(); fitMut = mut.getFitness();
for (int i = 0; i < fitOrg.length; i++) { for (int i = 0; i < fitOrg.length; i++) {
@@ -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,96 +224,112 @@ 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
* @param name The indenifier /**
* This method allows you to set an identifier for the algorithm
*
* @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
public String getIdentifier() {
return this.m_Identifier;
}
/** This method is required to free the memory on a RMIServer,
* but there is nothing to implement.
*/
@Override @Override
public void freeWilly() { public String getIdentifier() {
return this.m_Identifier;
} }
/**********************************************************************************************************************
* These are for GUI /**
*/ * ********************************************************************************************************************
/** This method returns a global info string * These are for GUI
*/
/**
* 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)).";
} }
@Override @Override
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,186 +13,200 @@ 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 {
private Population m_Population = new Population(); private Population m_Population = new Population();
private InterfaceOptimizationProblem m_Problem = new B1Problem(); private InterfaceOptimizationProblem m_Problem = new B1Problem();
private InterfaceSelection m_ParentSelection = new SelectTournament(); private InterfaceSelection m_ParentSelection = new SelectTournament();
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 = "";
transient private InterfacePopulationChangedEventListener m_Listener;
private String m_Identifier = ""; public SteadyStateGA() {
transient private InterfacePopulationChangedEventListener m_Listener; }
public SteadyStateGA() { public SteadyStateGA(SteadyStateGA a) {
} this.m_Population = (Population) a.m_Population.clone();
this.m_Problem = (InterfaceOptimizationProblem) a.m_Problem.clone();
public SteadyStateGA(SteadyStateGA a) { this.m_Identifier = a.m_Identifier;
this.m_Population = (Population)a.m_Population.clone(); this.m_NumberOfPartners = a.m_NumberOfPartners;
this.m_Problem = (InterfaceOptimizationProblem)a.m_Problem.clone(); this.m_ParentSelection = (InterfaceSelection) a.m_ParentSelection.clone();
this.m_Identifier = a.m_Identifier; this.m_PartnerSelection = (InterfaceSelection) a.m_PartnerSelection.clone();
this.m_NumberOfPartners = a.m_NumberOfPartners; this.m_ReplacementSelection = (InterfaceReplacement) a.m_ReplacementSelection.clone();
this.m_ParentSelection = (InterfaceSelection)a.m_ParentSelection.clone(); }
this.m_PartnerSelection = (InterfaceSelection)a.m_PartnerSelection.clone();
this.m_ReplacementSelection = (InterfaceReplacement)a.m_ReplacementSelection.clone();
}
@Override @Override
public Object clone() { public Object clone() {
return (Object) new SteadyStateGA(this); return (Object) new SteadyStateGA(this);
} }
@Override @Override
public void init() { public void init() {
this.m_Problem.initPopulation(this.m_Population); this.m_Problem.initPopulation(this.m_Population);
this.evaluatePopulation(this.m_Population);
this.firePropertyChangedEvent(Population.nextGenerationPerformed);
}
/**
* This method will init the optimizer with a given population
*
* @param reset If true the population is reset.
*/
@Override
public void initByPopulation(Population pop, boolean reset) {
this.m_Population = (Population) pop.clone();
if (reset) {
this.m_Population.init();
this.evaluatePopulation(this.m_Population); this.evaluatePopulation(this.m_Population);
this.firePropertyChangedEvent(Population.nextGenerationPerformed); this.firePropertyChangedEvent(Population.nextGenerationPerformed);
} }
}
/** This method will init the optimizer with a given population /**
* @param reset If true the population is reset. * This method will evaluate the current population using the given problem.
*/ *
@Override * @param population The population that is to be evaluated
public void initByPopulation(Population pop, boolean reset) { */
this.m_Population = (Population)pop.clone(); private void evaluatePopulation(Population population) {
if (reset) { this.m_Problem.evaluate(population);
this.m_Population.init(); population.incrGeneration();
this.evaluatePopulation(this.m_Population); }
this.firePropertyChangedEvent(Population.nextGenerationPerformed);
}
}
/** This method will evaluate the current population using the /**
* given problem. * This method will assign fitness values to all individual in the current
* @param population The population that is to be evaluated * population.
*/ *
private void evaluatePopulation(Population population) { * @param population The population that is to be evaluated
this.m_Problem.evaluate(population); */
population.incrGeneration(); private void defaultEvaluatePopulation(Population population) {
GAIndividualBinaryData tmpIndy;
for (int i = 0; i < population.size(); i++) {
tmpIndy = (GAIndividualBinaryData) population.get(i);
tmpIndy.SetFitness(0, tmpIndy.defaultEvaulateAsMiniBits());
population.incrFunctionCalls();
} }
population.incrGeneration();
}
/** This method will assign fitness values to all individual in the /**
* current population. * This method will generate the offspring population from the given
* @param population The population that is to be evaluated * population of evaluated individuals.
*/ */
private void defaultEvaluatePopulation(Population population) { private void generateChildren() {
GAIndividualBinaryData tmpIndy; this.m_ParentSelection.prepareSelection(this.m_Population);
for (int i = 0; i < population.size(); i++) { this.m_PartnerSelection.prepareSelection(this.m_Population);
tmpIndy = (GAIndividualBinaryData) population.get(i); Population parents = this.m_ParentSelection.selectFrom(this.m_Population, 1);
tmpIndy.SetFitness(0, tmpIndy.defaultEvaulateAsMiniBits()); AbstractEAIndividual mother = (AbstractEAIndividual) parents.get(0);
population.incrFunctionCalls(); parents = this.m_PartnerSelection.findPartnerFor(mother, this.m_Population, this.m_NumberOfPartners);
} AbstractEAIndividual[] offSprings = mother.mateWith(parents);
population.incrGeneration(); offSprings[0].mutate();
} this.m_Problem.evaluate(offSprings[0]);
this.m_ReplacementSelection.insertIndividual(offSprings[0], this.m_Population, parents);
/** This method will generate the offspring population from the }
* given population of evaluated individuals.
*/
private void generateChildren() {
this.m_ParentSelection.prepareSelection(this.m_Population);
this.m_PartnerSelection.prepareSelection(this.m_Population);
Population parents = this.m_ParentSelection.selectFrom(this.m_Population, 1);
AbstractEAIndividual mother = (AbstractEAIndividual)parents.get(0);
parents = this.m_PartnerSelection.findPartnerFor(mother, this.m_Population, this.m_NumberOfPartners);
AbstractEAIndividual[] offSprings = mother.mateWith(parents);
offSprings[0].mutate();
this.m_Problem.evaluate(offSprings[0]);
this.m_ReplacementSelection.insertIndividual(offSprings[0], this.m_Population, parents);
}
@Override @Override
public void optimize() { public void optimize() {
for (int i = 0; i < this.m_Population.size(); i++) { for (int i = 0; i < this.m_Population.size(); i++) {
this.generateChildren(); this.generateChildren();
}
this.m_Population.incrFunctionCallsBy(this.m_Population.size());
this.m_Population.incrGeneration();
this.firePropertyChangedEvent(Population.nextGenerationPerformed);
}
@Override
public void addPopulationChangedEventListener(InterfacePopulationChangedEventListener ea) {
this.m_Listener = ea;
}
@Override
public boolean removePopulationChangedEventListener(
InterfacePopulationChangedEventListener ea) {
if (m_Listener==ea) {
m_Listener=null;
return true;
} else {
return false;
}
}
protected void firePropertyChangedEvent (String name) {
if (this.m_Listener != null) {
this.m_Listener.registerPopulationStateChanged(this, name);
}
} }
this.m_Population.incrFunctionCallsBy(this.m_Population.size());
this.m_Population.incrGeneration();
this.firePropertyChangedEvent(Population.nextGenerationPerformed);
}
/** This method will set the problem that is to be optimized
* @param problem
*/
@Override @Override
public void setProblem (InterfaceOptimizationProblem problem) { public void addPopulationChangedEventListener(InterfacePopulationChangedEventListener ea) {
this.m_Problem = problem; this.m_Listener = ea;
} }
@Override
public InterfaceOptimizationProblem getProblem () {
return this.m_Problem;
}
/** This method will return a string describing all properties of the optimizer
* and the applied methods.
* @return A descriptive string
*/
@Override @Override
public String getStringRepresentation() { public boolean removePopulationChangedEventListener(
String result = ""; InterfacePopulationChangedEventListener ea) {
result += "Genetic Algorithm:\n"; if (m_Listener == ea) {
result += "Optimization Problem: "; m_Listener = null;
result += this.m_Problem.getStringRepresentationForProblem(this) +"\n"; return true;
result += this.m_Population.getStringRepresentation(); } else {
return result; return false;
} }
/** This method allows you to set an identifier for the algorithm }
* @param name The indenifier
*/
@Override
public void setIdentifier(String name) {
this.m_Identifier = name;
}
@Override
public String getIdentifier() {
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() {
protected void firePropertyChangedEvent(String name) {
if (this.m_Listener != null) {
this.m_Listener.registerPopulationStateChanged(this, name);
} }
/********************************************************************************************************************** }
/**
* This method will set the problem that is to be optimized
*
* @param problem
*/
@Override
public void setProblem(InterfaceOptimizationProblem problem) {
this.m_Problem = problem;
}
@Override
public InterfaceOptimizationProblem getProblem() {
return this.m_Problem;
}
/**
* This method will return a string describing all properties of the
* optimizer and the applied methods.
*
* @return A descriptive string
*/
@Override
public String getStringRepresentation() {
String result = "";
result += "Genetic Algorithm:\n";
result += "Optimization Problem: ";
result += this.m_Problem.getStringRepresentationForProblem(this) + "\n";
result += this.m_Population.getStringRepresentation();
return result;
}
/**
* This method allows you to set an identifier for the algorithm
*
* @param name The indenifier
*/
@Override
public void setIdentifier(String name) {
this.m_Identifier = name;
}
@Override
public String getIdentifier() {
return this.m_Identifier;
}
/**
* ********************************************************************************************************************
* 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,42 +214,53 @@ 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.";
} }
@Override @Override
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 /**
* @param selection * Choose a selection method for selecting recombination partners for given
*/ * parents
*
* @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,28 +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;
/** 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 int m_MultiRuns = 100;
private int m_FitnessCalls = 100;
private int m_FitnessCallsNeeded = 0;
GAIndividualBinaryData m_Best, m_Test;
public double m_InitialT = 2, m_CurrentT;
public double m_Alpha = 0.9;
private InterfaceOptimizationProblem m_Problem = new B1Problem();
private int m_MultiRuns = 100;
private int m_FitnessCalls = 100;
private int m_FitnessCallsNeeded = 0;
GAIndividualBinaryData m_Best, m_Test;
public double m_InitialT = 2, m_CurrentT;
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;
private Population m_Population; private Population m_Population;
public ThresholdAlgorithm() { public ThresholdAlgorithm() {
this.m_Population = new Population(); this.m_Population = new Population();
@@ -38,11 +35,11 @@ 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;
} }
@Override @Override
@@ -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,28 +58,31 @@ 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 /**
* @param pop The initial population * This method will init the optimizer with a given population
* @param reset If true the population is reset. *
* @param pop The initial population
* @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();
this.m_Problem.evaluate(this.m_Population); this.m_Problem.evaluate(this.m_Population);
this.firePropertyChangedEvent(Population.nextGenerationPerformed); this.firePropertyChangedEvent(Population.nextGenerationPerformed);
} }
} }
/** 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++) {
indy = ((AbstractEAIndividual) this.m_Population.get(i)); indy = ((AbstractEAIndividual) this.m_Population.get(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,13 +104,15 @@ 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 /**
* @param org The original * This method calculates the difference between the fitness values
* @param mut The mutant *
* @param org The original
* @param mut The mutant
*/ */
private double calculateDelta(AbstractEAIndividual org, AbstractEAIndividual mut) { private double calculateDelta(AbstractEAIndividual org, AbstractEAIndividual mut) {
double result = 0; double result = 0;
double[] fitOrg, fitMut; double[] fitOrg, fitMut;
fitOrg = org.getFitness(); fitOrg = org.getFitness();
fitMut = mut.getFitness(); fitMut = mut.getFitness();
for (int i = 0; i < fitOrg.length; i++) { for (int i = 0; i < fitOrg.length; i++) {
@@ -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,96 +214,112 @@ 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
* @param name The indenifier /**
* This method allows you to set an identifier for the algorithm
*
* @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
public String getIdentifier() {
return this.m_Identifier;
}
/** This method is required to free the memory on a RMIServer,
* but there is nothing to implement.
*/
@Override @Override
public void freeWilly() { public String getIdentifier() {
return this.m_Identifier;
} }
/**********************************************************************************************************************
* These are for GUI /**
*/ * ********************************************************************************************************************
/** This method returns a global info string * These are for GUI
*/
/**
* 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).";
} }
@Override @Override
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.";
} }

File diff suppressed because it is too large Load Diff

View File

@@ -11,46 +11,43 @@ 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 {
private InterfaceOptimizer m_MOOptimizer = new MultiObjectiveEA(); private InterfaceOptimizer m_MOOptimizer = new MultiObjectiveEA();
private InterfaceOptimizer m_SOOptimizer = new GeneticAlgorithm(); private InterfaceOptimizer m_SOOptimizer = new GeneticAlgorithm();
private InterfaceOptimizer[] m_SOOptimizers; private InterfaceOptimizer[] m_SOOptimizers;
private Population m_Population = new Population(); private Population m_Population = new Population();
private int m_MigrationRate = 5; private int m_MigrationRate = 5;
private int m_OutputDimension = 2; private int m_OutputDimension = 2;
private int m_NumberOfLocalOptimizers = 2; private int m_NumberOfLocalOptimizers = 2;
private InterfaceOptimizationProblem m_Problem = new FM0Problem(); private InterfaceOptimizationProblem m_Problem = new FM0Problem();
private String m_Identifier = ""; private String m_Identifier = "";
transient private InterfacePopulationChangedEventListener m_Listener; transient private InterfacePopulationChangedEventListener m_Listener;
public WingedMultiObjectiveEA() { public WingedMultiObjectiveEA() {
} }
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 reset If true the population is reset. * @param pop The initial population
* @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,75 +179,86 @@ 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() {
AbstractEAIndividual[] bestIndys = new AbstractEAIndividual[this.m_OutputDimension]; AbstractEAIndividual[] bestIndys = new AbstractEAIndividual[this.m_OutputDimension];
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);
} }
} }
} }
// 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
* @param name The indenifier /**
* This method allows you to set an identifier for the algorithm
*
* @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
public String getIdentifier() {
return this.m_Identifier;
}
/** This method is required to free the memory on a RMIServer,
* but there is nothing to implement.
*/
@Override @Override
public void freeWilly() { public String getIdentifier() {
return this.m_Identifier;
} }
/**********************************************************************************************************************
* These are for GUI /**
*/ * ********************************************************************************************************************
/** This method returns a global info string * These are for GUI
*/
/**
* 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,62 +309,79 @@ 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)";
} }
@Override @Override
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.";
} }