Some repairs (GradientDescentAlgorithm, F1 and F2 are now derivable); renamed Population.m_Size to m_TargetSize to avoid misunderstandings; Exceptions are now caught and their messages tried to display in a JOptionPane in addition to printing to System.err.

This commit is contained in:
Marcel Kronfeld 2009-11-19 16:56:28 +00:00
parent c84b1486b1
commit 88879683a4
81 changed files with 755 additions and 632 deletions

View File

@ -143,7 +143,7 @@ public class OptimizerFactory {
DifferentialEvolution de = new DifferentialEvolution(); DifferentialEvolution de = new DifferentialEvolution();
de.SetProblem(problem); de.SetProblem(problem);
de.getPopulation().setPopulationSize(popsize); de.getPopulation().setTargetSize(popsize);
de.setDEType(DETypeEnum.DE2_CurrentToBest); de.setDEType(DETypeEnum.DE2_CurrentToBest);
de.setF(f); de.setF(f);
de.setK(CR); de.setK(CR);
@ -260,7 +260,7 @@ public class OptimizerFactory {
GeneticAlgorithm ga = new GeneticAlgorithm(); GeneticAlgorithm ga = new GeneticAlgorithm();
ga.SetProblem(problem); ga.SetProblem(problem);
ga.getPopulation().setPopulationSize(popsize); ga.getPopulation().setTargetSize(popsize);
ga.setParentSelection(select); ga.setParentSelection(select);
ga.setPartnerSelection(select); ga.setPartnerSelection(select);
ga.addPopulationChangedEventListener(listener); ga.addPopulationChangedEventListener(listener);
@ -374,7 +374,7 @@ public class OptimizerFactory {
tmpIndi.setCrossoverProbability(0); tmpIndi.setCrossoverProbability(0);
HillClimbing hc = new HillClimbing(); HillClimbing hc = new HillClimbing();
hc.getPopulation().setPopulationSize(pop); hc.getPopulation().setTargetSize(pop);
hc.addPopulationChangedEventListener(listener); hc.addPopulationChangedEventListener(listener);
hc.SetProblem(problem); hc.SetProblem(problem);
hc.init(); hc.init();
@ -405,7 +405,7 @@ public class OptimizerFactory {
tmpIndi.setCrossoverProbability(0); tmpIndi.setCrossoverProbability(0);
MonteCarloSearch mc = new MonteCarloSearch(); MonteCarloSearch mc = new MonteCarloSearch();
mc.getPopulation().setPopulationSize(popsize); mc.getPopulation().setTargetSize(popsize);
mc.addPopulationChangedEventListener(listener); mc.addPopulationChangedEventListener(listener);
mc.SetProblem(problem); mc.SetProblem(problem);
mc.init(); mc.init();
@ -447,7 +447,7 @@ public class OptimizerFactory {
ParticleSwarmOptimization pso = new ParticleSwarmOptimization(); ParticleSwarmOptimization pso = new ParticleSwarmOptimization();
pso.SetProblem(problem); pso.SetProblem(problem);
pso.getPopulation().setPopulationSize(popsize); pso.getPopulation().setTargetSize(popsize);
pso.setPhi1(phi1); pso.setPhi1(phi1);
pso.setPhi2(phi2); pso.setPhi2(phi2);
pso.setSpeedLimit(k); pso.setSpeedLimit(k);
@ -493,7 +493,7 @@ public class OptimizerFactory {
sa.setAlpha(alpha); sa.setAlpha(alpha);
sa.setInitialTemperature(temperature); sa.setInitialTemperature(temperature);
sa.SetProblem(problem); sa.SetProblem(problem);
sa.getPopulation().setPopulationSize(popsize); sa.getPopulation().setTargetSize(popsize);
sa.addPopulationChangedEventListener(listener); sa.addPopulationChangedEventListener(listener);
sa.init(); sa.init();
@ -732,7 +732,7 @@ public class OptimizerFactory {
* @return * @return
*/ */
public static GOParameters makeParams(InterfaceOptimizer opt, AbstractOptimizationProblem problem, InterfaceTerminator term) { public static GOParameters makeParams(InterfaceOptimizer opt, AbstractOptimizationProblem problem, InterfaceTerminator term) {
return makeParams(opt, opt.getPopulation().getPopulationSize(), problem, randSeed, term); return makeParams(opt, opt.getPopulation().getTargetSize(), problem, randSeed, term);
} }
/** /**
* Set the population size, initialize the population and return a parameter structure containing all * Set the population size, initialize the population and return a parameter structure containing all

View File

@ -317,7 +317,7 @@ public class GOStandaloneVersion implements InterfaceGOStandalone, InterfacePopu
ga.setParentSelection(tour); ga.setParentSelection(tour);
ga.setPartnerSelection(tour); ga.setPartnerSelection(tour);
this.m_GO.setOptimizer(ga); this.m_GO.setOptimizer(ga);
this.m_GO.getOptimizer().getPopulation().setPopulationSize(100); this.m_GO.getOptimizer().getPopulation().setTargetSize(100);
F1Problem problem = new F1Problem(); F1Problem problem = new F1Problem();
tmpIndy = new GAIndividualDoubleData(); tmpIndy = new GAIndividualDoubleData();
((GAIndividualDoubleData)tmpIndy).setCrossoverOperator(new CrossoverGANPoint()); ((GAIndividualDoubleData)tmpIndy).setCrossoverOperator(new CrossoverGANPoint());
@ -335,7 +335,7 @@ public class GOStandaloneVersion implements InterfaceGOStandalone, InterfacePopu
this.m_OutputFileName = "X360_StandardES"; this.m_OutputFileName = "X360_StandardES";
EvolutionStrategies es = new EvolutionStrategies(); EvolutionStrategies es = new EvolutionStrategies();
this.m_GO.setOptimizer(es); this.m_GO.setOptimizer(es);
this.m_GO.getOptimizer().getPopulation().setPopulationSize(50); this.m_GO.getOptimizer().getPopulation().setTargetSize(50);
F1Problem problem = new F1Problem(); F1Problem problem = new F1Problem();
tmpIndy = new ESIndividualDoubleData(); tmpIndy = new ESIndividualDoubleData();
((AbstractEAIndividual)tmpIndy).setMutationOperator(new MutateESLocal()); ((AbstractEAIndividual)tmpIndy).setMutationOperator(new MutateESLocal());

View File

@ -128,7 +128,7 @@ public class MOCCOStandalone implements InterfaceGOStandalone, InterfacePopulati
while (!tmpP.isFinished()) { try { Thread.sleep(1000); } catch (java.lang.InterruptedException e) { }} while (!tmpP.isFinished()) { try { Thread.sleep(1000); } catch (java.lang.InterruptedException e) { }}
this.m_State.m_InitialPopulationSize = Math.max(1, this.m_State.m_InitialPopulationSize); this.m_State.m_InitialPopulationSize = Math.max(1, this.m_State.m_InitialPopulationSize);
Population pop = new Population(); Population pop = new Population();
pop.setPopulationSize(this.m_State.m_InitialPopulationSize); pop.setTargetSize(this.m_State.m_InitialPopulationSize);
this.m_State.m_CurrentProblem = (InterfaceOptimizationProblem) this.m_State.m_OriginalProblem.clone(); this.m_State.m_CurrentProblem = (InterfaceOptimizationProblem) this.m_State.m_OriginalProblem.clone();
this.m_State.m_CurrentProblem.initPopulation(pop); this.m_State.m_CurrentProblem.initPopulation(pop);
this.m_State.m_CurrentProblem.evaluate(pop); this.m_State.m_CurrentProblem.evaluate(pop);

View File

@ -46,7 +46,7 @@ public class ArchivingAllDominating extends AbstractArchiving implements java.io
if ((pop.getArchive().size() == 0) && (pop.size() > 0)) { if ((pop.getArchive().size() == 0) && (pop.size() > 0)) {
SelectBestIndividuals select = new SelectBestIndividuals(); SelectBestIndividuals select = new SelectBestIndividuals();
select.setObeyDebsConstViolationPrinciple(true); select.setObeyDebsConstViolationPrinciple(true);
pop.getArchive().addPopulation(select.selectFrom(pop, pop.getArchive().getPopulationSize())); pop.getArchive().addPopulation(select.selectFrom(pop, pop.getArchive().getTargetSize()));
} }
} else { } else {
// test for each element in population if it // test for each element in population if it

View File

@ -59,8 +59,8 @@ public class ArchivingMaxiMin implements InterfaceArchiving, java.io.Serializabl
this.m_MaxiMin.convertMultiObjective2SingleObjective(tmpPop); this.m_MaxiMin.convertMultiObjective2SingleObjective(tmpPop);
this.m_Selection.setObeyDebsConstViolationPrinciple(this.m_ObeyDebsConstViolationPrinciple); this.m_Selection.setObeyDebsConstViolationPrinciple(this.m_ObeyDebsConstViolationPrinciple);
this.m_Selection.prepareSelection(tmpPop); this.m_Selection.prepareSelection(tmpPop);
archive = this.m_Selection.selectFrom(tmpPop, pop.getArchive().getPopulationSize()); archive = this.m_Selection.selectFrom(tmpPop, pop.getArchive().getTargetSize());
archive.setPopulationSize(pop.getArchive().getPopulationSize()); archive.setTargetSize(pop.getArchive().getTargetSize());
// now unconvert from SO to MO // now unconvert from SO to MO
for (int i = 0; i < archive.size(); i++) { for (int i = 0; i < archive.size(); i++) {

View File

@ -74,21 +74,21 @@ public class ArchivingNSGAII extends ArchivingNSGA implements java.io.Serializab
// Now init the new archive // Now init the new archive
Population archive = new Population(); Population archive = new Population();
archive.setPopulationSize(pop.getArchive().getPopulationSize()); archive.setTargetSize(pop.getArchive().getTargetSize());
// Now add the fronts to the archive // Now add the fronts to the archive
int index = 0; int index = 0;
while ((index < fronts.length) && ((archive.size() + fronts[index].size()) < archive.getPopulationSize())) { while ((index < fronts.length) && ((archive.size() + fronts[index].size()) < archive.getTargetSize())) {
archive.addPopulation(fronts[index]); archive.addPopulation(fronts[index]);
index++; index++;
} }
if ((index < fronts.length) && (archive.size() < archive.getPopulationSize())) { if ((index < fronts.length) && (!archive.targetSizeReached())) {
// In this case there are still elements left in the front which could be added to the archive! // In this case there are still elements left in the front which could be added to the archive!
// and there is still some place left in the archive // and there is still some place left in the archive
// therefore we could add some individuals from front[index] // therefore we could add some individuals from front[index]
// to the archive using the crowding distance sorting // to the archive using the crowding distance sorting
fronts[index].setPopulationSize(archive.getPopulationSize() - archive.size()); fronts[index].setTargetSize(archive.getTargetSize() - archive.size());
this.m_Cleaner.removeSurplusIndividuals(fronts[index]); this.m_Cleaner.removeSurplusIndividuals(fronts[index]);
archive.addPopulation(fronts[index]); archive.addPopulation(fronts[index]);
} }

View File

@ -136,7 +136,7 @@ public class ArchivingPESAII extends AbstractArchiving implements java.io.Serial
// Now check whether there are individuals to remove // Now check whether there are individuals to remove
int bigSqueeze, index; int bigSqueeze, index;
int[] squeezeFactor; int[] squeezeFactor;
while(archive.size() > archive.getPopulationSize()) { while(archive.targetSizeExceeded()) {
squeezeFactor = this.calculateSqueezeFactor(archive); squeezeFactor = this.calculateSqueezeFactor(archive);
bigSqueeze = 0; bigSqueeze = 0;
index = -1; index = -1;

View File

@ -98,7 +98,7 @@ public class ArchivingSPEAII extends AbstractArchiving implements java.io.Serial
// Now init the new archive // Now init the new archive
Population archive = new Population(); Population archive = new Population();
archive.setPopulationSize(pop.getArchive().getPopulationSize()); archive.setTargetSize(pop.getArchive().getTargetSize());
// archive = this.m_Selection.selectFrom(tmpPop, archive.getPopulationSize()); // archive = this.m_Selection.selectFrom(tmpPop, archive.getPopulationSize());
@ -160,7 +160,7 @@ public class ArchivingSPEAII extends AbstractArchiving implements java.io.Serial
// if there is some place left let's add some more // if there is some place left let's add some more
int currentLevel = 0; int currentLevel = 0;
while (archive.size() < archive.getPopulationSize()) { while (!archive.targetSizeReached()) {
currentLevel++; currentLevel++;
for (int i = 0; i < RawFitness.length; i++) { for (int i = 0; i < RawFitness.length; i++) {
if ((RawFitness[i] >= currentLevel) && (RawFitness[i] < currentLevel +1)) { if ((RawFitness[i] >= currentLevel) && (RawFitness[i] < currentLevel +1)) {
@ -194,7 +194,7 @@ public class ArchivingSPEAII extends AbstractArchiving implements java.io.Serial
// RawFitness for the lowest kthDistance()!!! // RawFitness for the lowest kthDistance()!!!
int ICurSma; int ICurSma;
double curSmall, highestLevel; double curSmall, highestLevel;
while (archive.size() > archive.getPopulationSize()) { while (archive.targetSizeExceeded()) {
highestLevel = 0; highestLevel = 0;
RawFitness = this.calculateRawFitness(archive); RawFitness = this.calculateRawFitness(archive);
for (int i = 0; i < RawFitness.length; i++) { for (int i = 0; i < RawFitness.length; i++) {

View File

@ -31,9 +31,9 @@ public class InformationRetrievalInserting implements InterfaceInformationRetrie
Population archive = pop.getArchive(); Population archive = pop.getArchive();
if (archive == null) return; if (archive == null) return;
if (archive.size() < pop.getPopulationSize()) { if (archive.size() < pop.getTargetSize()) {
// remove archive size individuals from pop // remove archive size individuals from pop
pop.removeNIndividuals(archive.size()-(pop.getPopulationSize()-pop.size())); pop.removeNIndividuals(archive.size()-(pop.getTargetSize()-pop.size()));
} else { } else {
pop.clear(); pop.clear();
} }

View File

@ -33,7 +33,7 @@ public class InformationRetrievalReplacing implements InterfaceInformationRetrie
Population tmp = new Population(); Population tmp = new Population();
tmp.addPopulation(archive); tmp.addPopulation(archive);
while (tmp.size() < archive.getPopulationSize()) { while (tmp.size() < archive.getTargetSize()) {
tmp.add(pop.get(RNG.randomInt(0,pop.size()-1))); tmp.add(pop.get(RNG.randomInt(0,pop.size()-1)));
} }

View File

@ -35,7 +35,7 @@ public class RemoveSurplusIndividualsDynamicHyperCube implements InterfaceRemove
double[][] fitness; double[][] fitness;
double[] space; double[] space;
int indexSmallHyperCube; int indexSmallHyperCube;
while(archive.size() > archive.getPopulationSize()) { while(archive.targetSizeExceeded()) {
// select the individual with the least space around him // select the individual with the least space around him
// to do this i got to find the next smaller and the next bigger one // to do this i got to find the next smaller and the next bigger one
fitness = new double[archive.size()][]; fitness = new double[archive.size()][];

View File

@ -47,7 +47,7 @@ public class RemoveSurplusIndividualsStaticHyperCube extends RemoveSurplusIndivi
((AbstractEAIndividual)archive.get(i)).putData("HyperCube", new Double(space[i])); ((AbstractEAIndividual)archive.get(i)).putData("HyperCube", new Double(space[i]));
} }
while(archive.size() > archive.getPopulationSize()) { while(archive.targetSizeExceeded()) {
// select the individual with the least space around him // select the individual with the least space around him
// to do this i got to find the next smaller and the next bigger one // to do this i got to find the next smaller and the next bigger one
smallestHyperCube = ((Double)((AbstractEAIndividual)archive.get(0)).getData("HyperCube")).doubleValue(); smallestHyperCube = ((Double)((AbstractEAIndividual)archive.get(0)).getData("HyperCube")).doubleValue();

View File

@ -273,7 +273,7 @@ public class ClusteringXMeans implements InterfaceClustering, java.io.Serializab
ckm.setUseSearchSpace(true); ckm.setUseSearchSpace(true);
ckm.m_Debug = true; ckm.m_Debug = true;
Population pop = new Population(); Population pop = new Population();
pop.setPopulationSize(100); pop.setTargetSize(100);
F1Problem f1 = new F1Problem(); F1Problem f1 = new F1Problem();
f1.setProblemDimension(2); f1.setProblemDimension(2);
f1.setEAIndividual(new ESIndividualDoubleData()); f1.setEAIndividual(new ESIndividualDoubleData());

View File

@ -96,7 +96,7 @@ public class TestESCrossover implements java.io.Serializable {
ActionListener initListener = new ActionListener() { ActionListener initListener = new ActionListener() {
public void actionPerformed(ActionEvent event) { public void actionPerformed(ActionEvent event) {
m_Partners = new Population(); m_Partners = new Population();
m_Partners.setPopulationSize(m_NumberOfPartners); m_Partners.setTargetSize(m_NumberOfPartners);
m_Partners.clear(); m_Partners.clear();
InterfaceDataTypeDouble tmpIndyD = new ESIndividualDoubleData(); InterfaceDataTypeDouble tmpIndyD = new ESIndividualDoubleData();
@ -108,7 +108,7 @@ public class TestESCrossover implements java.io.Serializable {
} }
tmpIndyD.setDoubleDataLength(m_Dimension); tmpIndyD.setDoubleDataLength(m_Dimension);
tmpIndyD.SetDoubleRange(newRange); tmpIndyD.SetDoubleRange(newRange);
for (int i = 0; i < m_Partners.getPopulationSize(); i++) { for (int i = 0; i < m_Partners.getTargetSize(); i++) {
tmpIndyEA = (AbstractEAIndividual)((AbstractEAIndividual)tmpIndyD).clone(); tmpIndyEA = (AbstractEAIndividual)((AbstractEAIndividual)tmpIndyD).clone();
tmpIndyEA.init(m_Problem); tmpIndyEA.init(m_Problem);
m_Partners.add(tmpIndyEA); m_Partners.add(tmpIndyEA);
@ -134,7 +134,7 @@ public class TestESCrossover implements java.io.Serializable {
ActionListener init2Listener = new ActionListener() { ActionListener init2Listener = new ActionListener() {
public void actionPerformed(ActionEvent event) { public void actionPerformed(ActionEvent event) {
m_Partners = new Population(); m_Partners = new Population();
m_Partners.setPopulationSize(2); m_Partners.setTargetSize(2);
m_Partners.clear(); m_Partners.clear();
InterfaceDataTypeDouble tmpIndyD = new ESIndividualDoubleData(); InterfaceDataTypeDouble tmpIndyD = new ESIndividualDoubleData();
@ -177,7 +177,7 @@ public class TestESCrossover implements java.io.Serializable {
ActionListener init3Listener = new ActionListener() { ActionListener init3Listener = new ActionListener() {
public void actionPerformed(ActionEvent event) { public void actionPerformed(ActionEvent event) {
m_Partners = new Population(); m_Partners = new Population();
m_Partners.setPopulationSize(3); m_Partners.setTargetSize(3);
m_Partners.clear(); m_Partners.clear();
InterfaceDataTypeDouble tmpIndyD = new ESIndividualDoubleData(); InterfaceDataTypeDouble tmpIndyD = new ESIndividualDoubleData();

View File

@ -0,0 +1,75 @@
package eva2.server.go.operators.distancemetric;
import java.io.Serializable;
import eva2.server.go.individuals.AbstractEAIndividual;
import eva2.server.go.individuals.InterfaceDataTypeDouble;
import eva2.server.go.strategies.ParticleSwarmOptimization;
/**
* Define a metric on data stored within individuals, such as the personal best position
* in PSO.
* @author mkron
*
*/
public class IndividualDataMetric implements InterfaceDistanceMetric, Serializable {
private String dataKey = ParticleSwarmOptimization.partBestPosKey;
private boolean normedDistance = true; // flag whether to use normed distances (for InterfaceDataTypeDouble)
public IndividualDataMetric() {}
public IndividualDataMetric(String key) {
dataKey = key;
}
public IndividualDataMetric(IndividualDataMetric pBestMetric) {
// TODO Auto-generated constructor stub
}
/** This method allows you to make a deep clone of
* the object
* @return the deep clone
*/
public Object clone() {
return new IndividualDataMetric(this);
}
public double distance(AbstractEAIndividual indy1, AbstractEAIndividual indy2) {
if (dataKey==null) throw new RuntimeException("Error, no data key defined in " + this.getClass().getName() + "::distance()");
else {
Object data1 = indy1.getData(dataKey);
Object data2 = indy2.getData(dataKey);
if (data1 instanceof double[] && (data2 instanceof double[])) {
if (normedDistance) {
double[][] range1 = ((InterfaceDataTypeDouble)indy1).getDoubleRange();
double[][] range2 = ((InterfaceDataTypeDouble)indy2).getDoubleRange();
return EuclideanMetric.normedEuclideanDistance((double[])data1, range1, (double[])data2, range2);
} else return EuclideanMetric.euclideanDistance((double[])data1, (double[])data2);
} else throw new RuntimeException("Error, invalid key data, double array required by " + this.getClass().getName());
}
}
public String dataKeyTipText() {
return "Name of the data key to use to retrieve individual data (double[] for now).";
}
public String getDataKey() {
return dataKey;
}
public void setDataKey(String dataKey) {
this.dataKey = dataKey;
}
public String normedDistanceTipText() {
return "Flag whether to use euclidean distance directly or normed by the double range.";
}
public boolean isNormedDistance() {
return normedDistance;
}
public void setNormedDistance(boolean normedDistance) {
this.normedDistance = normedDistance;
}
public String globalInfo() {
return "Uses individual object data (so far only double[]) to calculate the distance.";
}
}

View File

@ -217,8 +217,8 @@ public class MOClusteringSeparation implements InterfaceMigration, java.io.Seria
oldIPOP[i].clear(); oldIPOP[i].clear();
oldIPOP[i].addPopulation(newIPOP[i]); oldIPOP[i].addPopulation(newIPOP[i]);
// todo remove this for nice pictures // todo remove this for nice pictures
if (oldIPOP[i].size() < oldIPOP[i].getPopulationSize()) { if (!oldIPOP[i].targetSizeReached()) {
oldIPOP[i].addPopulation(this.m_Selection.selectFrom(memory, oldIPOP[i].getPopulationSize()-oldIPOP[i].size())); oldIPOP[i].addPopulation(this.m_Selection.selectFrom(memory, oldIPOP[i].getTargetSize()-oldIPOP[i].size()));
} }
if (this.m_Debug) System.out.println("Setting "+i+" to population size " + oldIPOP[i].size()); if (this.m_Debug) System.out.println("Setting "+i+" to population size " + oldIPOP[i].size());
islands[i].setPopulation(oldIPOP[i]); islands[i].setPopulation(oldIPOP[i]);

View File

@ -111,8 +111,8 @@ public class MOConeSeparation implements InterfaceMigration, java.io.Serializabl
oldIPOP[i].clear(); oldIPOP[i].clear();
oldIPOP[i].addPopulation(newIPOP[i]); oldIPOP[i].addPopulation(newIPOP[i]);
// todo remove this for nice pictures // todo remove this for nice pictures
if (oldIPOP[i].size() < oldIPOP[i].getPopulationSize()) { if (!oldIPOP[i].targetSizeReached()) {
oldIPOP[i].addPopulation(this.m_Selection.selectFrom(memory, oldIPOP[i].getPopulationSize()-oldIPOP[i].size())); oldIPOP[i].addPopulation(this.m_Selection.selectFrom(memory, oldIPOP[i].getTargetSize()-oldIPOP[i].size()));
} }
if (this.m_Debug) System.out.println("Setting island "+i+" to population size " + oldIPOP[i].size()); if (this.m_Debug) System.out.println("Setting island "+i+" to population size " + oldIPOP[i].size());
allDom.addElementsToArchive(oldIPOP[i]); allDom.addElementsToArchive(oldIPOP[i]);

View File

@ -137,7 +137,7 @@ public class MOXMeansSeparation implements InterfaceMigration, java.io.Serializa
newIPOP = this.m_XMeans.cluster(collector, c); newIPOP = this.m_XMeans.cluster(collector, c);
for (int i = 0; i < islands.length; i++) { for (int i = 0; i < islands.length; i++) {
islands[i].getPopulation().clear(); islands[i].getPopulation().clear();
islands[i].getPopulation().setPopulationSize(0); islands[i].getPopulation().setTargetSize(0);
} }
if (this.m_Debug) { if (this.m_Debug) {
Plot plot; Plot plot;
@ -218,12 +218,12 @@ public class MOXMeansSeparation implements InterfaceMigration, java.io.Serializa
oldIPOP[i].clear(); oldIPOP[i].clear();
oldIPOP[i].addPopulation(newIPOP[i]); oldIPOP[i].addPopulation(newIPOP[i]);
// todo remove this for nice pictures // todo remove this for nice pictures
if (oldIPOP[i].size() < oldIPOP[i].getPopulationSize()) { if (!oldIPOP[i].targetSizeReached()) {
oldIPOP[i].addPopulation(this.m_Selection.selectFrom(memory, oldIPOP[i].getPopulationSize()-oldIPOP[i].size())); oldIPOP[i].addPopulation(this.m_Selection.selectFrom(memory, oldIPOP[i].getFreeSlots()));
} }
if (this.m_Debug) System.out.println("Setting "+i+" to population size " + oldIPOP[i].size()); if (this.m_Debug) System.out.println("Setting "+i+" to population size " + oldIPOP[i].size());
islands[i].setPopulation(oldIPOP[i]); islands[i].setPopulation(oldIPOP[i]);
islands[i].getPopulation().setPopulationSize(oldIPOP[i].size()); islands[i].getPopulation().setTargetSize(oldIPOP[i].size());
} }
} }

View File

@ -413,6 +413,7 @@ public class MutateESRankMuCMA implements InterfaceMutationGenerational, Seriali
} }
if (TRACE_1) { if (TRACE_1) {
System.out.println("sigma=" + params.sigma);
System.out.print("psLen=" + (psNorm) + " "); System.out.print("psLen=" + (psNorm) + " ");
outputParams(params, mu); outputParams(params, mu);
} }

View File

@ -105,7 +105,7 @@ public class MetricSWithReference implements InterfaceParetoFrontMetric, java.io
if (this.m_ReferenceSMetric < 0) { if (this.m_ReferenceSMetric < 0) {
Population tmpPop = new Population(); Population tmpPop = new Population();
AbstractEAIndividual tmpIndy; AbstractEAIndividual tmpIndy;
tmpPop.setPopulationSize(this.m_Reference.length); tmpPop.setTargetSize(this.m_Reference.length);
tmpPop.clear(); tmpPop.clear();
for (int i = 0; i < this.m_Reference.length; i++) { for (int i = 0; i < this.m_Reference.length; i++) {
tmpIndy = new ESIndividualDoubleData(); tmpIndy = new ESIndividualDoubleData();

View File

@ -134,7 +134,7 @@ public class PostProcess {
for (int i=0; i<optsFound.length; i++) { for (int i=0; i<optsFound.length; i++) {
if (optsFound[i] != null) result.add(optsFound[i]); if (optsFound[i] != null) result.add(optsFound[i]);
} }
result.setPopulationSize(result.size()); result.synchSize();
return result; return result;
} }
@ -212,7 +212,7 @@ public class PostProcess {
} }
} }
} }
result.setPopulationSize(result.size()); result.synchSize();
return result; return result;
} }
@ -387,8 +387,8 @@ public class PostProcess {
hc.SetProblem(problem); hc.SetProblem(problem);
mute.init(problem.getIndividualTemplate(), problem); mute.init(problem.getIndividualTemplate(), problem);
hc.SetMutationOperator(mute); hc.SetMutationOperator(mute);
if (pop.size() != pop.getPopulationSize()) { if (pop.size() != pop.getTargetSize()) {
System.err.println(pop.size() + " vs. "+ pop.getPopulationSize()); System.err.println(pop.size() + " vs. "+ pop.getTargetSize());
System.err.println("warning: population size and vector size dont match! (PostProcess::processWithHC)"); System.err.println("warning: population size and vector size dont match! (PostProcess::processWithHC)");
} }
hc.setPopulation(pop); hc.setPopulation(pop);

View File

@ -47,7 +47,7 @@ public class SelectAll implements InterfaceSelection, java.io.Serializable {
*/ */
public Population selectFrom(Population population, int size) { public Population selectFrom(Population population, int size) {
Population result = new Population(); Population result = new Population();
result.setPopulationSize(size); result.setTargetSize(size);
if (this.m_ObeyDebsConstViolationPrinciple) { if (this.m_ObeyDebsConstViolationPrinciple) {
int index = 0; int index = 0;
while (result.size() < size) { while (result.size() < size) {

View File

@ -52,7 +52,7 @@ public class SelectBestSingle implements InterfaceSelection, java.io.Serializabl
double currentBestValue; double currentBestValue;
critSize = ((AbstractEAIndividual)population.get(0)).getFitness().length; critSize = ((AbstractEAIndividual)population.get(0)).getFitness().length;
result.setPopulationSize(size); result.setTargetSize(size);
if (this.m_ObeyDebsConstViolationPrinciple) { if (this.m_ObeyDebsConstViolationPrinciple) {
for (int i = 0; i < size; i++) { for (int i = 0; i < size; i++) {
currentCriteria = RNG.randomInt(0, critSize-1); currentCriteria = RNG.randomInt(0, critSize-1);

View File

@ -54,7 +54,7 @@ public class SelectMONSGAIICrowedTournament implements InterfaceSelection, java.
*/ */
public Population selectFrom(Population population, int size) { public Population selectFrom(Population population, int size) {
Population result = new Population(); Population result = new Population();
result.setPopulationSize(size); result.setTargetSize(size);
for (int i = 0; i < size; i++) { for (int i = 0; i < size; i++) {
result.add(this.select(population)); result.add(this.select(population));
} }

View File

@ -52,7 +52,7 @@ public class SelectMOPESA implements InterfaceSelection, java.io.Serializable {
*/ */
public Population selectFrom(Population population, int size) { public Population selectFrom(Population population, int size) {
Population result = new Population(); Population result = new Population();
result.setPopulationSize(size); result.setTargetSize(size);
for (int i = 0; i < size; i++) { for (int i = 0; i < size; i++) {
result.add(this.select(population)); result.add(this.select(population));
} }

View File

@ -86,7 +86,7 @@ public class SelectMOPESAII implements InterfaceSelection, java.io.Serializable
*/ */
public Population selectFrom(Population population, int size) { public Population selectFrom(Population population, int size) {
Population result = new Population(); Population result = new Population();
result.setPopulationSize(size); result.setTargetSize(size);
for (int i = 0; i < size; i++) { for (int i = 0; i < size; i++) {
result.add(this.select(population)); result.add(this.select(population));
} }

View File

@ -63,7 +63,7 @@ public class SelectParticleWheel implements InterfaceSelection, java.io.Serializ
*/ */
public Population selectFrom(Population population, int size) { public Population selectFrom(Population population, int size) {
Population result = new Population(); Population result = new Population();
result.setPopulationSize(size); result.setTargetSize(size);
if (selectFixedSteps ) selectFixed(population, size, result); if (selectFixedSteps ) selectFixed(population, size, result);
else selectDrawIndependent(population, size, result); else selectDrawIndependent(population, size, result);

View File

@ -55,7 +55,7 @@ public class SelectRandom implements InterfaceSelection, java.io.Serializable {
*/ */
public Population selectFrom(Population population, int size) { public Population selectFrom(Population population, int size) {
Population result = new Population(); Population result = new Population();
result.setPopulationSize(size); result.setTargetSize(size);
if (this.m_ObeyDebsConstViolationPrinciple) { if (this.m_ObeyDebsConstViolationPrinciple) {
int index = 0, rand; int index = 0, rand;
while (result.size() < size) { while (result.size() < size) {

View File

@ -50,7 +50,7 @@ public class SelectTournament implements InterfaceSelection, java.io.Serializabl
*/ */
public Population selectFrom(Population population, int size) { public Population selectFrom(Population population, int size) {
Population result = new Population(); Population result = new Population();
result.setPopulationSize(size); result.setTargetSize(size);
for (int i = 0; i < size; i++) { for (int i = 0; i < size; i++) {
result.add(this.select(population)); result.add(this.select(population));
} }

View File

@ -95,7 +95,7 @@ public class SelectXProbRouletteWheel implements InterfaceSelection, java.io.Ser
*/ */
public Population selectFrom(Population population, int size) { public Population selectFrom(Population population, int size) {
Population result = new Population(); Population result = new Population();
result.setPopulationSize(size); result.setTargetSize(size);
if (true) { if (true) {
//this.m_TreeRoot = this.buildSelectionTree(population); //this.m_TreeRoot = this.buildSelectionTree(population);

View File

@ -29,12 +29,8 @@ public class PBILPopulation extends Population implements Cloneable, java.io.Ser
} }
public PBILPopulation(PBILPopulation population) { public PBILPopulation(PBILPopulation population) {
this.m_Generation = population.m_Generation; super(population);
this.m_FunctionCalls = population.m_FunctionCalls;
this.m_Size = population.m_Size;
for (int i = 0; i < population.size(); i++) {
this.add((((AbstractEAIndividual)population.get(i))).clone());
}
this.m_ProbabilityVector = new double[population.m_ProbabilityVector.length]; this.m_ProbabilityVector = new double[population.m_ProbabilityVector.length];
for (int i = 0; i < this.m_ProbabilityVector.length; i++) { for (int i = 0; i < this.m_ProbabilityVector.length; i++) {
this.m_ProbabilityVector[i] = population.m_ProbabilityVector[i]; this.m_ProbabilityVector[i] = population.m_ProbabilityVector[i];
@ -86,7 +82,7 @@ public class PBILPopulation extends Population implements Cloneable, java.io.Ser
BitSet tmpBitSet; BitSet tmpBitSet;
this.clear(); this.clear();
for (int i = 0; i < this.m_Size; i++) { for (int i = 0; i < this.getTargetSize(); i++) {
tmpIndy = (InterfaceGAIndividual)((AbstractEAIndividual)template).clone(); tmpIndy = (InterfaceGAIndividual)((AbstractEAIndividual)template).clone();
tmpBitSet = tmpIndy.getBGenotype(); tmpBitSet = tmpIndy.getBGenotype();
for (int j = 0; j < this.m_ProbabilityVector.length; j++) { for (int j = 0; j < this.m_ProbabilityVector.length; j++) {

View File

@ -47,7 +47,7 @@ public class Population extends ArrayList implements PopulationInterface, Clonea
protected int m_Generation = 0; protected int m_Generation = 0;
protected int m_FunctionCalls = 0; protected int m_FunctionCalls = 0;
protected int m_Size = 50; protected int m_TargetSize = 50;
protected Population m_Archive = null; protected Population m_Archive = null;
PopulationInitMethod initMethod = PopulationInitMethod.individualDefault; PopulationInitMethod initMethod = PopulationInitMethod.individualDefault;
transient private ArrayList<InterfacePopulationChangedEventListener> listeners = null; transient private ArrayList<InterfacePopulationChangedEventListener> listeners = null;
@ -86,7 +86,7 @@ public class Population extends ArrayList implements PopulationInterface, Clonea
*/ */
public Population(int initialCapacity) { public Population(int initialCapacity) {
super(initialCapacity); super(initialCapacity);
setPopulationSize(initialCapacity); setTargetSize(initialCapacity);
} }
public Population(Population population) { public Population(Population population) {
@ -110,7 +110,7 @@ public class Population extends ArrayList implements PopulationInterface, Clonea
public void setSameParams(Population population) { public void setSameParams(Population population) {
this.m_Generation = population.m_Generation; this.m_Generation = population.m_Generation;
this.m_FunctionCalls = population.m_FunctionCalls; this.m_FunctionCalls = population.m_FunctionCalls;
this.m_Size = population.m_Size; this.m_TargetSize = population.m_TargetSize;
this.useHistory = population.useHistory; this.useHistory = population.useHistory;
this.notifyEvalInterval = population.notifyEvalInterval; this.notifyEvalInterval = population.notifyEvalInterval;
// this.m_Listener = population.m_Listener; // this.m_Listener = population.m_Listener;
@ -196,15 +196,13 @@ public class Population extends ArrayList implements PopulationInterface, Clonea
* are reset and m_Size default Individuals are created and initialized by * are reset and m_Size default Individuals are created and initialized by
* the GAIndividual default init() method. * the GAIndividual default init() method.
*/ */
public void defaultInitPopulation() { public void defaultInit(AbstractEAIndividual template) {
GAIndividualBinaryData tmpIndy;
this.m_Generation = 0; this.m_Generation = 0;
this.m_FunctionCalls = 0; this.m_FunctionCalls = 0;
this.m_Archive = null; this.m_Archive = null;
this.clear(); this.clear();
for (int i = 0; i < this.m_Size; i++) { for (int i = 0; i < this.m_TargetSize; i++) {
tmpIndy = new GAIndividualBinaryData(); AbstractEAIndividual tmpIndy = (AbstractEAIndividual)template.clone();
tmpIndy.defaultInit(); tmpIndy.defaultInit();
super.add(tmpIndy); super.add(tmpIndy);
} }
@ -239,8 +237,8 @@ public class Population extends ArrayList implements PopulationInterface, Clonea
return; return;
} }
AbstractEAIndividual template = pop.getEAIndividual(0); AbstractEAIndividual template = pop.getEAIndividual(0);
if (fillPop && (pop.size()<pop.getPopulationSize())) { if (fillPop && (pop.size()<pop.getTargetSize())) {
for (int i=pop.size(); i<pop.getPopulationSize(); i++) pop.add((AbstractEAIndividual)template.clone()); for (int i=pop.size(); i<pop.getTargetSize(); i++) pop.add((AbstractEAIndividual)template.clone());
} }
if (template instanceof InterfaceDataTypeDouble) { if (template instanceof InterfaceDataTypeDouble) {
double[][] range = ((InterfaceDataTypeDouble)template).getDoubleRange(); double[][] range = ((InterfaceDataTypeDouble)template).getDoubleRange();
@ -695,7 +693,7 @@ public class Population extends ArrayList implements PopulationInterface, Clonea
public Population getSortedBestFirst() { public Population getSortedBestFirst() {
Population result = this.cloneWithoutInds(); Population result = this.cloneWithoutInds();
getSortedNIndividuals(size(), true, result); getSortedNIndividuals(size(), true, result);
result.setPopulationSize(result.size()); result.synchSize();
return result; return result;
} }
@ -741,7 +739,7 @@ public class Population extends ArrayList implements PopulationInterface, Clonea
for (int i = skip; i < skip+n; i++) { for (int i = skip; i < skip+n; i++) {
res.add(sorted.get(i)); res.add(sorted.get(i));
} }
res.setPopulationSize(res.size()); res.synchSize();
} }
/** /**
@ -1041,7 +1039,7 @@ public class Population extends ArrayList implements PopulationInterface, Clonea
} }
public String getName() { public String getName() {
return "Population-"+getPopulationSize(); return "Population-"+getTargetSize();
} }
/** /**
@ -1094,8 +1092,8 @@ public class Population extends ArrayList implements PopulationInterface, Clonea
* *
* @param size * @param size
*/ */
public void setPopulationSize(int size) { public void setTargetSize(int size) {
this.m_Size = size; this.m_TargetSize = size;
} }
/** /**
@ -1104,16 +1102,16 @@ public class Population extends ArrayList implements PopulationInterface, Clonea
* @param size * @param size
* @return * @return
*/ */
public Population setPopSize(int size) { public Population setTargetPopSize(int size) {
this.m_Size = size; setTargetSize(size);
return this; return this;
} }
public int getPopulationSize() { public int getTargetSize() {
return this.m_Size; return this.m_TargetSize;
} }
public String populationSizeTipText() { public String targetSizeTipText() {
return "The population size."; return "The initial population size.";
} }
public AbstractEAIndividual getEAIndividual(int i) { public AbstractEAIndividual getEAIndividual(int i) {
return (AbstractEAIndividual)this.get(i); return (AbstractEAIndividual)this.get(i);
@ -1255,7 +1253,7 @@ public class Population extends ArrayList implements PopulationInterface, Clonea
double d; double d;
double[] res = new double[3]; double[] res = new double[3];
double meanDist = 0.; double distSum = 0.;
double maxDist = Double.MIN_VALUE; double maxDist = Double.MIN_VALUE;
double minDist = Double.MAX_VALUE; double minDist = Double.MAX_VALUE;
@ -1264,14 +1262,14 @@ public class Population extends ArrayList implements PopulationInterface, Clonea
if (metric == null) d = EuclideanMetric.euclideanDistance(AbstractEAIndividual.getDoublePositionShallow(getEAIndividual(i)), if (metric == null) d = EuclideanMetric.euclideanDistance(AbstractEAIndividual.getDoublePositionShallow(getEAIndividual(i)),
AbstractEAIndividual.getDoublePositionShallow(getEAIndividual(j))); AbstractEAIndividual.getDoublePositionShallow(getEAIndividual(j)));
else d = metric.distance((AbstractEAIndividual)this.get(i), (AbstractEAIndividual)this.get(j)); else d = metric.distance((AbstractEAIndividual)this.get(i), (AbstractEAIndividual)this.get(j));
meanDist += d; distSum += d;
if (d < minDist) minDist = d; if (d < minDist) minDist = d;
if (d > maxDist) maxDist = d; if (d > maxDist) maxDist = d;
} }
} }
res[1] = minDist; res[1] = minDist;
res[2] = maxDist; res[2] = maxDist;
if (this.size() > 1) res[0] = meanDist / (this.size() * (this.size()-1) / 2); if (this.size() > 1) res[0] = distSum / (this.size() * (this.size()-1) / 2);
else { // only one indy? else { // only one indy?
res[1]=0; res[1]=0;
res[2]=0; res[2]=0;
@ -1496,14 +1494,14 @@ public class Population extends ArrayList implements PopulationInterface, Clonea
* this method cannot grow, of course. * this method cannot grow, of course.
*/ */
public void fitToSize() { public void fitToSize() {
if (size() != getPopulationSize()) { if (size() != getTargetSize()) {
while (size() > getPopulationSize()) remove(size()-1); while (size() > getTargetSize()) remove(size()-1);
if (size() < getPopulationSize()) { if (size() < getTargetSize()) {
if (size() == 0) System.err.println("Cannot grow empty population!"); if (size() == 0) System.err.println("Cannot grow empty population!");
else { else {
int origSize=size(); int origSize=size();
int k=0; int k=0;
while (size()< getPopulationSize()) { while (size()< getTargetSize()) {
addIndividual((AbstractEAIndividual)getEAIndividual(k%origSize).clone()); addIndividual((AbstractEAIndividual)getEAIndividual(k%origSize).clone());
} }
} }
@ -1530,7 +1528,7 @@ public class Population extends ArrayList implements PopulationInterface, Clonea
* *
*/ */
public void synchSize() { public void synchSize() {
setPopulationSize(size()); setTargetSize(size());
} }
/** /**
@ -1577,6 +1575,30 @@ public class Population extends ArrayList implements PopulationInterface, Clonea
// else return ((hashes.head().equals(evaluationTimeHashes.head())) && (hashes.tail().equals(evaluationTimeHashes.tail())) && (evaluationTimeModCount == modCount)); // else return ((hashes.head().equals(evaluationTimeHashes.head())) && (hashes.tail().equals(evaluationTimeHashes.tail())) && (evaluationTimeModCount == modCount));
// } // }
/**
* Return true if the targeted size of the population has been reached.
*/
public boolean targetSizeReached() {
return this.size()>=this.getTargetSize();
}
/**
* Return true if the targeted size of the population has been exceeded.
*/
public boolean targetSizeExceeded() {
return this.size()>this.getTargetSize();
}
/**
* Return the number of free individual slots until the target size is reached.
* Returns zero if the target size is already reached or exceeded.
*
* @return
*/
public int getFreeSlots() {
return Math.max(0, this.getTargetSize() - this.size());
}
// /** // /**
// * Mark the population at the current state as evaluated. Changes to the modCount or hashes of individuals // * Mark the population at the current state as evaluated. Changes to the modCount or hashes of individuals
// * will invalidate the mark. // * will invalidate the mark.

View File

@ -158,7 +158,7 @@ public abstract class AbstractDynTransProblem extends AbstractSynchronousOptimiz
this.prob = prob; this.prob = prob;
/* to get the right values for problemDimension and Range */ /* to get the right values for problemDimension and Range */
Population pop = new Population(); Population pop = new Population();
pop.setPopulationSize(1); pop.setTargetSize(1);
prob.initPopulation(pop); prob.initPopulation(pop);
AbstractEAIndividual indy = (AbstractEAIndividual)pop.get(0); AbstractEAIndividual indy = (AbstractEAIndividual)pop.get(0);
if (indy instanceof InterfaceDataTypeDouble) { if (indy instanceof InterfaceDataTypeDouble) {

View File

@ -79,7 +79,7 @@ public abstract class AbstractMultiModalProblemKnown extends AbstractProblemDoub
// this.m_ProblemDimension = 2; // this.m_ProblemDimension = 2;
((InterfaceDataTypeDouble)this.m_Template).setDoubleDataLength(this.m_ProblemDimension); ((InterfaceDataTypeDouble)this.m_Template).setDoubleDataLength(this.m_ProblemDimension);
((InterfaceDataTypeDouble)this.m_Template).SetDoubleRange(makeRange()); ((InterfaceDataTypeDouble)this.m_Template).SetDoubleRange(makeRange());
for (int i = 0; i < population.getPopulationSize(); i++) { for (int i = 0; i < population.getTargetSize(); i++) {
tmpIndy = (AbstractEAIndividual)((AbstractEAIndividual)this.m_Template).clone(); tmpIndy = (AbstractEAIndividual)((AbstractEAIndividual)this.m_Template).clone();
tmpIndy.init(this); tmpIndy.init(this);
population.add(tmpIndy); population.add(tmpIndy);

View File

@ -182,67 +182,21 @@ public abstract class AbstractMultiObjectiveOptimizationProblem extends Abstract
this.m_ParetoFront = new Population(); this.m_ParetoFront = new Population();
} }
/** This method evaluates a given population and set the fitness values public void evaluatePopulationStart(Population population) {
* accordingly super.evaluatePopulationStart(population);
* @param population The population that is to be evaluated. if (this.m_Show && (this.m_Plot==null)) this.initProblemFrame();
*/ }
public void evaluate(Population population) {
AbstractEAIndividual tmpIndy;
double[] fitness;
evaluatePopulationStart(population); public void evaluatePopulationEnd(Population population) {
super.evaluatePopulationEnd(population);
double[] fitness;
for (int i = 0; i < population.size(); i++) {
if (this.parallelthreads > 1) { // check and update border if necessary
Vector<AbstractEAIndividual> queue = new Vector<AbstractEAIndividual>(); AbstractEAIndividual tmpIndy = (AbstractEAIndividual) population.get(i);
Vector<AbstractEAIndividual> finished = new Vector<AbstractEAIndividual>();
queue.addAll(population);
/* Semaphore available=new Semaphore(parallelthreads);
while (finished.size() < population.size()) {
try {
available.acquire();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
if ((population.size()-(queue.size() + finished.size())) < parallelthreads) {
if (queue.size() > 0) {
AbstractEAIndividual tmpindy = queue.get(0);
queue.remove(0);
tmpindy.resetConstraintViolation();
MultiObjectiveEvalThread evalthread = new MultiObjectiveEvalThread(this,tmpindy,finished,population,available);
evalthread.start();
}
}
}
*/
Semaphore sema=new Semaphore(0);
ExecutorService pool = Executors.newFixedThreadPool(parallelthreads);
for (int i = 0; i < population.size(); i++){
AbstractEAIndividual tmpindy = (AbstractEAIndividual)population.get(i);
tmpindy.resetConstraintViolation();
EvalThread evalthread = new EvalThread(this,tmpindy,finished,population,sema);
pool.execute(evalthread);
}
try {
sema.acquire(population.size());
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
pool.shutdownNow();
}else {
// first evaluate the population
for (int i = 0; i < population.size(); i++) {
tmpIndy = (AbstractEAIndividual) population.get(i);
tmpIndy.resetConstraintViolation();
this.evaluate(tmpIndy);
fitness = tmpIndy.getFitness(); fitness = tmpIndy.getFitness();
// check and update border if necessary // check and update border if necessary
if (m_Border == null) if (m_Border == null) this.m_Border = new double[fitness.length][2];
this.m_Border = new double[fitness.length][2];
else if (fitness.length != this.m_Border.length) { else if (fitness.length != this.m_Border.length) {
//System.out.println("AbstractMOOptimizationProblem: Warning fitness.length("+fitness.length+") doesn't fit border.length("+this.m_Border.length+")"); //System.out.println("AbstractMOOptimizationProblem: Warning fitness.length("+fitness.length+") doesn't fit border.length("+this.m_Border.length+")");
//System.out.println("Resetting the border!"); //System.out.println("Resetting the border!");
@ -257,17 +211,8 @@ public abstract class AbstractMultiObjectiveOptimizationProblem extends Abstract
this.m_Border[j][0] = Math.min(this.m_Border[j][0], fitness[j]); this.m_Border[j][0] = Math.min(this.m_Border[j][0], fitness[j]);
this.m_Border[j][1] = Math.max(this.m_Border[j][1], fitness[j]); this.m_Border[j][1] = Math.max(this.m_Border[j][1], fitness[j]);
} }
population.incrFunctionCalls();
} }
}
evaluatePopulationEnd(population); // refactored by MK
}
public void evaluatePopulationStart(Population population) {
if (this.m_Show && (this.m_Plot==null)) this.initProblemFrame();
}
public void evaluatePopulationEnd(Population population) {
// So what is the problem: // So what is the problem:
// on the one hand i want to log the pareto-front in the // on the one hand i want to log the pareto-front in the
// multiobjective case // multiobjective case

View File

@ -1,12 +1,11 @@
package eva2.server.go.problems; package eva2.server.go.problems;
import java.awt.BorderLayout; import java.awt.BorderLayout;
import java.util.Vector;
import java.util.concurrent.ExecutorService; import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors; import java.util.concurrent.Executors;
import java.util.concurrent.Semaphore; import java.util.concurrent.Semaphore;
import java.io.Serializable; import java.io.Serializable;
import java.util.Vector;
import javax.swing.JComponent; import javax.swing.JComponent;
import javax.swing.JPanel; import javax.swing.JPanel;
@ -42,14 +41,14 @@ public abstract class AbstractOptimizationProblem implements InterfaceOptimizati
class EvalThread extends Thread { class EvalThread extends Thread {
AbstractOptimizationProblem prob; AbstractOptimizationProblem prob;
AbstractEAIndividual ind; AbstractEAIndividual ind;
Vector<AbstractEAIndividual> resultrep; // Vector<AbstractEAIndividual> resultrep;
Population pop; Population pop;
Semaphore m_Semaphore; Semaphore m_Semaphore;
public EvalThread(AbstractOptimizationProblem prob, AbstractEAIndividual ind, Vector<AbstractEAIndividual> resultrep, Population pop,Semaphore sema) { public EvalThread(AbstractOptimizationProblem prob, AbstractEAIndividual ind, Population pop,Semaphore sema) {
this.ind = ind; this.ind = ind;
this.prob = prob; this.prob = prob;
this.resultrep = resultrep; // this.resultrep = resultrep;
this.pop = pop; this.pop = pop;
this.m_Semaphore=sema; this.m_Semaphore=sema;
} }
@ -58,7 +57,7 @@ public abstract class AbstractOptimizationProblem implements InterfaceOptimizati
// System.out.println("Running ET " + this); // System.out.println("Running ET " + this);
// long time=System.nanoTime(); // long time=System.nanoTime();
prob.evaluate(ind); prob.evaluate(ind);
resultrep.add(ind); // resultrep.add(ind);
pop.incrFunctionCalls(); pop.incrFunctionCalls();
m_Semaphore.release(); m_Semaphore.release();
// long duration=System.nanoTime()-time; // long duration=System.nanoTime()-time;
@ -110,7 +109,7 @@ public abstract class AbstractOptimizationProblem implements InterfaceOptimizati
if (this.parallelthreads > 1) { if (this.parallelthreads > 1) {
Vector<AbstractEAIndividual> queue = new Vector<AbstractEAIndividual>(population.size()); Vector<AbstractEAIndividual> queue = new Vector<AbstractEAIndividual>(population.size());
Vector<AbstractEAIndividual> finished = new Vector<AbstractEAIndividual>(population.size()); // Vector<AbstractEAIndividual> finished = new Vector<AbstractEAIndividual>(population.size());
/* queue.addAll(population); /* queue.addAll(population);
Semaphore sema=new Semaphore(parallelthreads); Semaphore sema=new Semaphore(parallelthreads);
while (finished.size() < population.size()) { while (finished.size() < population.size()) {
@ -133,18 +132,18 @@ public abstract class AbstractOptimizationProblem implements InterfaceOptimizati
}*/ }*/
Semaphore sema=new Semaphore(0); Semaphore sema=new Semaphore(0);
ExecutorService pool = Executors.newFixedThreadPool(parallelthreads); ExecutorService pool = Executors.newFixedThreadPool(parallelthreads);
for (int i = 0; i < population.size(); i++){ int cntIndies=0;
AbstractEAIndividual tmpindy = (AbstractEAIndividual)population.get(i); for (; cntIndies < population.size(); cntIndies++){
AbstractEAIndividual tmpindy = (AbstractEAIndividual)population.get(cntIndies);
tmpindy.resetConstraintViolation(); tmpindy.resetConstraintViolation();
EvalThread evalthread = new EvalThread(this,tmpindy,finished,population,sema); EvalThread evalthread = new EvalThread(this,tmpindy,population,sema);
pool.execute(evalthread); pool.execute(evalthread);
} }
try { try {
sema.acquire(population.size()); sema.acquire(cntIndies);
} catch (InterruptedException e) { } catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace(); e.printStackTrace();
throw new RuntimeException("Threading error in AbstractOptimizationProblem: " + e.getMessage());
} }
pool.shutdownNow(); pool.shutdownNow();
} else { } else {
@ -185,6 +184,21 @@ public abstract class AbstractOptimizationProblem implements InterfaceOptimizati
*/ */
public abstract void evaluate(AbstractEAIndividual individual); public abstract void evaluate(AbstractEAIndividual individual);
public static void defaultInitPopulation(Population population, AbstractEAIndividual template, InterfaceOptimizationProblem prob) {
AbstractEAIndividual tmpIndy;
population.clear();
for (int i = 0; i < population.getTargetSize(); i++) {
tmpIndy = (AbstractEAIndividual)((AbstractEAIndividual)template).clone();
tmpIndy.init(prob);
population.add(tmpIndy);
}
// population init must be last
// it set's fitcalls and generation to zero
population.init();
}
/******************** Some output methods *******************************************/ /******************** Some output methods *******************************************/
/** This method allows you to output a string that describes a found solution /** This method allows you to output a string that describes a found solution

View File

@ -55,31 +55,20 @@ public abstract class AbstractProblemBinary extends AbstractOptimizationProblem
*/ */
public abstract int getProblemDimension(); public abstract int getProblemDimension();
/** // /**
* Initialize a single individual with index k in the // * Initialize a single individual with index k in the
* initPopulation cycle. // * initPopulation cycle.
* @param k // * @param k
* @param indy // * @param indy
*/ // */
protected void initIndy(int k, AbstractEAIndividual indy) { // protected void initIndy(int k, AbstractEAIndividual indy) {
indy.init(this); // indy.init(this);
} // }
@Override @Override
public void initPopulation(Population population) { public void initPopulation(Population population) {
AbstractEAIndividual tmpIndy;
population.clear();
((InterfaceDataTypeBinary)this.m_Template).setBinaryDataLength(this.getProblemDimension()); ((InterfaceDataTypeBinary)this.m_Template).setBinaryDataLength(this.getProblemDimension());
AbstractOptimizationProblem.defaultInitPopulation(population, m_Template, this);
for (int i = 0; i < population.getPopulationSize(); i++) {
tmpIndy = (AbstractEAIndividual)((AbstractEAIndividual)this.m_Template).clone();
initIndy(i, tmpIndy);
population.add(tmpIndy);
}
// population init must be last
// it set's fitcalls and generation to zero
population.init();
} }
@Override @Override

View File

@ -155,18 +155,8 @@ public abstract class AbstractProblemDouble extends AbstractOptimizationProblem
@Override @Override
public void initPopulation(Population population) { public void initPopulation(Population population) {
AbstractEAIndividual tmpIndy;
population.clear();
initTemplate(); initTemplate();
AbstractOptimizationProblem.defaultInitPopulation(population, m_Template, this);
for (int i = 0; i < population.getPopulationSize(); i++) {
tmpIndy = (AbstractEAIndividual)((AbstractEAIndividual)this.m_Template).clone();
tmpIndy.init(this);
population.add(tmpIndy);
}
// population init must be last
// it set's fitcalls and generation to zero
population.init();
} }
/** /**

View File

@ -0,0 +1,99 @@
package eva2.server.go.problems;
/**
* Created by IntelliJ IDEA.
* User: streiche
* Date: 24.03.2003
* Time: 17:58:55
* To change this template use Options | File Templates.
*/
public abstract class AbstractProblemDoubleOffset extends AbstractProblemDouble implements Interface2DBorderProblem {
// protected AbstractEAIndividual m_OverallBest = null;
protected int m_ProblemDimension = 10;
protected double m_XOffSet = 0.0;
protected double m_YOffSet = 0.0;
// protected boolean m_UseTestConstraint = false;
public AbstractProblemDoubleOffset() {
super();
setDefaultRange(10);
}
public AbstractProblemDoubleOffset(AbstractProblemDoubleOffset b) {
super();
super.cloneObjects(b);
this.m_ProblemDimension = b.m_ProblemDimension;
this.m_XOffSet = b.m_XOffSet;
this.m_YOffSet = b.m_YOffSet;
// this.m_UseTestConstraint = b.m_UseTestConstraint;
}
public AbstractProblemDoubleOffset(int dim) {
this();
setProblemDimension(dim);
}
public AbstractProblemDoubleOffset(int dim, double defRange) {
this(dim);
setDefaultRange(defRange);
}
/** This method inits the Problem to log multiruns
*/
public void initProblem() {
// this.m_OverallBest = null;
initTemplate();
}
/**********************************************************************************************************************
* These are for GUI
*/
/** This method allows the CommonJavaObjectEditorPanel to read the
* name to the current object.
* @return The name.
*/
public String getName() {
return "Double-valued-Problem+Offsets";
}
/** This method allows you to set/get an offset for decision variables.
* @param XOffSet The offset for the decision variables.
*/
public void setXOffSet(double XOffSet) {
this.m_XOffSet = XOffSet;
}
public double getXOffSet() {
return this.m_XOffSet;
}
public String xOffSetTipText() {
return "Choose an offset for the decision variable.";
}
/** This method allows you to set/get the offset for the
* objective value.
* @param YOffSet The offset for the objective value.
*/
public void setYOffSet(double YOffSet) {
this.m_YOffSet = YOffSet;
}
public double getYOffSet() {
return this.m_YOffSet;
}
public String yOffSetTipText() {
return "Choose an offset for the objective value.";
}
/** Length of the x vector at is to be optimized
* @param t Length of the x vector at is to be optimized
*/
public void setProblemDimension(int t) {
this.m_ProblemDimension = t;
}
public int getProblemDimension() {
return this.m_ProblemDimension;
}
public String problemDimensionTipText() {
return "Length of the x vector to be optimized.";
}
}

View File

@ -105,23 +105,12 @@ public class ExternalRuntimeProblem extends AbstractOptimizationProblem implemen
* @param population The populations that is to be inited * @param population The populations that is to be inited
*/ */
public void initPopulation(Population population) { public void initPopulation(Population population) {
AbstractEAIndividual tmpIndy;
this.m_OverallBest = null; this.m_OverallBest = null;
population.clear();
((InterfaceDataTypeDouble)this.m_Template).setDoubleDataLength(this.m_ProblemDimension); ((InterfaceDataTypeDouble)this.m_Template).setDoubleDataLength(this.m_ProblemDimension);
((InterfaceDataTypeDouble)this.m_Template).SetDoubleRange(makeRange()); ((InterfaceDataTypeDouble)this.m_Template).SetDoubleRange(makeRange());
for (int i = 0; i < population.getPopulationSize(); i++) { AbstractOptimizationProblem.defaultInitPopulation(population, m_Template, this);
tmpIndy = (AbstractEAIndividual)((AbstractEAIndividual)this.m_Template).clone();
tmpIndy.init(this);
population.add(tmpIndy);
}
// population init must be last
// it set's fitcalls and generation to zero
population.init();
} }
public double[][] makeRange() { public double[][] makeRange() {

View File

@ -9,7 +9,7 @@ import eva2.server.go.individuals.ESIndividualDoubleData;
* Time: 14:33:07 * Time: 14:33:07
* To change this template use File | Settings | File Templates. * To change this template use File | Settings | File Templates.
*/ */
public class F10Problem extends F1Problem implements InterfaceMultimodalProblem, java.io.Serializable { public class F10Problem extends AbstractProblemDoubleOffset implements InterfaceMultimodalProblem, java.io.Serializable {
private double m_D = 1.5; private double m_D = 1.5;
private double m_b = 2.3; private double m_b = 2.3;

View File

@ -12,7 +12,7 @@ import eva2.server.go.populations.Population;
* Time: 14:59:23 * Time: 14:59:23
* To change this template use File | Settings | File Templates. * To change this template use File | Settings | File Templates.
*/ */
public class F11Problem extends F1Problem implements InterfaceMultimodalProblem, java.io.Serializable { public class F11Problem extends AbstractProblemDoubleOffset implements InterfaceMultimodalProblem, java.io.Serializable {
private double m_D = 4000; private double m_D = 4000;

View File

@ -12,7 +12,7 @@ import eva2.server.go.populations.Population;
* Time: 14:59:33 * Time: 14:59:33
* To change this template use File | Settings | File Templates. * To change this template use File | Settings | File Templates.
*/ */
public class F12Problem extends F1Problem implements java.io.Serializable { public class F12Problem extends AbstractProblemDoubleOffset implements java.io.Serializable {
private final static double f12range = 5.; private final static double f12range = 5.;
public F12Problem() { public F12Problem() {

View File

@ -6,7 +6,7 @@ import eva2.server.go.individuals.ESIndividualDoubleData;
* Schwefels sine root function (1981) with a minimum at 420.9687^n of value 0. * Schwefels sine root function (1981) with a minimum at 420.9687^n of value 0.
* Function f(x) = (418.9829 * n) - sum_n(x_i * sin(sqrt(abs(x_i)))) + (418.9829 * n); * Function f(x) = (418.9829 * n) - sum_n(x_i * sin(sqrt(abs(x_i)))) + (418.9829 * n);
*/ */
public class F13Problem extends F1Problem implements InterfaceMultimodalProblem { public class F13Problem extends AbstractProblemDoubleOffset implements InterfaceMultimodalProblem {
public F13Problem() { public F13Problem() {
this.m_Template = new ESIndividualDoubleData(); this.m_Template = new ESIndividualDoubleData();

View File

@ -9,7 +9,7 @@ import eva2.server.go.individuals.ESIndividualDoubleData;
* Time: 19:15:03 * Time: 19:15:03
* To change this template use File | Settings | File Templates. * To change this template use File | Settings | File Templates.
*/ */
public class F14Problem extends F1Problem implements InterfaceMultimodalProblem, java.io.Serializable { public class F14Problem extends AbstractProblemDoubleOffset implements InterfaceMultimodalProblem, java.io.Serializable {
double rotation = 0.; double rotation = 0.;
double rotationDX = 2; double rotationDX = 2;

View File

@ -1,7 +1,5 @@
package eva2.server.go.problems; package eva2.server.go.problems;
import eva2.server.go.individuals.AbstractEAIndividual;
import eva2.server.go.operators.constraint.GenericConstraint;
import eva2.server.go.strategies.InterfaceOptimizer; import eva2.server.go.strategies.InterfaceOptimizer;
/** /**
@ -11,18 +9,7 @@ import eva2.server.go.strategies.InterfaceOptimizer;
* Time: 17:58:55 * Time: 17:58:55
* To change this template use Options | File Templates. * To change this template use Options | File Templates.
*/ */
public class F1Problem extends AbstractProblemDouble implements Interface2DBorderProblem, java.io.Serializable { public class F1Problem extends AbstractProblemDoubleOffset implements Interface2DBorderProblem, java.io.Serializable, InterfaceFirstOrderDerivableProblem {
/**
*
*/
private static final long serialVersionUID = 4870484001737601464L;
// protected AbstractEAIndividual m_OverallBest = null;
protected int m_ProblemDimension = 10;
protected double m_XOffSet = 0.0;
protected double m_YOffSet = 0.0;
// protected boolean m_UseTestConstraint = false;
public F1Problem() { public F1Problem() {
super(); super();
setDefaultRange(10); setDefaultRange(10);
@ -31,15 +18,10 @@ public class F1Problem extends AbstractProblemDouble implements Interface2DBorde
public F1Problem(F1Problem b) { public F1Problem(F1Problem b) {
super(); super();
super.cloneObjects(b); super.cloneObjects(b);
this.m_ProblemDimension = b.m_ProblemDimension;
this.m_XOffSet = b.m_XOffSet;
this.m_YOffSet = b.m_YOffSet;
// this.m_UseTestConstraint = b.m_UseTestConstraint;
} }
public F1Problem(int dim) { public F1Problem(int dim) {
this(); super(dim);
setProblemDimension(dim);
} }
public F1Problem(int dim, double defRange) { public F1Problem(int dim, double defRange) {
@ -54,13 +36,6 @@ public class F1Problem extends AbstractProblemDouble implements Interface2DBorde
return (Object) new F1Problem(this); return (Object) new F1Problem(this);
} }
/** This method inits the Problem to log multiruns
*/
public void initProblem() {
// this.m_OverallBest = null;
initTemplate();
}
/** Ths method allows you to evaluate a simple bit string to determine the fitness /** Ths method allows you to evaluate a simple bit string to determine the fitness
* @param x The n-dimensional input vector * @param x The n-dimensional input vector
* @return The m-dimensional output vector. * @return The m-dimensional output vector.
@ -110,54 +85,12 @@ public class F1Problem extends AbstractProblemDouble implements Interface2DBorde
return "F1: multidimensional parabola problem"; return "F1: multidimensional parabola problem";
} }
/** This method allows you to set/get an offset for decision variables. public double[] getFirstOrderGradients(double[] x) {
* @param XOffSet The offset for the decision variables. // first order partial derivation in direction x_i is 2*x_i
*/ double[] grads=new double[x.length];
public void setXOffSet(double XOffSet) { for (int i=0; i<x.length; i++) {
this.m_XOffSet = XOffSet; grads[i]=(2.*(x[i] - this.m_XOffSet));
} }
public double getXOffSet() { return grads;
return this.m_XOffSet; }
}
public String xOffSetTipText() {
return "Choose an offset for the decision variable.";
}
/** This method allows you to set/get the offset for the
* objective value.
* @param YOffSet The offset for the objective value.
*/
public void setYOffSet(double YOffSet) {
this.m_YOffSet = YOffSet;
}
public double getYOffSet() {
return this.m_YOffSet;
}
public String yOffSetTipText() {
return "Choose an offset for the objective value.";
}
/** Length of the x vector at is to be optimized
* @param t Length of the x vector at is to be optimized
*/
public void setProblemDimension(int t) {
this.m_ProblemDimension = t;
}
public int getProblemDimension() {
return this.m_ProblemDimension;
}
public String problemDimensionTipText() {
return "Length of the x vector to be optimized.";
}
// /** This method allows you to toggle the application of a simple test constraint.
// * @param b The mode for the test constraint
// */
// public void setUseTestConstraint(boolean b) {
// this.m_UseTestConstraint = b;
// }
// public boolean getUseTestConstraint() {
// return this.m_UseTestConstraint;
// }
// public String useTestConstraintTipText() {
// return "Just a simple test constraint of x[0] >= 1.";
// }
} }

View File

@ -9,7 +9,7 @@ import eva2.server.go.individuals.ESIndividualDoubleData;
* Time: 19:03:09 * Time: 19:03:09
* To change this template use File | Settings | File Templates. * To change this template use File | Settings | File Templates.
*/ */
public class F2Problem extends F1Problem implements InterfaceMultimodalProblem, java.io.Serializable { public class F2Problem extends AbstractProblemDoubleOffset implements InterfaceMultimodalProblem, java.io.Serializable, InterfaceFirstOrderDerivableProblem {
public F2Problem() { public F2Problem() {
this.m_Template = new ESIndividualDoubleData(); this.m_Template = new ESIndividualDoubleData();
@ -45,6 +45,21 @@ public class F2Problem extends F1Problem implements InterfaceMultimodalProblem,
return result; return result;
} }
public double[] getFirstOrderGradients(double[] x) {
int dim = x.length;
double[] result = new double[dim];
double xi, xii;
for (int i = 0; i < dim-1; i++) {
xi=x[i]-m_XOffSet;
xii=x[i+1]-m_XOffSet;
result[i] += (-200.*xii+200.*xi+2.*xi-2);
result[i+1] += (200.*xii-200*xi);
}
return result;
}
/** This method returns a string describing the optimization problem. /** This method returns a string describing the optimization problem.
* @return The description. * @return The description.
*/ */

View File

@ -10,7 +10,7 @@ import eva2.server.go.individuals.ESIndividualDoubleData;
* Time: 19:15:03 * Time: 19:15:03
* To change this template use File | Settings | File Templates. * To change this template use File | Settings | File Templates.
*/ */
public class F3Problem extends F1Problem implements java.io.Serializable { public class F3Problem extends AbstractProblemDoubleOffset implements java.io.Serializable {
public F3Problem() { public F3Problem() {
this.m_Template = new ESIndividualDoubleData(); this.m_Template = new ESIndividualDoubleData();

View File

@ -13,7 +13,7 @@ import eva2.tools.math.RNG;
* Time: 19:28:33 * Time: 19:28:33
* To change this template use File | Settings | File Templates. * To change this template use File | Settings | File Templates.
*/ */
public class F4Problem extends F1Problem implements java.io.Serializable { public class F4Problem extends AbstractProblemDoubleOffset implements java.io.Serializable {
final static double f4range = 1.28; final static double f4range = 1.28;
public F4Problem() { public F4Problem() {

View File

@ -13,7 +13,7 @@ import eva2.tools.math.RNG;
* Time: 19:30:52 * Time: 19:30:52
* To change this template use File | Settings | File Templates. * To change this template use File | Settings | File Templates.
*/ */
public class F5Problem extends F1Problem implements java.io.Serializable { public class F5Problem extends AbstractProblemDoubleOffset implements java.io.Serializable {
final static double f5range = 65.536; final static double f5range = 65.536;
public F5Problem() { public F5Problem() {

View File

@ -11,7 +11,7 @@ import eva2.tools.math.Jama.Matrix;
* Time: 13:09:36 * Time: 13:09:36
* To change this template use File | Settings | File Templates. * To change this template use File | Settings | File Templates.
*/ */
public class F6Problem extends F1Problem implements InterfaceMultimodalProblem, java.io.Serializable { public class F6Problem extends AbstractProblemDoubleOffset implements InterfaceMultimodalProblem, java.io.Serializable {
private boolean doRotation = false; private boolean doRotation = false;
private double m_A = 10; private double m_A = 10;

View File

@ -15,7 +15,7 @@ import eva2.tools.math.RNG;
* Time: 13:23:43 * Time: 13:23:43
* To change this template use File | Settings | File Templates. * To change this template use File | Settings | File Templates.
*/ */
public class F7Problem extends F1Problem implements java.io.Serializable { public class F7Problem extends AbstractProblemDoubleOffset implements java.io.Serializable {
private double m_t = 250; private double m_t = 250;
private double m_Change = 4; private double m_Change = 4;

View File

@ -8,7 +8,7 @@ package eva2.server.go.problems;
* Time: 19:40:28 * Time: 19:40:28
* To change this template use File | Settings | File Templates. * To change this template use File | Settings | File Templates.
*/ */
public class F8Problem extends F1Problem implements InterfaceMultimodalProblem, java.io.Serializable { public class F8Problem extends AbstractProblemDoubleOffset implements InterfaceMultimodalProblem, java.io.Serializable {
private double a = 20; private double a = 20;
private double b = 0.2; private double b = 0.2;

View File

@ -3,7 +3,7 @@ package eva2.server.go.problems;
import eva2.server.go.individuals.AbstractEAIndividual; import eva2.server.go.individuals.AbstractEAIndividual;
import eva2.server.go.individuals.ESIndividualDoubleData; import eva2.server.go.individuals.ESIndividualDoubleData;
public class F9Problem extends F1Problem implements java.io.Serializable { public class F9Problem extends AbstractProblemDoubleOffset implements java.io.Serializable {
public F9Problem() { public F9Problem() {
this.m_Template = new ESIndividualDoubleData(); this.m_Template = new ESIndividualDoubleData();

View File

@ -247,13 +247,8 @@ public class FLensProblem extends AbstractOptimizationProblem implements Interfa
* @param population The populations that is to be inited * @param population The populations that is to be inited
*/ */
public void initPopulation(Population population) { public void initPopulation(Population population) {
AbstractEAIndividual tmpIndy;
this.m_OverallBest = null; this.m_OverallBest = null;
population.clear();
((InterfaceDataTypeDouble)this.m_Template).setDoubleDataLength(this.m_ProblemDimension); ((InterfaceDataTypeDouble)this.m_Template).setDoubleDataLength(this.m_ProblemDimension);
// set the range // set the range
double[][] range = new double[this.m_ProblemDimension][2]; double[][] range = new double[this.m_ProblemDimension][2];
for (int i = 0; i < range.length; i++) { for (int i = 0; i < range.length; i++) {
@ -262,13 +257,8 @@ public class FLensProblem extends AbstractOptimizationProblem implements Interfa
} }
((InterfaceDataTypeDouble)this.m_Template).SetDoubleRange(range); ((InterfaceDataTypeDouble)this.m_Template).SetDoubleRange(range);
for (int i = 0; i < population.getPopulationSize(); i++) { AbstractOptimizationProblem.defaultInitPopulation(population, m_Template, this);
tmpIndy = (AbstractEAIndividual)((AbstractEAIndividual)this.m_Template).clone();
tmpIndy.init(this);
population.add(tmpIndy);
}
if (this.m_Show) this.initProblemFrame(); if (this.m_Show) this.initProblemFrame();
population.init();
} }
public void evaluatePopulationEnd(Population pop) { public void evaluatePopulationEnd(Population pop) {

View File

@ -1,18 +1,19 @@
package eva2.server.go.problems; package eva2.server.go.problems;
/** /**
* <p>Title: EvA2</p> * An interface for first-order derivable problems which can be used for gradient descent.
* <p>Description: </p> *
* <p>Copyright: Copyright (c) 2003</p> * @author hplanatscher, mkron
* <p>Company: </p> *
* @author not attributable
* @version 1.0
*/ */
public interface InterfaceFirstOrderDerivableProblem { public interface InterfaceFirstOrderDerivableProblem {
/**
* Calculate the first order gradients of this problem.
* @param x
* @return the first order gradients of this problem
*/
public double[] getFirstOrderGradients(double[] x); public double[] getFirstOrderGradients(double[] x);
public double getFirstOrderGradient(int paramindex,double[] x); // public double getFirstOrderGradient(int paramindex,double[] x);
} }

View File

@ -9,7 +9,7 @@ import eva2.server.go.individuals.codings.gp.GPArea;
* Time: 14:43:03 * Time: 14:43:03
* To change this template use Options | File Templates. * To change this template use Options | File Templates.
*/ */
public interface InterfaceProgramProblem { public interface InterfaceProgramProblem extends InterfaceOptimizationProblem {
/** This method allows a GP program to sense the environment, e.g. /** This method allows a GP program to sense the environment, e.g.
* input values, current time etc * input values, current time etc

View File

@ -437,19 +437,8 @@ public class MatlabProblem extends AbstractOptimizationProblem implements Interf
@Override @Override
public void initPopulation(Population population) { public void initPopulation(Population population) {
AbstractEAIndividual tmpIndy;
population.clear();
initTemplate(); initTemplate();
AbstractOptimizationProblem.defaultInitPopulation(population, m_Template, this);
for (int i = 0; i < population.getPopulationSize(); i++) {
tmpIndy = (AbstractEAIndividual)((AbstractEAIndividual)this.m_Template).clone();
tmpIndy.init(this);
// System.err.println("initPopulation: " + AbstractEAIndividual.getDefaultDataString(tmpIndy) + " , " + tmpIndy.getStringRepresentation());
population.add(tmpIndy);
}
// population init must be last
// it set's fitcalls and generation to zero
population.init();
} }
public String getStringRepresentationForProblem(InterfaceOptimizer opt) { public String getStringRepresentationForProblem(InterfaceOptimizer opt) {

View File

@ -143,9 +143,8 @@ public class PSymbolicRegression extends AbstractOptimizationProblem implements
* @param population The populations that is to be inited * @param population The populations that is to be inited
*/ */
public static void initPopulation(Population pop, InterfaceProgramProblem prob, boolean useInnerConsts, int numConsts) { public static void initPopulation(Population pop, InterfaceProgramProblem prob, boolean useInnerConsts, int numConsts) {
AbstractEAIndividual tmpIndy, template; AbstractEAIndividual template;
pop.clear();
template = ((AbstractOptimizationProblem)prob).getIndividualTemplate(); template = ((AbstractOptimizationProblem)prob).getIndividualTemplate();
GPArea tmpArea[] = new GPArea[1]; GPArea tmpArea[] = new GPArea[1];
tmpArea[0] = prob.getArea(); tmpArea[0] = prob.getArea();
@ -154,14 +153,7 @@ public class PSymbolicRegression extends AbstractOptimizationProblem implements
if ((template instanceof GAPIndividualProgramData) && useInnerConsts) { if ((template instanceof GAPIndividualProgramData) && useInnerConsts) {
((GAPIndividualProgramData)template).setDoubleDataLength(numConsts); ((GAPIndividualProgramData)template).setDoubleDataLength(numConsts);
} }
for (int i = 0; i < pop.getPopulationSize(); i++) { AbstractOptimizationProblem.defaultInitPopulation(pop, template, prob);
tmpIndy = (AbstractEAIndividual)((AbstractEAIndividual)template).clone();
tmpIndy.init((AbstractOptimizationProblem)prob);
pop.add(tmpIndy);
}
// population init must be last
// it set's fitcalls and generation to zero
pop.init();
} }
/** This method init the enviroment panel if necessary. /** This method init the enviroment panel if necessary.
@ -238,6 +230,7 @@ public class PSymbolicRegression extends AbstractOptimizationProblem implements
if ((this.m_OverallBest == null) || (this.m_OverallBest.getFitness(0) > individual.getFitness(0))) { if ((this.m_OverallBest == null) || (this.m_OverallBest.getFitness(0) > individual.getFitness(0))) {
this.m_OverallBest = (AbstractEAIndividual)individual.clone(); this.m_OverallBest = (AbstractEAIndividual)individual.clone();
if (this.m_Show) { if (this.m_Show) {
if (m_Plot==null) this.initEnvironmentPanel();
this.m_Plot.clearAll(); this.m_Plot.clearAll();
program = ((InterfaceDataTypeProgram)this.m_OverallBest).getProgramData()[0]; program = ((InterfaceDataTypeProgram)this.m_OverallBest).getProgramData()[0];
for (double i = 0; i < this.m_NumberOfCheckPoints; i++) { for (double i = 0; i < this.m_NumberOfCheckPoints; i++) {

View File

@ -101,20 +101,8 @@ public class SimpleProblemWrapper extends AbstractOptimizationProblem {
@Override @Override
public void initPopulation(Population population) { public void initPopulation(Population population) {
AbstractEAIndividual tmpIndy;
population.clear();
initTemplate(); initTemplate();
AbstractOptimizationProblem.defaultInitPopulation(population, m_Template, this);
for (int i = 0; i < population.getPopulationSize(); i++) {
tmpIndy = (AbstractEAIndividual)((AbstractEAIndividual)this.m_Template).clone();
tmpIndy.init(this);
population.add(tmpIndy);
}
// population init must be last
// it set's fitcalls and generation to zero
population.init();
} }
@Override @Override

View File

@ -90,23 +90,14 @@ public class TF1Problem extends AbstractMultiObjectiveOptimizationProblem implem
* @param population The populations that is to be inited * @param population The populations that is to be inited
*/ */
public void initPopulation(Population population) { public void initPopulation(Population population) {
AbstractEAIndividual tmpIndy;
this.m_ParetoFront = new Population(); this.m_ParetoFront = new Population();
double[][] newRange = makeRange(); double[][] newRange = makeRange();
population.clear();
((InterfaceDataTypeDouble)this.m_Template).setDoubleDataLength(this.m_ProblemDimension); ((InterfaceDataTypeDouble)this.m_Template).setDoubleDataLength(this.m_ProblemDimension);
((InterfaceDataTypeDouble)this.m_Template).SetDoubleRange(newRange); ((InterfaceDataTypeDouble)this.m_Template).SetDoubleRange(newRange);
for (int i = 0; i < population.getPopulationSize(); i++) {
tmpIndy = (AbstractEAIndividual)((AbstractEAIndividual)this.m_Template).clone(); AbstractOptimizationProblem.defaultInitPopulation(population, m_Template, this);
tmpIndy.init(this);
population.add(tmpIndy);
}
// population init must be last
// it set's fitcalls and generation to zero
population.init();
} }
protected double[][] makeRange() { protected double[][] makeRange() {

View File

@ -118,7 +118,7 @@ public class CHCAdaptiveSearchAlgorithm implements InterfaceOptimizer, java.io.S
//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.getPopulationSize()); 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++) {
@ -169,7 +169,7 @@ public class CHCAdaptiveSearchAlgorithm implements InterfaceOptimizer, java.io.S
this.m_Population.clear(); this.m_Population.clear();
this.m_Population.add(best); this.m_Population.add(best);
for (int i = 1; i < this.m_Population.getPopulationSize(); 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++) {
@ -207,7 +207,7 @@ public class CHCAdaptiveSearchAlgorithm implements InterfaceOptimizer, java.io.S
nextGeneration.addPopulation(this.m_Population); nextGeneration.addPopulation(this.m_Population);
// this.m_NormationOperator.computeSelectionProbability(nextGeneration, "Fitness"); // this.m_NormationOperator.computeSelectionProbability(nextGeneration, "Fitness");
this.m_PopulSelectionOperator.prepareSelection(this.m_Population); this.m_PopulSelectionOperator.prepareSelection(this.m_Population);
tmp = this.m_PopulSelectionOperator.selectFrom(nextGeneration, this.m_Population.getPopulationSize()); tmp = this.m_PopulSelectionOperator.selectFrom(nextGeneration, this.m_Population.getTargetSize());
nextGeneration.clear(); nextGeneration.clear();
nextGeneration.addPopulation(tmp); nextGeneration.addPopulation(tmp);
this.m_Population = nextGeneration; this.m_Population = nextGeneration;

View File

@ -111,7 +111,7 @@ public class ClusterBasedNichingEA implements InterfacePopulationChangedEventLis
this.m_Optimizer.addPopulationChangedEventListener(this); this.m_Optimizer.addPopulationChangedEventListener(this);
this.m_Undifferentiated = new Population(); this.m_Undifferentiated = new Population();
this.m_Undifferentiated.setUseHistory(true); this.m_Undifferentiated.setUseHistory(true);
this.m_Undifferentiated.setPopulationSize(this.m_PopulationSize); this.m_Undifferentiated.setTargetSize(this.m_PopulationSize);
this.m_Species = new ArrayList<Population>(); this.m_Species = new ArrayList<Population>();
this.m_Problem.initPopulation(this.m_Undifferentiated); this.m_Problem.initPopulation(this.m_Undifferentiated);
this.evaluatePopulation(this.m_Undifferentiated); this.evaluatePopulation(this.m_Undifferentiated);
@ -132,7 +132,7 @@ public class ClusterBasedNichingEA implements InterfacePopulationChangedEventLis
pop.setUseHistory(true); pop.setUseHistory(true);
this.m_Undifferentiated = (Population)pop.clone(); this.m_Undifferentiated = (Population)pop.clone();
if (reset) this.m_Undifferentiated.init(); if (reset) this.m_Undifferentiated.init();
this.m_Undifferentiated.setPopulationSize(this.m_PopulationSize); this.m_Undifferentiated.setTargetSize(this.m_PopulationSize);
this.m_Species = new ArrayList<Population>(); this.m_Species = new ArrayList<Population>();
m_Archive = new Population(); m_Archive = new Population();
convergedCnt = 0; convergedCnt = 0;
@ -273,7 +273,7 @@ public class ClusterBasedNichingEA implements InterfacePopulationChangedEventLis
private Population initializeIndividuals(int n) { private Population initializeIndividuals(int n) {
Population result = new Population(); Population result = new Population();
result.setUseHistory(true); result.setUseHistory(true);
result.setPopulationSize(n); result.setTargetSize(n);
//@todo: crossover between species is to be impelemented //@todo: crossover between species is to be impelemented
this.m_Problem.initPopulation(result); this.m_Problem.initPopulation(result);
this.m_Problem.evaluate(result); this.m_Problem.evaluate(result);
@ -334,18 +334,18 @@ public class ClusterBasedNichingEA implements InterfacePopulationChangedEventLis
if (TRACE) System.out.println("mu: "+es.getMu() + " / lambda: " + es.getLambda()); if (TRACE) System.out.println("mu: "+es.getMu() + " / lambda: " + es.getLambda());
} }
if (TRACE) { if (TRACE) {
System.out.println("Bef: spec size: " + species.size() + ", says its " + species.getPopulationSize()); System.out.println("Bef: spec size: " + species.size() + ", target size " + species.getTargetSize());
System.out.println("Best bef: " + BeanInspector.toString(m_Optimizer.getPopulation().getBestFitness())); System.out.println("Best bef: " + BeanInspector.toString(m_Optimizer.getPopulation().getBestFitness()));
} }
this.m_Optimizer.optimize(); this.m_Optimizer.optimize();
Population retPop = m_Optimizer.getPopulation(); Population retPop = m_Optimizer.getPopulation();
if (TRACE) { if (TRACE) {
System.out.println("Aft: spec size: " + retPop.size() + ", says its " + retPop.getPopulationSize()); System.out.println("Aft: spec size: " + retPop.size() + ", target size " + retPop.getTargetSize());
System.out.println("Best aft: " + BeanInspector.toString(retPop.getBestFitness())); System.out.println("Best aft: " + BeanInspector.toString(retPop.getBestFitness()));
} }
if (retPop.size() != retPop.getPopulationSize()) { if (retPop.size() != retPop.getTargetSize()) {
if (TRACE) System.out.println("correcting popsize after opt: " + retPop.getPopulationSize() + " to " + retPop.size()); if (TRACE) System.out.println("correcting popsize after opt: " + retPop.getTargetSize() + " to " + retPop.size());
retPop.setPopulationSize(retPop.size()); retPop.synchSize();
} }
// if (useDistraction) { // if (useDistraction) {
@ -376,7 +376,7 @@ public class ClusterBasedNichingEA implements InterfacePopulationChangedEventLis
} }
// optimize D_0 // optimize D_0
this.m_Undifferentiated.setPopulationSize(this.m_Undifferentiated.size()); this.m_Undifferentiated.synchSize();
if (isActive(m_Undifferentiated)) { if (isActive(m_Undifferentiated)) {
this.capMutationRate(this.m_Undifferentiated, 0); // MK TODO this sets mutation rate to 0! why? this.capMutationRate(this.m_Undifferentiated, 0); // MK TODO this sets mutation rate to 0! why?
m_Undifferentiated = optimizeSpecies(m_Undifferentiated); m_Undifferentiated = optimizeSpecies(m_Undifferentiated);
@ -398,7 +398,7 @@ public class ClusterBasedNichingEA implements InterfacePopulationChangedEventLis
if (TRACE) System.out.println("-Deme " + i + " size: " + ((Population)this.m_Species.get(i)).size()); if (TRACE) System.out.println("-Deme " + i + " size: " + ((Population)this.m_Species.get(i)).size());
curSpecies = ((Population)this.m_Species.get(i)); curSpecies = ((Population)this.m_Species.get(i));
curSpecies.SetFunctionCalls(0); curSpecies.SetFunctionCalls(0);
curSpecies.setPopulationSize(curSpecies.size()); curSpecies.synchSize();
if (isActive(curSpecies)) { if (isActive(curSpecies)) {
if ((haltingWindow > 0) && (this.testSpeciesForConvergence(curSpecies))) { if ((haltingWindow > 0) && (this.testSpeciesForConvergence(curSpecies))) {
///////////////////////////////////////////// Halting Window ///////////////////////////////////////////////// ///////////////////////////////////////////// Halting Window /////////////////////////////////////////////////
@ -431,7 +431,7 @@ public class ClusterBasedNichingEA implements InterfacePopulationChangedEventLis
// reinit the surplus individuals and add these new individuals to undifferentiated // reinit the surplus individuals and add these new individuals to undifferentiated
m_Undifferentiated.addPopulation(this.initializeIndividuals(reinitCount)); m_Undifferentiated.addPopulation(this.initializeIndividuals(reinitCount));
m_Undifferentiated.incrFunctionCallsBy(reinitCount); m_Undifferentiated.incrFunctionCallsBy(reinitCount);
m_Undifferentiated.setPopulationSize(this.m_Undifferentiated.getPopulationSize()+reinitCount); m_Undifferentiated.setTargetSize(this.m_Undifferentiated.getTargetSize()+reinitCount);
// if (this.m_Debug) { // if (this.m_Debug) {
// System.out.println("Undiff.Size: " + this.m_Undifferentiated.size() +"/"+this.m_Undifferentiated.getPopulationSize()); // System.out.println("Undiff.Size: " + this.m_Undifferentiated.size() +"/"+this.m_Undifferentiated.getPopulationSize());
// System.out.println("Diff.Size : " + ((Population)this.m_Species.get(i)).size() +"/"+((Population)this.m_Species.get(i)).getPopulationSize()); // System.out.println("Diff.Size : " + ((Population)this.m_Species.get(i)).size() +"/"+((Population)this.m_Species.get(i)).getPopulationSize());
@ -492,9 +492,9 @@ public class ClusterBasedNichingEA implements InterfacePopulationChangedEventLis
ClusterResult = this.m_CAForSpeciesDifferentation.cluster(curSpecies); ClusterResult = this.m_CAForSpeciesDifferentation.cluster(curSpecies);
this.m_Undifferentiated.addPopulation(ClusterResult[0]); this.m_Undifferentiated.addPopulation(ClusterResult[0]);
// ClusterResult[0].setUseHistory(true); // ClusterResult[0].setUseHistory(true);
this.m_Undifferentiated.setPopulationSize(this.m_Undifferentiated.getPopulationSize() + ClusterResult[0].size()); this.m_Undifferentiated.setTargetSize(this.m_Undifferentiated.getTargetSize() + ClusterResult[0].size());
for (int j = 1; j < ClusterResult.length; j++) { // set up new species for (int j = 1; j < ClusterResult.length; j++) { // set up new species
ClusterResult[j].setPopulationSize(ClusterResult[j].size()); ClusterResult[j].synchSize();
ClusterResult[j].setUseHistory(true); ClusterResult[j].setUseHistory(true);
// if (ClusterResult.length > 2) ClusterResult[j].m_History = new ArrayList(); // mk: why min 3? Ill copy the history from the original pop for any j... // if (ClusterResult.length > 2) ClusterResult[j].m_History = new ArrayList(); // mk: why min 3? Ill copy the history from the original pop for any j...
ClusterResult[j].m_History = (ArrayList<AbstractEAIndividual>) curSpecies.m_History.clone(); ClusterResult[j].m_History = (ArrayList<AbstractEAIndividual>) curSpecies.m_History.clone();
@ -537,7 +537,7 @@ public class ClusterBasedNichingEA implements InterfacePopulationChangedEventLis
this.m_Undifferentiated.remove(i); this.m_Undifferentiated.remove(i);
if (isActive(curSpecies)) { if (isActive(curSpecies)) {
curSpecies.add(tmpIndy); curSpecies.add(tmpIndy);
this.m_Undifferentiated.setPopulationSize(this.m_Undifferentiated.getPopulationSize()-1); this.m_Undifferentiated.setTargetSize(this.m_Undifferentiated.getTargetSize()-1);
i--; // needs to be reduced because D0 size has decreased i--; // needs to be reduced because D0 size has decreased
} else { } else {
// the species is inactive and seen as converged, so reinitialize the individual // the species is inactive and seen as converged, so reinitialize the individual
@ -578,7 +578,7 @@ public class ClusterBasedNichingEA implements InterfacePopulationChangedEventLis
// reinitialized individuals and add them to undifferentiated // reinitialized individuals and add them to undifferentiated
this.m_Undifferentiated.addPopulation(this.initializeIndividuals(reinitCount)); this.m_Undifferentiated.addPopulation(this.initializeIndividuals(reinitCount));
// m_Undifferentiated.incrFunctionCallsby(reinitCount); // m_Undifferentiated.incrFunctionCallsby(reinitCount);
this.m_Undifferentiated.setPopulationSize(this.m_Undifferentiated.getPopulationSize()+reinitCount); this.m_Undifferentiated.setTargetSize(this.m_Undifferentiated.getTargetSize()+reinitCount);
} }
} }
} }
@ -639,7 +639,7 @@ public class ClusterBasedNichingEA implements InterfacePopulationChangedEventLis
* @param spec * @param spec
*/ */
protected void deactivateSpecies(Population spec, AbstractEAIndividual survivor) { protected void deactivateSpecies(Population spec, AbstractEAIndividual survivor) {
spec.setPopulationSize(1); spec.setTargetSize(1);
spec.clear(); spec.clear();
spec.add(survivor); spec.add(survivor);
} }
@ -736,7 +736,7 @@ public class ClusterBasedNichingEA implements InterfacePopulationChangedEventLis
this.m_Population = (Population)m_Undifferentiated.clone(); this.m_Population = (Population)m_Undifferentiated.clone();
// m_Population.addPopulation(this.m_Undifferentiated); // m_Population.addPopulation(this.m_Undifferentiated);
for (int i = 0; i < this.m_Species.size(); i++) this.m_Population.addPopulation((Population)this.m_Species.get(i)); for (int i = 0; i < this.m_Species.size(); i++) this.m_Population.addPopulation((Population)this.m_Species.get(i));
m_Population.setPopulationSize(m_Population.size()); // set it to true value m_Population.synchSize(); // set target size to current size
return this.m_Population; return this.m_Population;
} }
@ -753,7 +753,7 @@ public class ClusterBasedNichingEA implements InterfacePopulationChangedEventLis
// return inactive species // return inactive species
Population sols = (Population)m_Archive.clone(); Population sols = (Population)m_Archive.clone();
sols.addPopulation(getPopulation()); sols.addPopulation(getPopulation());
sols.setPopulationSize(sols.size()); sols.synchSize();
return new SolutionSet(getPopulation(), sols); return new SolutionSet(getPopulation(), sols);
} }

View File

@ -4,6 +4,7 @@ import java.io.Serializable;
import eva2.gui.GenericObjectEditor; import eva2.gui.GenericObjectEditor;
import eva2.server.go.InterfacePopulationChangedEventListener; import eva2.server.go.InterfacePopulationChangedEventListener;
import eva2.server.go.PopulationInterface;
import eva2.server.go.enums.PostProcessMethod; import eva2.server.go.enums.PostProcessMethod;
import eva2.server.go.operators.mutation.MutateESFixedStepSize; import eva2.server.go.operators.mutation.MutateESFixedStepSize;
import eva2.server.go.operators.postprocess.PostProcess; import eva2.server.go.operators.postprocess.PostProcess;
@ -12,6 +13,7 @@ import eva2.server.go.populations.Population;
import eva2.server.go.populations.SolutionSet; import eva2.server.go.populations.SolutionSet;
import eva2.server.go.problems.AbstractOptimizationProblem; import eva2.server.go.problems.AbstractOptimizationProblem;
import eva2.server.go.problems.F1Problem; import eva2.server.go.problems.F1Problem;
import eva2.server.go.problems.InterfaceAdditionalPopulationInformer;
import eva2.server.go.problems.InterfaceOptimizationProblem; import eva2.server.go.problems.InterfaceOptimizationProblem;
import eva2.tools.Pair; import eva2.tools.Pair;
@ -31,7 +33,7 @@ import eva2.tools.Pair;
* @author mkron * @author mkron
* *
*/ */
public class ClusteringHillClimbing implements InterfacePopulationChangedEventListener, InterfaceOptimizer, Serializable { public class ClusteringHillClimbing implements InterfacePopulationChangedEventListener, 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;
@ -52,6 +54,7 @@ public class ClusteringHillClimbing implements InterfacePopulationChangedEventLi
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;
public ClusteringHillClimbing() { public ClusteringHillClimbing() {
hideHideable(); hideHideable();
@ -83,6 +86,8 @@ public class ClusteringHillClimbing implements InterfacePopulationChangedEventLi
*/ */
public void hideHideable() { public void hideHideable() {
GenericObjectEditor.setHideProperty(getClass(), "population", true); GenericObjectEditor.setHideProperty(getClass(), "population", true);
setDoReinitialization(isDoReinitialization());
setLocalSearchMethod(getLocalSearchMethod());
} }
public void SetIdentifier(String name) { public void SetIdentifier(String name) {
@ -117,7 +122,7 @@ public class ClusteringHillClimbing implements InterfacePopulationChangedEventLi
mutator = new MutateESFixedStepSize(initialStepSize); mutator = new MutateESFixedStepSize(initialStepSize);
archive = new Population(); archive = new Population();
hideHideable(); hideHideable();
m_Population.setPopulationSize(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);
@ -152,16 +157,26 @@ public class ClusteringHillClimbing implements InterfacePopulationChangedEventLi
m_Population.addPopulationChangedEventListener(this); m_Population.addPopulationChangedEventListener(this);
m_Population.setNotifyEvalInterval(notifyGuiEvery); m_Population.setNotifyEvalInterval(notifyGuiEvery);
Pair<Population, Double> popD; Pair<Population, Double> popD;
if (TRACE) System.out.println("evalCycle: " + hcEvalCycle + ", evals now: " + (2*hcEvalCycle - (m_Population.getFunctionCalls() % hcEvalCycle))); int funCallsBefore=m_Population.getFunctionCalls();
popD = PostProcess.clusterLocalSearch(localSearchMethod, m_Population, (AbstractOptimizationProblem)m_Problem, sigmaClust, 2*hcEvalCycle - (m_Population.getFunctionCalls() % hcEvalCycle), 0.5, mutator); int evalsNow, lastOverhead = (m_Population.getFunctionCalls() % hcEvalCycle);
// (m_Population, (AbstractOptimizationProblem)m_Problem, sigmaClust, hcEvalCycle - (m_Population.getFunctionCalls() % hcEvalCycle), 0.5); if (lastOverhead>0) evalsNow = (2*hcEvalCycle - (m_Population.getFunctionCalls() % hcEvalCycle));
else evalsNow = hcEvalCycle;
do {
if (TRACE) System.out.println("evalCycle: " + hcEvalCycle + ", evals now: " + evalsNow);
popD = PostProcess.clusterLocalSearch(localSearchMethod, m_Population, (AbstractOptimizationProblem)m_Problem, sigmaClust, evalsNow, 0.5, mutator);
// (m_Population, (AbstractOptimizationProblem)m_Problem, sigmaClust, hcEvalCycle - (m_Population.getFunctionCalls() % hcEvalCycle), 0.5);
if (popD.head().getFunctionCalls()==funCallsBefore) {
System.err.println("Bad case, increasing allowed evaluations!");
evalsNow=Math.max(evalsNow++, (int)(evalsNow*1.2));
}
} while (popD.head().getFunctionCalls()==funCallsBefore);
improvement = popD.tail(); improvement = popD.tail();
m_Population = popD.head(); m_Population = popD.head();
if (TRACE) System.out.println("num inds after clusterLS: " + m_Population.size()); if (TRACE) System.out.println("num inds after clusterLS: " + m_Population.size());
popD.head().setGenerationTo(m_Population.getGeneration()+1); popD.head().setGenerationTo(m_Population.getGeneration()+1);
if (improvement < minImprovement) { if (doReinitialization && (improvement < minImprovement)) {
if (TRACE) System.out.println("improvement below " + minImprovement); if (TRACE) System.out.println("improvement below " + minImprovement);
if ((localSearchMethod != PostProcessMethod.hillClimber) || (mutator.getSigma() < stepSizeThreshold)) { // reinit! if ((localSearchMethod != PostProcessMethod.hillClimber) || (mutator.getSigma() < stepSizeThreshold)) { // reinit!
// is performed for nm and cma, and if hc has too low sigma // is performed for nm and cma, and if hc has too low sigma
@ -175,10 +190,10 @@ public class ClusteringHillClimbing implements InterfacePopulationChangedEventLi
Population tmpPop = new Population(); Population tmpPop = new Population();
tmpPop.addPopulationChangedEventListener(null); tmpPop.addPopulationChangedEventListener(null);
tmpPop.setPopulationSize(initialPopSize); tmpPop.setTargetSize(initialPopSize);
this.m_Problem.initPopulation(tmpPop); this.m_Problem.initPopulation(tmpPop);
tmpPop.setSameParams(m_Population); tmpPop.setSameParams(m_Population);
tmpPop.setPopulationSize(initialPopSize); tmpPop.setTargetSize(initialPopSize);
this.m_Problem.evaluate(tmpPop); this.m_Problem.evaluate(tmpPop);
// reset population while keeping function calls etc. // reset population while keeping function calls etc.
@ -245,7 +260,7 @@ public class ClusteringHillClimbing implements InterfacePopulationChangedEventLi
public String getStringRepresentation() { public String getStringRepresentation() {
StringBuffer sbuf = new StringBuffer("Clustering Hill Climbing"); StringBuffer sbuf = new StringBuffer("Clustering Hill Climbing");
sbuf.append(", initial pop size: "); sbuf.append(", initial pop size: ");
sbuf.append(getPopulation().getPopulationSize()); sbuf.append(getPopulation().getTargetSize());
sbuf.append("Optimization Problem: "); sbuf.append("Optimization Problem: ");
sbuf.append(this.m_Problem.getStringRepresentationForProblem(this)); sbuf.append(this.m_Problem.getStringRepresentationForProblem(this));
sbuf.append(this.m_Population.getStringRepresentation()); sbuf.append(this.m_Population.getStringRepresentation());
@ -259,7 +274,8 @@ public class ClusteringHillClimbing implements InterfacePopulationChangedEventLi
} }
public String globalInfo() { public String globalInfo() {
return "Similar to multi-start HC, but clusters the population during optimization to remove redundant individuals for efficiency."; return "Similar to multi-start HC, but clusters the population during optimization to remove redundant individuals for efficiency." +
"If the local search step does not achieve a minimum improvement, the population may be reinitialized.";
} }
/** /**
@ -394,23 +410,32 @@ public class ClusteringHillClimbing implements InterfacePopulationChangedEventLi
public void setLocalSearchMethod(PostProcessMethod localSearchMethod) { public void setLocalSearchMethod(PostProcessMethod localSearchMethod) {
this.localSearchMethod = localSearchMethod; this.localSearchMethod = localSearchMethod;
GenericObjectEditor.setShowProperty(this.getClass(), "stepSizeInitial", localSearchMethod==PostProcessMethod.hillClimber);
GenericObjectEditor.setShowProperty(this.getClass(), "stepSizeThreshold", localSearchMethod==PostProcessMethod.hillClimber);
} }
public String localSearchMethodTipText() { public String localSearchMethodTipText() {
return "Set the method to be used for local search"; return "Set the method to be used for the hill climbing as local search";
} }
// /** public String getAdditionalFileStringHeader(PopulationInterface pop) {
// * @return the mutator return "#Indies";
// */ }
// public InterfaceMutation getMutator() {
// return mutator; public String getAdditionalFileStringValue(PopulationInterface pop) {
// } return ""+m_Population.size();
// }
// /**
// * @param mutator the mutator to set public boolean isDoReinitialization() {
// */ return doReinitialization;
// public void setMutator(InterfaceMutation mutator) { }
// this.mutator = mutator;
// } public void setDoReinitialization(boolean doReinitialization) {
this.doReinitialization = doReinitialization;
GenericObjectEditor.setShowProperty(this.getClass(), "minImprovement", doReinitialization);
}
public String doReinitializationTipText() {
return "Activate reinitialization if no improvement was achieved.";
}
} }

View File

@ -52,7 +52,7 @@ public class EvolutionStrategies implements InterfaceOptimizer, java.io.Serializ
public static final String esMuParam = "EvolutionStrategyMuParameter"; public static final String esMuParam = "EvolutionStrategyMuParameter";
public EvolutionStrategies() { public EvolutionStrategies() {
this.m_Population.setPopulationSize(this.m_Lambda); this.m_Population.setTargetSize(this.m_Lambda);
} }
public EvolutionStrategies(int mu, int lambda, boolean usePlus) { public EvolutionStrategies(int mu, int lambda, boolean usePlus) {
@ -111,7 +111,7 @@ public class EvolutionStrategies implements InterfaceOptimizer, java.io.Serializ
* @param reset If true the population is reset. * @param reset If true the population is reset.
*/ */
public void initByPopulation(Population pop, boolean reset) { public void initByPopulation(Population pop, boolean reset) {
origPopSize = pop.getPopulationSize(); origPopSize = pop.getTargetSize();
// System.out.println("ES: orig popsize is " + origPopSize); // System.out.println("ES: orig popsize is " + origPopSize);
this.m_Population = (Population)pop.clone(); this.m_Population = (Population)pop.clone();
if (reset) { if (reset) {
@ -368,9 +368,9 @@ public class EvolutionStrategies implements InterfaceOptimizer, java.io.Serializ
System.err.println("Invalid mu/lambda ratio! Setting mu=lambda="+m_Mu); System.err.println("Invalid mu/lambda ratio! Setting mu=lambda="+m_Mu);
this.m_Lambda = this.m_Mu; this.m_Lambda = this.m_Mu;
} }
if (this.m_UsePlusStrategy) this.m_Population.setPopulationSize(this.m_Mu + this.m_Lambda); if (this.m_UsePlusStrategy) this.m_Population.setTargetSize(this.m_Mu + this.m_Lambda);
else this.m_Population.setPopulationSize(this.m_Lambda); else this.m_Population.setTargetSize(this.m_Lambda);
origPopSize=m_Population.getPopulationSize(); origPopSize=m_Population.getTargetSize();
} }
/** This method allows you to set an identifier for the algorithm /** This method allows you to set an identifier for the algorithm

View File

@ -39,7 +39,7 @@ public class FloodAlgorithm implements InterfaceOptimizer, java.io.Serializable
public FloodAlgorithm() { public FloodAlgorithm() {
this.m_Population = new Population(); this.m_Population = new Population();
this.m_Population.setPopulationSize(10); this.m_Population.setTargetSize(10);
} }
public FloodAlgorithm(FloodAlgorithm a) { public FloodAlgorithm(FloodAlgorithm a) {

View File

@ -110,7 +110,7 @@ public class GeneticAlgorithm implements InterfaceOptimizer, java.io.Serializabl
//System.out.println("Population:"+this.m_Population.getSolutionRepresentationFor()); //System.out.println("Population:"+this.m_Population.getSolutionRepresentationFor());
this.m_ParentSelection.prepareSelection(this.m_Population); this.m_ParentSelection.prepareSelection(this.m_Population);
this.m_PartnerSelection.prepareSelection(this.m_Population); this.m_PartnerSelection.prepareSelection(this.m_Population);
parents = this.m_ParentSelection.selectFrom(this.m_Population, this.m_Population.getPopulationSize()); parents = this.m_ParentSelection.selectFrom(this.m_Population, this.m_Population.getTargetSize());
//System.out.println("Parents:"+parents.getSolutionRepresentationFor()); //System.out.println("Parents:"+parents.getSolutionRepresentationFor());
if (parents.getEAIndividual(0).getMutationOperator() instanceof InterfaceMutationGenerational) { if (parents.getEAIndividual(0).getMutationOperator() instanceof InterfaceMutationGenerational) {
@ -153,7 +153,7 @@ public class GeneticAlgorithm implements InterfaceOptimizer, java.io.Serializabl
} }
if (this.m_Plague > 0) { if (this.m_Plague > 0) {
for (int i = 0; i < this.m_Plague; i++) if (this.m_Population.size() > 2) this.m_Population.remove(this.m_Population.getWorstEAIndividual()); for (int i = 0; i < this.m_Plague; i++) if (this.m_Population.size() > 2) this.m_Population.remove(this.m_Population.getWorstEAIndividual());
this.m_Population.setPopulationSize(this.m_Population.size()); this.m_Population.setTargetSize(this.m_Population.size());
} }
//System.out.println("Population size: " + this.m_Population.size()); //System.out.println("Population size: " + this.m_Population.size());
// if (this.m_Population.getArchive() != null) { // if (this.m_Population.getArchive() != null) {
@ -203,7 +203,7 @@ public class GeneticAlgorithm implements InterfaceOptimizer, java.io.Serializabl
String result = ""; String result = "";
result += "Genetic Algorithm:\n"; result += "Genetic Algorithm:\n";
result += "Using:\n"; result += "Using:\n";
result += " Population Size = " + this.m_Population.getPopulationSize() + "/" + this.m_Population.size() + "\n"; result += " Population Size = " + this.m_Population.getTargetSize() + "/" + this.m_Population.size() + "\n";
result += " Parent Selection = " + this.m_ParentSelection.getClass().toString() + "\n"; result += " Parent Selection = " + this.m_ParentSelection.getClass().toString() + "\n";
result += " Partner Selection = " + this.m_PartnerSelection.getClass().toString() + "\n"; result += " Partner Selection = " + this.m_PartnerSelection.getClass().toString() + "\n";
result += " Number of Partners = " + this.m_NumberOfPartners + "\n"; result += " Number of Partners = " + this.m_NumberOfPartners + "\n";

View File

@ -1,7 +1,5 @@
package eva2.server.go.strategies; package eva2.server.go.strategies;
import java.util.*;
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.InterfaceDataTypeDouble; import eva2.server.go.individuals.InterfaceDataTypeDouble;
@ -11,45 +9,53 @@ import eva2.server.go.populations.SolutionSet;
import eva2.server.go.problems.F1Problem; import eva2.server.go.problems.F1Problem;
import eva2.server.go.problems.InterfaceFirstOrderDerivableProblem; import eva2.server.go.problems.InterfaceFirstOrderDerivableProblem;
import eva2.server.go.problems.InterfaceOptimizationProblem; import eva2.server.go.problems.InterfaceOptimizationProblem;
import eva2.tools.EVAERROR;
/** /**
* A gradient descent algorithm by hannes planatscher don't expect any * A gradient descent algorithm by hannes planatscher don't expect any
* descriptions here... *big sigh* * descriptions here... *big sigh*
* *
* mkron added some!
*
* @author not attributable * @author not attributable
* @version 1.0 * @version 1.0
*/ */
public class GradientDescentAlgorithm implements InterfaceOptimizer, java.io.Serializable { public class GradientDescentAlgorithm implements InterfaceOptimizer, java.io.Serializable {
private InterfaceOptimizationProblem m_Problem; private InterfaceOptimizationProblem m_Problem;
InterfaceDataTypeDouble m_Best, m_Test; InterfaceDataTypeDouble m_Best, m_Test;
private int iterations = 1; private int iterations = 1;
private double localnminus = 0.5; private double wDecreaseStepSize = 0.5;
private double localnplus = 1.1; private double wIncreaseStepSize = 1.1;
boolean recovery = false; boolean recovery = false;
private int recoverylocksteps = 5; private int recoverylocksteps = 5;
private double recoverythreshold = 100000; private double recoverythreshold = 100000;
boolean localstepsizeadaption = true; boolean localStepSizeAdaption = true;
boolean globalstepsizeadaption = true; boolean globalStepSizeAdaption = false;
private double globalinitstepsize = 1; private double globalinitstepsize = 1;
double globalmaxstepsize = 3.0; double globalmaxstepsize = 3.0;
double globalminstepsize = 0.1; double globalminstepsize = 0.0001;
boolean manhattan = false; boolean manhattan = false;
double localmaxstepsize = 10; double localmaxstepsize = 10;
double localminstepsize = 0.1; double localminstepsize = 0.0001;
private boolean momentumterm = false; private boolean momentumterm = false;
transient private InterfacePopulationChangedEventListener m_Listener; transient private InterfacePopulationChangedEventListener m_Listener;
public double maximumabsolutechange = 0.2; public double maximumabsolutechange = 0.2;
Hashtable indyhash; // Hashtable indyhash;
// These variables are necessary for the more complex LectureGUI enviroment // These variables are necessary for the more complex LectureGUI enviroment
transient private String m_Identifier = ""; transient private String m_Identifier = "";
private Population m_Population; private Population m_Population;
private InterfaceDataTypeDouble InterfaceDataTypeDouble;
private static final String lockKey = "gdaLockDataKey";
private static final String lastFitnessKey = "gdaLastFitDataKey";
private static final String stepSizeKey = "gdaStepSizeDataKey";
private static final String wStepSizeKey = "gdaWStepSizeDataKey";
private static final String gradientKey = "gdaGradientDataKey";
private static final String changesKey = "gdaChangesDataKey";
private static final String oldParamsKey = "gdaOldParamsDataKey";
public void initByPopulation(Population pop, boolean reset) { public void initByPopulation(Population pop, boolean reset) {
this.setPopulation((Population) pop.clone()); this.setPopulation((Population) pop.clone());
@ -59,16 +65,15 @@ public class GradientDescentAlgorithm implements InterfaceOptimizer, java.io.Ser
this.firePropertyChangedEvent(Population.nextGenerationPerformed); this.firePropertyChangedEvent(Population.nextGenerationPerformed);
} }
//System.out.println("initByPopulation() called"); //System.out.println("initByPopulation() called");
indyhash = new Hashtable(); // indyhash = new Hashtable();
} }
public GradientDescentAlgorithm() { public GradientDescentAlgorithm() {
indyhash = new Hashtable(); // indyhash = new Hashtable();
this.m_Population = new Population(); this.m_Population = new Population();
this.m_Population.setPopulationSize(1); this.m_Population.setTargetSize(1);
} }
public Object clone() { public Object clone() {
/**@todo Implement InterfaceOptimizer method*/ /**@todo Implement InterfaceOptimizer method*/
throw new java.lang.UnsupportedOperationException("Method clone() not yet implemented."); throw new java.lang.UnsupportedOperationException("Method clone() not yet implemented.");
@ -78,15 +83,13 @@ public class GradientDescentAlgorithm implements InterfaceOptimizer, java.io.Ser
return "GradientDescentAlgorithm"; return "GradientDescentAlgorithm";
} }
public void init() { public void init() {
//System.out.println("init() called "); //System.out.println("init() called ");
indyhash = new Hashtable(); // indyhash = new Hashtable();
this.m_Problem.initPopulation(this.m_Population); this.m_Problem.initPopulation(this.m_Population);
this.m_Problem.evaluate(this.m_Population); this.m_Problem.evaluate(this.m_Population);
} }
public double signum(double val) { public double signum(double val) {
return (val < 0) ? -1 : 1; return (val < 0) ? -1 : 1;
} }
@ -94,23 +97,23 @@ public class GradientDescentAlgorithm implements InterfaceOptimizer, java.io.Ser
public void optimize() { public void optimize() {
// System.out.println("opt. called"); // System.out.println("opt. called");
AbstractEAIndividual indy; AbstractEAIndividual indy;
if ((this.indyhash == null) || (this.indyhash.size() <1)) init(); // if ((this.indyhash == null) || (this.indyhash.size() <1)) init();
for (int i = 0; i < this.m_Population.size(); i++) { for (int i = 0; i < this.m_Population.size(); i++) {
indy = ((AbstractEAIndividual)this.m_Population.get(i)); indy = ((AbstractEAIndividual)this.m_Population.get(i));
if (!indyhash.containsKey(indy)) { if (!indy.hasData(gradientKey)) {
//System.out.println("new indy to hash"); //System.out.println("new indy to hash");
Hashtable history = new Hashtable(); // Hashtable history = new Hashtable();
int[] lock = new int[((InterfaceDataTypeDouble) indy).getDoubleData().length]; int[] lock = new int[((InterfaceDataTypeDouble) indy).getDoubleData().length];
double[] wstepsize = new double[((InterfaceDataTypeDouble) indy).getDoubleData().length]; double[] wstepsize = new double[((InterfaceDataTypeDouble) indy).getDoubleData().length];
for (int li = 0; li < lock.length; li++) lock[li] = 0; for (int li = 0; li < lock.length; li++) lock[li] = 0;
for (int li = 0; li < lock.length; li++) wstepsize[li] = 1.0; for (int li = 0; li < lock.length; li++) wstepsize[li] = 1.0;
double fitness = 0; double fitness = 0;
history.put("lock", lock); indy.putData(lockKey, lock);
history.put("lastfitness", new Double(fitness)); indy.putData(lastFitnessKey, new Double(fitness));
history.put("stepsize", new Double(globalinitstepsize)); indy.putData(stepSizeKey, new Double(globalinitstepsize));
history.put("wstepsize", wstepsize); indy.putData(wStepSizeKey, wstepsize);
indyhash.put(indy, history); // indyhash.put(indy, history);
} else { } else {
//System.out.println("indy already in hash"); //System.out.println("indy already in hash");
} }
@ -121,48 +124,49 @@ public class GradientDescentAlgorithm implements InterfaceOptimizer, java.io.Ser
indy = ((AbstractEAIndividual)this.m_Population.get(i)); indy = ((AbstractEAIndividual)this.m_Population.get(i));
double[][] range = ((InterfaceDataTypeDouble) indy).getDoubleRange(); double[][] range = ((InterfaceDataTypeDouble) indy).getDoubleRange();
double[] params = ((InterfaceDataTypeDouble) indy).getDoubleData(); double[] params = ((InterfaceDataTypeDouble) indy).getDoubleData();
indy.putData(oldParamsKey , params);
int[] lock = (int[]) ((Hashtable) indyhash.get(indy)).get("lock"); int[] lock = (int[]) indy.getData(lockKey);
double indystepsize = ((Double) ((Hashtable) indyhash.get(indy)).get("stepsize")).doubleValue(); double indystepsize = ((Double) indy.getData(stepSizeKey)).doubleValue();
// System.out.println("indystepsize" + indystepsize); // System.out.println("indystepsize" + indystepsize);
if ((this.m_Problem instanceof InterfaceFirstOrderDerivableProblem) && (indy instanceof InterfaceDataTypeDouble)) { if ((this.m_Problem instanceof InterfaceFirstOrderDerivableProblem) && (indy instanceof InterfaceDataTypeDouble)) {
Hashtable history = (Hashtable) indyhash.get(indy); // Hashtable history = (Hashtable) indyhash.get(indy);
for (int iterations = 0; iterations < this.iterations; iterations++) { for (int iterations = 0; iterations < this.iterations; iterations++) {
double[] oldgradient = (double[]) history.get("gradient"); double[] oldgradient = indy.hasData(gradientKey) ? (double[]) indy.getData(gradientKey) : null;
double[] wstepsize = (double[]) history.get("wstepsize"); double[] wstepsize = (double[]) indy.getData(wStepSizeKey);
double[] oldchange = null; double[] oldchange = null;
double[] gradient = ((InterfaceFirstOrderDerivableProblem) m_Problem).getFirstOrderGradients(params); double[] gradient = ((InterfaceFirstOrderDerivableProblem) m_Problem).getFirstOrderGradients(params);
if ((oldgradient != null) && (wstepsize != null)) { if ((oldgradient != null) && (wstepsize != null)) { // LOCAL adaption
for (int li = 0; li < wstepsize.length; li++) { for (int li = 0; li < wstepsize.length; li++) {
double prod = gradient[li] * oldgradient[li]; double prod = gradient[li] * oldgradient[li];
if (prod < 0) { if (prod < 0) {
wstepsize[li] = localnminus * wstepsize[li]; wstepsize[li] = wDecreaseStepSize * wstepsize[li];
} else if (prod > 0) { } else if (prod > 0) {
wstepsize[li] = localnplus * wstepsize[li]; wstepsize[li] = wIncreaseStepSize * wstepsize[li];
} }
wstepsize[li] = (wstepsize[li] < localminstepsize) ? localminstepsize : wstepsize[li]; wstepsize[li] = (wstepsize[li] < localminstepsize) ? localminstepsize : wstepsize[li];
wstepsize[li] = (wstepsize[li] > localmaxstepsize) ? localmaxstepsize : wstepsize[li]; wstepsize[li] = (wstepsize[li] > localmaxstepsize) ? localmaxstepsize : wstepsize[li];
//System.out.println("wstepsize "+ li + " " + wstepsize[li]); // System.out.println("wstepsize "+ li + " " + wstepsize[li]);
} }
} }
double[] newparams = new double[params.length]; double[] newparams = new double[params.length];
history.put("gradient", gradient); indy.putData(gradientKey, gradient);
double[] change = new double[params.length]; double[] change = new double[params.length];
if (history.containsKey("changes")) { if (indy.hasData(changesKey)) {
oldchange =(double[]) history.get("changes"); oldchange =(double[]) indy.getData(changesKey);
} }
boolean dograddesc = (this.momentumterm) && (oldchange != null); boolean dograddesc = (this.momentumterm) && (oldchange != null);
for (int j = 0; j < newparams.length; j++) { for (int j = 0; j < newparams.length; j++) {
if (lock[j] == 0) { if (lock[j] == 0) {
double tempstepsize = 1; double tempstepsize = 1;
if (this.localstepsizeadaption) tempstepsize = tempstepsize *wstepsize[j]; if (this.localStepSizeAdaption) tempstepsize = tempstepsize * wstepsize[j];
if (this.globalstepsizeadaption) tempstepsize = tempstepsize *indystepsize; if (this.globalStepSizeAdaption) tempstepsize = tempstepsize * indystepsize;
double wchange = signum(tempstepsize * gradient[j]) * Math.min(maximumabsolutechange,Math.abs(tempstepsize * gradient[j])); //indystepsize * gradient[j]; double wchange = signum(tempstepsize * gradient[j]) * Math.min(maximumabsolutechange,Math.abs(tempstepsize * gradient[j])); //indystepsize * gradient[j];
if (this.manhattan) wchange = this.signum(wchange) * tempstepsize; if (this.manhattan) wchange = this.signum(wchange) * tempstepsize;
if (dograddesc) { if (dograddesc) {
@ -181,26 +185,31 @@ public class GradientDescentAlgorithm implements InterfaceOptimizer, java.io.Ser
} }
params = newparams; params = newparams;
history.put("changes", change); indy.putData(changesKey, change);
} } // end loop iterations
((InterfaceDataTypeDouble) indy).SetDoubleGenotype(params); ((InterfaceDataTypeDouble) indy).SetDoubleGenotype(params);
} // end if ((this.m_Problem instanceof InterfaceFirstOrderDerivableProblem) && (indy instanceof InterfaceDataTypeDouble)) {
else {
String msg="Warning, problem of type InterfaceFirstOrderDerivableProblem and template of type InterfaceDataTypeDouble is required for " + this.getClass();
EVAERROR.errorMsgOnce(msg);
throw new RuntimeException(msg);
} }
} } // for loop population size
this.m_Problem.evaluate(this.m_Population); this.m_Problem.evaluate(this.m_Population);
if (this.recovery) { if (this.recovery) {
for (int i = 0; i < this.m_Population.size(); i++) { for (int i = 0; i < this.m_Population.size(); i++) {
indy = ((AbstractEAIndividual)this.m_Population.get(i)); indy = ((AbstractEAIndividual)this.m_Population.get(i));
Hashtable history = (Hashtable) indyhash.get(indy); // Hashtable history = (Hashtable) indyhash.get(indy);
if (indy.getFitness()[0] > recoverythreshold) { if (indy.getFitness()[0] > recoverythreshold) {
System.out.println("Gradient Descent: Fitness critical:" + indy.getFitness()[0]); System.out.println("Gradient Descent: Fitness critical:" + indy.getFitness()[0]);
((InterfaceDataTypeDouble) indy).SetDoublePhenotype((double[]) history.get("params")); ((InterfaceDataTypeDouble) indy).SetDoublePhenotype((double[]) indy.getData(oldParamsKey));
double[] changes = (double[]) history.get("changes"); double[] changes = (double[]) indy.getData(changesKey);
int[] lock = (int[]) history.get("lock"); int[] lock = (int[]) indy.getData(lockKey);
int indexmaxchange = 0; int indexmaxchange = 0;
double maxchangeval = Double.NEGATIVE_INFINITY; double maxchangeval = Double.NEGATIVE_INFINITY;
@ -211,37 +220,37 @@ public class GradientDescentAlgorithm implements InterfaceOptimizer, java.io.Ser
} }
} }
lock[indexmaxchange] = recoverylocksteps; lock[indexmaxchange] = recoverylocksteps;
history.put("lock", lock); indy.putData(lockKey, lock);
} else { } else {
} }
} }
this.m_Problem.evaluate(this.m_Population); this.m_Problem.evaluate(this.m_Population);
} }
if (this.globalstepsizeadaption) { if (this.globalStepSizeAdaption) {
//System.out.println("gsa main"); //System.out.println("gsa main");
for (int i = 0; i < this.m_Population.size(); i++) { for (int i = 0; i < this.m_Population.size(); i++) {
indy = ((AbstractEAIndividual)this.m_Population.get(i)); indy = ((AbstractEAIndividual)this.m_Population.get(i));
Hashtable history = (Hashtable) indyhash.get(indy); // Hashtable history = (Hashtable) indyhash.get(indy);
if (history == null) break; // if (history == null) break;
if (history.get("lastfitness") != null) { if (indy.getData(lastFitnessKey) != null) {
double lastfit = ((Double) history.get("lastfitness")).doubleValue(); double lastfit = ((Double) indy.getData(lastFitnessKey)).doubleValue();
double indystepsize = ((Double) history.get("stepsize")).doubleValue(); double indystepsize = ((Double) indy.getData(stepSizeKey)).doubleValue();
if (lastfit < indy.getFitness()[0]) { if (lastfit < indy.getFitness()[0]) { // GLOBAL adaption
indystepsize *= 0.5; indystepsize *= wDecreaseStepSize;
} else { } else {
indystepsize *= 1.1; indystepsize *= wIncreaseStepSize;
} }
//System.out.println("newstepsize" + indystepsize); //System.out.println("newstepsize" + indystepsize);
indystepsize = (indystepsize > globalmaxstepsize) ? globalmaxstepsize : indystepsize; indystepsize = (indystepsize > globalmaxstepsize) ? globalmaxstepsize : indystepsize;
indystepsize = (indystepsize < globalminstepsize) ? globalminstepsize : indystepsize; indystepsize = (indystepsize < globalminstepsize) ? globalminstepsize : indystepsize;
history.put("stepsize", new Double(indystepsize)); indy.putData(stepSizeKey, new Double(indystepsize));
} }
//System.out.println("newstepsize in bounds" + indystepsize); //System.out.println("newstepsize in bounds" + indystepsize);
history.put("lastfitness", new Double(indy.getFitness()[0])); indy.putData(lastFitnessKey, new Double(indy.getFitness()[0]));
} }
} }
@ -265,11 +274,11 @@ public class GradientDescentAlgorithm implements InterfaceOptimizer, java.io.Ser
} }
public void setPopulation(Population pop) { public void setPopulation(Population pop) {
Hashtable newindyhash = new Hashtable(); // Hashtable newindyhash = new Hashtable();
for (int i = 0; i < pop.size(); i++) { // for (int i = 0; i < pop.size(); i++) {
if (indyhash.contains(pop.get(i))) newindyhash.put(pop.get(i), indyhash.get(pop.get(i))); // if (indyhash.contains(pop.get(i))) newindyhash.put(pop.get(i), indyhash.get(pop.get(i)));
} // }
indyhash = newindyhash; // indyhash = newindyhash;
this.m_Population = pop; this.m_Population = pop;
} }
@ -298,7 +307,6 @@ public class GradientDescentAlgorithm implements InterfaceOptimizer, java.io.Ser
return "GradientDescentAlgorithm"; return "GradientDescentAlgorithm";
} }
public void addPopulationChangedEventListener(InterfacePopulationChangedEventListener ea) { public void addPopulationChangedEventListener(InterfacePopulationChangedEventListener ea) {
this.m_Listener = ea; this.m_Listener = ea;
} }
@ -324,143 +332,163 @@ public class GradientDescentAlgorithm implements InterfaceOptimizer, java.io.Ser
} }
} }
public void freeWilly() { }
public String globalInfo() {
public void freeWilly() { return "Gradient Descent can be applied to derivable functions ("+InterfaceFirstOrderDerivableProblem.class.getSimpleName()+").";
}
//////////////// for global adaption
public boolean isAdaptStepSizeGlobally() {
return globalStepSizeAdaption;
}
public void setAdaptStepSizeGlobally(boolean globalstepsizeadaption) {
this.globalStepSizeAdaption = globalstepsizeadaption;
if (globalstepsizeadaption && localStepSizeAdaption) setAdaptStepSizeLocally(false);
}
public String adaptStepSizeGloballyTipText() {
return "Use a single step size per individual - (priority over local step size).";
} }
public double getGlobalMaxStepSize() {
public double getGlobalMaxstepsize() {
return globalmaxstepsize; return globalmaxstepsize;
} }
public void setGlobalMaxStepSize(double p) {
public void setGlobalMaxstepsize(double p) {
globalmaxstepsize = p; globalmaxstepsize = p;
} }
public String globalMaxStepSizeTipText() {
return "Maximum step size for global adaption.";
}
public double getGlobalMinStepSize() {
public double getGlobalMinstepsize() {
return globalminstepsize; return globalminstepsize;
} }
public void setGlobalMinStepSize(double p) {
public void setGlobalMinstepsize(double p) {
globalminstepsize = p; globalminstepsize = p;
} }
public String globalMindStepSizeTipText() {
public int getRecoveryLocksteps() { return "Minimum step size for global adaption.";
return recoverylocksteps;
} }
public void setRecoveryLocksteps(int locksteps) { public double getGlobalInitStepSize() {
this.recoverylocksteps = locksteps;
}
public double getGlobalInitstepsize() {
return globalinitstepsize; return globalinitstepsize;
} }
public void setGlobalInitStepSize(double initstepsize) {
public void setGlobalInitstepsize(double initstepsize) {
this.globalinitstepsize = initstepsize; this.globalinitstepsize = initstepsize;
} }
public boolean isLocalStepsizeadaption() { public String globalInitStepSizeTipText() {
return localstepsizeadaption; return "Initial step size for global adaption.";
} }
public void setLocalStepsizeadaption(boolean stepsizeadaption) {
this.localstepsizeadaption = stepsizeadaption; //////////////// for local adaption
public boolean isAdaptStepSizeLocally() {
return localStepSizeAdaption;
} }
public void setAdaptStepSizeLocally(boolean stepsizeadaption) {
this.localStepSizeAdaption = stepsizeadaption;
if (globalStepSizeAdaption && localStepSizeAdaption) setAdaptStepSizeGlobally(false);
}
public String adaptStepSizeLocallyTipText() {
return "Use a step size parameter in any dimension.";
}
public double getLocalMinStepSize() {
return localminstepsize;
}
public void setLocalMinStepSize(double localminstepsize) {
this.localminstepsize = localminstepsize;
}
public double getLocalMaxStepSize() {
return localmaxstepsize;
}
public void setLocalMaxStepSize(double localmaxstepsize) {
this.localmaxstepsize = localmaxstepsize;
}
public void setStepSizeIncreaseFact(double nplus) {
this.wIncreaseStepSize = nplus;
}
public double getStepSizeIncreaseFact() {
return wIncreaseStepSize;
}
public String stepSizeIncreaseFactTipText() {
return "Factor for increasing the step size in adaption.";
}
public void setStepSizeDecreaseFact(double nminus) {
this.wDecreaseStepSize = nminus;
}
public double getStepSizeDecreaseFact() {
return wDecreaseStepSize;
}
public String stepSizeDecreaseFactTipText() {
return "Factor for decreasing the step size in adaption.";
}
//////////////// concerning recovery
public boolean isRecovery() { public boolean isRecovery() {
return recovery; return recovery;
} }
public void setRecovery(boolean recovery) { public void setRecovery(boolean recovery) {
this.recovery = recovery; this.recovery = recovery;
} }
public double getLocalNplus() { public int getRecoveryLocksteps() {
return localnplus; return recoverylocksteps;
} }
public double getLocalNminus() { public void setRecoveryLocksteps(int locksteps) {
return localnminus; this.recoverylocksteps = locksteps;
} }
public void setLocalNplus(double nplus) { public double getRecoveryThreshold() {
this.localnplus = nplus; return recoverythreshold;
} }
public void setLocalNminus(double nminus) { public void setRecoveryThreshold(double recoverythreshold) {
this.localnminus = nminus; this.recoverythreshold = recoverythreshold;
} }
public String recoveryThresholdTipText() {
return "If the fitness exceeds this threshold, an unstable area is assumed and one step recovered.";
}
public int getIterations() { public int getIterations() {
return iterations; return iterations;
} }
public void setIterations(int iterations) { public void setIterations(int iterations) {
this.iterations = iterations; this.iterations = iterations;
} }
public boolean isGlobalstepsizeadaption() { public String iterationsTipText() {
return globalstepsizeadaption; return "The number of GD-iterations per generation.";
}
public void setGlobalstepsizeadaption(boolean globalstepsizeadaption) {
this.globalstepsizeadaption = globalstepsizeadaption;
}
public double getLocalminstepsize() {
return localminstepsize;
}
public double getLocalmaxstepsize() {
return localmaxstepsize;
}
public void setLocalminstepsize(double localminstepsize) {
this.localminstepsize = localminstepsize;
}
public void setLocalmaxstepsize(double localmaxstepsize) {
this.localmaxstepsize = localmaxstepsize;
} }
public boolean isManhattan() { public boolean isManhattan() {
return manhattan; return manhattan;
} }
public boolean isMomentumTerm() {
return momentumterm;
}
public double getMomentumweigth() {
return momentumweigth;
}
public void setManhattan(boolean manhattan) { public void setManhattan(boolean manhattan) {
this.manhattan = manhattan; this.manhattan = manhattan;
} }
public boolean isMomentumTerm() {
return momentumterm;
}
public void setMomentumTerm(boolean momentum) { public void setMomentumTerm(boolean momentum) {
this.momentumterm = momentum; this.momentumterm = momentum;
} }
public void setMomentumweigth(double momentumweigth) { public double getMomentumWeigth() {
return momentumweigth;
}
public void setMomentumWeigth(double momentumweigth) {
this.momentumweigth = momentumweigth; this.momentumweigth = momentumweigth;
} }
public void setPopulationSize(int p) { public double getMaximumAbsoluteChange() {
this.getPopulation().setPopulationSize(p);
}
public int GetPopulationSize() {
return this.getPopulation().getPopulationSize();
}
public double getRecoverythreshold() {
return recoverythreshold;
}
public void setRecoverythreshold(double recoverythreshold) {
this.recoverythreshold = recoverythreshold;
}
public double getMaximumabsolutechange() {
return maximumabsolutechange; return maximumabsolutechange;
} }
public void setMaximumAbsoluteChange(double maximumabsolutechange) {
public void setMaximumabsolutechange(double maximumabsolutechange) {
this.maximumabsolutechange = maximumabsolutechange; this.maximumabsolutechange = maximumabsolutechange;
} }
public String maximumAbsoluteChangeTipText() {
return "The maximum change along a coordinate in one step.";
}
} }

View File

@ -38,7 +38,7 @@ public class HillClimbing implements InterfaceOptimizer, java.io.Serializable {
public HillClimbing() { public HillClimbing() {
this.m_Population = new Population(); this.m_Population = new Population();
this.m_Population.setPopulationSize(10); this.m_Population.setTargetSize(10);
} }
public HillClimbing(HillClimbing a) { public HillClimbing(HillClimbing a) {

View File

@ -336,7 +336,7 @@ public class IslandModelEA implements InterfacePopulationChangedEventListener, I
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().setPopulationSize(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());

View File

@ -42,7 +42,7 @@ public class MonteCarloSearch implements InterfaceOptimizer, java.io.Serializabl
public MonteCarloSearch() { public MonteCarloSearch() {
this.m_Population = new Population(); this.m_Population = new Population();
this.m_Population.setPopulationSize(50); this.m_Population.setTargetSize(50);
} }
public MonteCarloSearch(MonteCarloSearch a) { public MonteCarloSearch(MonteCarloSearch a) {

View File

@ -48,7 +48,7 @@ public class MultiObjectiveEA implements InterfaceOptimizer, java.io.Serializabl
transient private InterfacePopulationChangedEventListener m_Listener; transient private InterfacePopulationChangedEventListener m_Listener;
public MultiObjectiveEA() { public MultiObjectiveEA() {
this.m_Optimizer.getPopulation().setPopulationSize(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());
} }
@ -297,7 +297,7 @@ public class MultiObjectiveEA implements InterfaceOptimizer, java.io.Serializabl
archive = new Population(); archive = new Population();
this.m_Optimizer.getPopulation().SetArchive(archive); this.m_Optimizer.getPopulation().SetArchive(archive);
} }
return archive.getPopulationSize(); 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();
@ -305,7 +305,7 @@ public class MultiObjectiveEA implements InterfaceOptimizer, java.io.Serializabl
archive = new Population(); archive = new Population();
this.m_Optimizer.getPopulation().SetArchive(archive); this.m_Optimizer.getPopulation().SetArchive(archive);
} }
archive.setPopulationSize(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

@ -312,8 +312,8 @@ public class NelderMeadSimplex implements InterfaceOptimizer, Serializable, Inte
public void setPopulationSize(int populationSize) { public void setPopulationSize(int populationSize) {
this.populationSize = populationSize; this.populationSize = populationSize;
if (m_Population!=null) { if (m_Population!=null) {
m_Population.setPopulationSize(populationSize); m_Population.setTargetSize(populationSize);
m_Population.setNotifyEvalInterval(m_Population.getPopulationSize()); m_Population.setNotifyEvalInterval(m_Population.getTargetSize());
} }
} }
@ -430,7 +430,7 @@ public class NelderMeadSimplex implements InterfaceOptimizer, Serializable, Inte
indy.resetConstraintViolation(); indy.resetConstraintViolation();
initialPop.add((AbstractEAIndividual)indy.clone()); initialPop.add((AbstractEAIndividual)indy.clone());
} }
initialPop.setPopulationSize(initialPop.size()); initialPop.synchSize();
} }
/** /**

View File

@ -100,7 +100,7 @@ public class ParticleFilterOptimization implements InterfaceOptimizer, java.io.S
} else { } else {
(((AbstractOptimizationProblem)m_Problem).getIndividualTemplate()).setMutationOperator(new MutateESCorrVector(mutationSigma, initialVelocity, rotationDeg)); (((AbstractOptimizationProblem)m_Problem).getIndividualTemplate()).setMutationOperator(new MutateESCorrVector(mutationSigma, initialVelocity, rotationDeg));
} }
m_Population.setPopSize(popSize); m_Population.setTargetSize(popSize);
this.m_Problem.initPopulation(this.m_Population); this.m_Problem.initPopulation(this.m_Population);
setWithShow(withShow); setWithShow(withShow);
@ -144,13 +144,13 @@ public class ParticleFilterOptimization implements InterfaceOptimizer, java.io.S
// 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.getPopulationSize(); int targetSize = this.m_Population.getTargetSize();
if (randomImmigrationQuota>0) { if (randomImmigrationQuota>0) {
if (randomImmigrationQuota>1.) System.err.println("Error, invalid immigration quota!"); if (randomImmigrationQuota>1.) System.err.println("Error, invalid immigration quota!");
else { else {
targetSize = (int)(this.m_Population.getPopulationSize() * (1.-randomImmigrationQuota)); targetSize = (int)(this.m_Population.getTargetSize() * (1.-randomImmigrationQuota));
targetSize = Math.max(1, targetSize); // guarantee at least one to be selected targetSize = Math.max(1, targetSize); // guarantee at least one to be selected
if (targetSize < this.m_Population.getPopulationSize()) doImmigr=true; if (targetSize < this.m_Population.getTargetSize()) doImmigr=true;
} }
} }
@ -160,7 +160,7 @@ public class ParticleFilterOptimization implements InterfaceOptimizer, java.io.S
// add immigrants // add immigrants
AbstractEAIndividual immi; AbstractEAIndividual immi;
int i; int i;
for (i=0; (i+parents.getPopulationSize())<pop.getPopulationSize(); 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);
@ -181,7 +181,7 @@ public class ParticleFilterOptimization implements InterfaceOptimizer, java.io.S
if (withShow) { if (withShow) {
drawPop(pop, 0, false); drawPop(pop, 0, false);
} }
for (int i = 0; i < pop.getPopulationSize(); 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++;
} }
@ -454,6 +454,6 @@ public class ParticleFilterOptimization implements InterfaceOptimizer, java.io.S
public void setPopSize(int popSize) { public void setPopSize(int popSize) {
this.popSize = popSize; this.popSize = popSize;
m_Population.setPopSize(popSize); m_Population.setTargetSize(popSize);
} }
} }

View File

@ -1569,17 +1569,12 @@ public class ParticleSwarmOptimization implements InterfaceOptimizer, java.io.Se
return "PSO-"+getTopology()+getTopologyRange()+"_"+getPhi1()+"_"+getPhi2(); return "PSO-"+getTopology()+getTopologyRange()+"_"+getPhi1()+"_"+getPhi2();
} }
/** 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.
*/
public Population getPopulation() { public Population getPopulation() {
return this.m_Population; return this.m_Population;
} }
public void setPopulation(Population pop){ public void setPopulation(Population pop){
this.m_Population = pop; this.m_Population = pop;
if (pop.size() != pop.getPopulationSize()) { // new particle count! if (pop.size() != pop.getTargetSize()) { // new particle count!
tracedVelocity = null; tracedVelocity = null;
initByPopulation(null, false); initByPopulation(null, false);
} else for (int i=0; i<pop.size(); i++) { } else for (int i=0; i<pop.size(); i++) {

View File

@ -37,7 +37,7 @@ public class SimulatedAnnealing implements InterfaceOptimizer, java.io.Serializa
public SimulatedAnnealing() { public SimulatedAnnealing() {
this.m_Population = new Population(); this.m_Population = new Population();
this.m_Population.setPopulationSize(10); this.m_Population.setTargetSize(10);
} }
public SimulatedAnnealing(SimulatedAnnealing a) { public SimulatedAnnealing(SimulatedAnnealing a) {

View File

@ -35,7 +35,7 @@ public class ThresholdAlgorithm implements InterfaceOptimizer, java.io.Serializa
public ThresholdAlgorithm() { public ThresholdAlgorithm() {
this.m_Population = new Population(); this.m_Population = new Population();
this.m_Population.setPopulationSize(10); this.m_Population.setTargetSize(10);
} }
public ThresholdAlgorithm(ThresholdAlgorithm a) { public ThresholdAlgorithm(ThresholdAlgorithm a) {

View File

@ -65,7 +65,7 @@ public class TribesSwarm implements java.io.Serializable{
for (int i=0; i<tribes[n].explorerNb; i++) pop.add(tribes[n].explorer[i]); for (int i=0; i<tribes[n].explorerNb; i++) pop.add(tribes[n].explorer[i]);
} }
pop.add(getBestMemory().asDummyExplorer(range, masterTribe.getObjectiveFirstDim())); pop.add(getBestMemory().asDummyExplorer(range, masterTribe.getObjectiveFirstDim()));
pop.setPopulationSize(pop.size()); pop.synchSize();
return pop; return pop;
} }

View File

@ -133,7 +133,7 @@ public class MOEAParameters extends AbstractGOParameters implements InterfaceGOP
archive = new Population(); archive = new Population();
((MultiObjectiveEA)this.m_Optimizer).getPopulation().SetArchive(archive); ((MultiObjectiveEA)this.m_Optimizer).getPopulation().SetArchive(archive);
} }
((MultiObjectiveEA)this.m_Optimizer).getPopulation().getArchive().setPopulationSize(b); ((MultiObjectiveEA)this.m_Optimizer).getPopulation().getArchive().setTargetSize(b);
} }
public String archiveSizeTipText() { public String archiveSizeTipText() {
return "Choose the size of the archive."; return "Choose the size of the archive.";

View File

@ -2,6 +2,8 @@ package eva2.server.modules;
import java.util.Vector; import java.util.Vector;
import javax.swing.JOptionPane;
import eva2.gui.BeanInspector; import eva2.gui.BeanInspector;
import eva2.server.go.InterfaceGOParameters; import eva2.server.go.InterfaceGOParameters;
import eva2.server.go.InterfacePopulationChangedEventListener; import eva2.server.go.InterfacePopulationChangedEventListener;
@ -25,6 +27,7 @@ import eva2.server.stat.StatisticsWithGUI;
import eva2.tools.EVAERROR; import eva2.tools.EVAERROR;
import eva2.tools.EVAHELP; import eva2.tools.EVAHELP;
import eva2.tools.Pair; import eva2.tools.Pair;
import eva2.tools.StringTools;
import eva2.tools.jproxy.RemoteStateListener; import eva2.tools.jproxy.RemoteStateListener;
import eva2.tools.math.RNG; import eva2.tools.math.RNG;
@ -165,15 +168,19 @@ public class Processor extends Thread implements InterfaceProcessor, InterfacePo
setPriority(1); setPriority(1);
} }
} catch (Exception e) { } catch (Exception e) {
System.err.println("Caught exception in Processor: "+e.getMessage()); String errMsg = e.getMessage();
if ((errMsg == null) || (errMsg.length() == 0)) errMsg="check console output for error messages.";
errMsg = "Exception in Processor: "+errMsg;
System.err.println(errMsg);
e.printStackTrace(); e.printStackTrace();
try {
JOptionPane.showMessageDialog(null, StringTools.wrapLine(errMsg, 60, 0.2), "Error in Optimization", JOptionPane.ERROR_MESSAGE);
} catch (Exception ex) {} catch(Error er) {};
//m_Statistics.stopOptPerformed(false); //m_Statistics.stopOptPerformed(false);
setOptRunning(false); // normal finish setOptRunning(false); // normal finish
if (m_ListenerModule!=null) { if (m_ListenerModule!=null) {
m_ListenerModule.performedStop(); // is only needed in client server mode m_ListenerModule.performedStop(); // is only needed in client server mode
String errMsg = e.getMessage(); m_ListenerModule.updateProgress(0, errMsg);
if ((errMsg == null) || (errMsg.length() == 0)) errMsg="check console output for error messages.";
m_ListenerModule.updateProgress(0, "Error in optimization: " + errMsg);
} }
} }
return resPop; return resPop;
@ -428,7 +435,7 @@ public class Processor extends Thread implements InterfaceProcessor, InterfacePo
} }
if (!resultPop.contains(m_Statistics.getBestSolution())) { if (!resultPop.contains(m_Statistics.getBestSolution())) {
resultPop.add(m_Statistics.getBestSolution()); // this is a minor cheat but guarantees that the best solution ever found is contained in the final results resultPop.add(m_Statistics.getBestSolution()); // this is a minor cheat but guarantees that the best solution ever found is contained in the final results
resultPop.setPopulationSize(resultPop.size()); resultPop.synchSize();
} }
resultPop = PostProcess.postProcess(ppp, resultPop, (AbstractOptimizationProblem)goParams.getProblem(), listener); resultPop = PostProcess.postProcess(ppp, resultPop, (AbstractOptimizationProblem)goParams.getProblem(), listener);
resPop = resultPop; resPop = resultPop;

View File

@ -130,4 +130,52 @@ public class StringTools {
return null; return null;
} }
} }
/**
* Rewrap a given string to lines of approx. length len.
*
* @param str
* @param len
* @return
*/
public static String wrapLine(String str, int len, double tolerancePerCent) {
return wrapLine(str, new char[]{' ', '-', ',', '.'}, len, tolerancePerCent);
}
/**
* Rewrap a given string to lines of approx. length len.
*
* @param str
* @param len
* @return
*/
public static String wrapLine(String str, char[] breakChars, int len, double tolerancePerCent) {
StringBuffer res=new StringBuffer();
String rest=str;
int minLen = (int)((1.-tolerancePerCent)*(double)len);
int maxLen = (int)((1.+tolerancePerCent)*(double)len);
int nextBreak=-1;
while (rest.length()>0) {
if (rest.length()<=maxLen) {
nextBreak = rest.length()-1;
} else {
nextBreak = getNextBreak(minLen, maxLen, breakChars, rest); // search for a break character in a certain interval
if (nextBreak<0) nextBreak = len; // if none found force the break at the intended length
}
if (res.length()>0) res.append("\n"); // insert newline
res.append(rest.substring(0, nextBreak+1));
rest = rest.substring(nextBreak+1);
}
return res.toString();
}
public static int getNextBreak(int startIndex, int endIndex, char[] brkChars, String str) {
int index;
for (int i=0; i<brkChars.length; i++) {
//indices[i] = str.indexOf(""+brkChars[i], startIndex);
index =str.indexOf(""+brkChars[i], startIndex);
if (index>=0 && (index <= endIndex)) return index;
}
return -1;
}
} }