From 7d6a9faf66f7e1c584bb1a9f139bb492a87266c8 Mon Sep 17 00:00:00 2001 From: Fabian Becker Date: Sun, 19 Oct 2014 14:19:54 +0200 Subject: [PATCH] Remove last traces of the TRACE variable. --- src/eva2/gui/EvATreeSelectionListener.java | 14 +- src/eva2/gui/PropertySheetPanelStat.java | 4 - src/eva2/gui/plot/FunctionArea.java | 1 - src/eva2/gui/plot/TopoPlot.java | 7 - .../codings/gp/AbstractGPNode.java | 7 - .../paretofrontviewer/ParetoFrontView2D.java | 2 +- src/eva2/optimization/modules/Processor.java | 3 +- .../cluster/ClusteringNearestBetter.java | 25 +- .../constraint/AbstractConstraint.java | 4 +- .../constraint/ConstraintCollection.java | 7 +- .../constraint/GenericConstraint.java | 9 - .../crossover/CrossoverGAGINPoint.java | 16 +- .../crossover/CrossoverGPDefault.java | 28 +-- .../operator/mutation/CMAParamSet.java | 6 +- .../operator/mutation/MutateESCorrVector.java | 24 +- .../MutateESCovarianceMatrixAdaption.java | 5 - .../operator/mutation/MutateESRankMuCMA.java | 109 +-------- .../AbstractParameterControl.java | 5 - .../paramcontrol/ConstraintBasedAdaption.java | 19 -- .../PSOActivityFeedbackControl.java | 5 +- .../paramcontrol/ParameterControlManager.java | 12 +- .../operator/paretofrontmetrics/MetricS.java | 25 +- .../operator/postprocess/PostProcess.java | 33 +-- .../PopulationMeasureTerminator.java | 30 +-- .../optimization/population/Population.java | 18 +- .../stat/EvAStatisticalEvaluation.java | 23 -- src/eva2/optimization/strategies/ANPSO.java | 89 ++----- .../strategies/BinaryScatterSearch.java | 20 +- .../strategies/ClusterBasedNichingEA.java | 222 +----------------- .../strategies/ClusteringHillClimbing.java | 25 -- .../optimization/strategies/EsDpiNiching.java | 128 +--------- .../strategies/GradientDescentAlgorithm.java | 18 +- .../strategies/IslandModelEA.java | 7 - .../strategies/MemeticAlgorithm.java | 23 +- .../ParticleFilterOptimization.java | 9 - .../strategies/ParticleSwarmOptimization.java | 15 +- .../strategies/ScatterSearch.java | 57 +---- src/eva2/optimization/strategies/Tribes.java | 10 - .../strategies/tribes/TribesPosition.java | 24 +- .../strategies/tribes/TribesSwarm.java | 16 +- src/eva2/problems/MatlabEvalMediator.java | 1 - src/eva2/problems/MatlabProblem.java | 6 - src/eva2/tools/KMEANSJAVA.java | 18 +- src/eva2/tools/ReflectPackage.java | 179 +++----------- src/eva2/tools/chart2d/DArea.java | 30 +-- 45 files changed, 127 insertions(+), 1211 deletions(-) diff --git a/src/eva2/gui/EvATreeSelectionListener.java b/src/eva2/gui/EvATreeSelectionListener.java index f8119566..84d0d399 100644 --- a/src/eva2/gui/EvATreeSelectionListener.java +++ b/src/eva2/gui/EvATreeSelectionListener.java @@ -22,7 +22,6 @@ public class EvATreeSelectionListener implements TreeSelectionListener, Property private PropertyEditor goe = null; private EvATreeNode root = null; private JTree jtree = null; - public static final boolean TRACE = true; /** * Create a tree listener and hook it up in the editor to listen to parameter changes @@ -47,17 +46,9 @@ public class EvATreeSelectionListener implements TreeSelectionListener, Property @Override public void valueChanged(TreeSelectionEvent e) { - if (TRACE) { - System.out.println("valueChanged to " + BeanInspector.toString(e.getPath())); - } TreePath tp = e.getPath(); - if (TRACE) { - for (int i = tp.getPathCount() - 1; i >= 0; i--) { - System.out.println("* " + i + " " + tp.getPathComponent(i)); - } - } + EvATreeNode leafNode = (EvATreeNode) tp.getLastPathComponent(); -// goe.setValue(leafNode.getUserObject()); Component editComp = goe.getCustomEditor(); if (editComp instanceof OptimizationEditorPanel) { // update the object in the main OptimizationEditorPanel @@ -69,9 +60,6 @@ public class EvATreeSelectionListener implements TreeSelectionListener, Property @Override public void propertyChange(PropertyChangeEvent evt) { - if (TRACE) { - System.out.println("EvATreeNode received change event " + evt); - } root.setObject(evt.getNewValue(), true); if (jtree != null) { jtree.setModel(new DefaultTreeModel(root)); diff --git a/src/eva2/gui/PropertySheetPanelStat.java b/src/eva2/gui/PropertySheetPanelStat.java index 0017958a..1fa174eb 100644 --- a/src/eva2/gui/PropertySheetPanelStat.java +++ b/src/eva2/gui/PropertySheetPanelStat.java @@ -11,8 +11,6 @@ import java.io.Serializable; * */ public class PropertySheetPanelStat extends JPanel implements Serializable { - - public final static boolean TRACE = false; private Object[] values; private JCheckBoxFlag[] views; private JLabel[] labels; @@ -38,8 +36,6 @@ public class PropertySheetPanelStat extends JPanel implements Serializable { setLayout(gbLayout); setVisible(false); - int rowHeight = 12; - values = new Object[flag.length]; views = new JCheckBoxFlag[flag.length]; labels = new JLabel[names.length]; diff --git a/src/eva2/gui/plot/FunctionArea.java b/src/eva2/gui/plot/FunctionArea.java index b377621e..77b4c416 100644 --- a/src/eva2/gui/plot/FunctionArea.java +++ b/src/eva2/gui/plot/FunctionArea.java @@ -426,7 +426,6 @@ public class FunctionArea extends DArea implements Serializable { minY = Math.min(minY, pSet.getMinYVal()); } } - // if (TRACE) System.out.println("min is " + minY); return (minY > 0); } diff --git a/src/eva2/gui/plot/TopoPlot.java b/src/eva2/gui/plot/TopoPlot.java index 6b9d6fcf..a8829917 100644 --- a/src/eva2/gui/plot/TopoPlot.java +++ b/src/eva2/gui/plot/TopoPlot.java @@ -25,12 +25,10 @@ public class TopoPlot extends Plot { */ public TopoPlot(String PlotName, String xname, String yname) { super(PlotName, xname, yname, true); - //if (TRACE) System.out.println("Constructor TopoPlot "+PlotName); } public TopoPlot(String PlotName, String xname, String yname, double[] a, double[] b) { super(PlotName, xname, yname, a, b); - //if (TRACE) System.out.println("Constructor TopoPlot "+PlotName); } /** @@ -98,17 +96,12 @@ public class TopoPlot extends Plot { double deltaY = sizeXY[1] / gridy; double maxDeriv = 0; double[] pos = new double[2]; - boolean TRACEMETH = false; - //double fitRange = java.lang.Math.abs(problem.getMinFitness()-problem.getMaxFitness() ); double fitRange = 0, max = -Double.MAX_VALUE, min = Double.MAX_VALUE, tmp; for (int x = 0; x < gridx; x++) { for (int y = 0; y < gridy; y++) { pos[0] = border[0][0] + x * deltaX; pos[1] = border[1][0] + y * deltaY; tmp = (float) (problem.functionValue(pos)); - if (TRACEMETH) { - System.out.println(pos[0] + " " + pos[1] + " " + tmp); - } if (tmp < min) { min = tmp; } diff --git a/src/eva2/optimization/individuals/codings/gp/AbstractGPNode.java b/src/eva2/optimization/individuals/codings/gp/AbstractGPNode.java index e43b8e5f..0da90404 100644 --- a/src/eva2/optimization/individuals/codings/gp/AbstractGPNode.java +++ b/src/eva2/optimization/individuals/codings/gp/AbstractGPNode.java @@ -22,7 +22,6 @@ public abstract class AbstractGPNode implements InterfaceProgram, java.io.Serial protected AbstractGPNode parentNode; protected AbstractGPNode[] nodes = new AbstractGPNode[0]; protected int depth = 0; - private static final boolean TRACE = false; /** * This method allows you to clone the Nodes @@ -132,9 +131,6 @@ public abstract class AbstractGPNode implements InterfaceProgram, java.io.Serial System.err.println("String has ambiguous prefix: " + str + " -- " + BeanInspector.toString(matchSet)); } else { // exactly one match: AbstractGPNode currentNode = (AbstractGPNode) matchSet.get(0).clone(); - if (TRACE) { - System.out.println("Found match: " + currentNode.getOpIdentifier() + "/" + currentNode.getArity()); - } int cutFront = currentNode.getOpIdentifier().length(); String restStr; if (currentNode.getArity() == 0) { @@ -163,9 +159,6 @@ public abstract class AbstractGPNode implements InterfaceProgram, java.io.Serial e.printStackTrace(); } } - if (TRACE) { - System.out.println("read " + currentNode.getName() + ", rest: " + restStr); - } return new Pair(currentNode, restStr); } } diff --git a/src/eva2/optimization/mocco/paretofrontviewer/ParetoFrontView2D.java b/src/eva2/optimization/mocco/paretofrontviewer/ParetoFrontView2D.java index 4f99066b..7903bdb8 100644 --- a/src/eva2/optimization/mocco/paretofrontviewer/ParetoFrontView2D.java +++ b/src/eva2/optimization/mocco/paretofrontviewer/ParetoFrontView2D.java @@ -261,7 +261,7 @@ public class ParetoFrontView2D extends JPanel implements InterfaceParetoFrontVie InterfaceOptimizationObjective[] tmpObj = ((InterfaceMultiObjectiveDeNovoProblem) this.moccoViewer.moccoStandalone.state.currentProblem).getProblemObjectives(); fitness = new double[tmpObj.length]; for (int k = 0; k < tmpObj.length; k++) { - fitness[k] = ((Double) ((AbstractEAIndividual) pf.get(i)).getData(tmpObj[k].getIdentName())).doubleValue(); + fitness[k] = (Double) ((AbstractEAIndividual) pf.get(i)).getData(tmpObj[k].getIdentName()); } } point = new DPoint(fitness[indexX], fitness[indexY]); diff --git a/src/eva2/optimization/modules/Processor.java b/src/eva2/optimization/modules/Processor.java index 74ea6d59..9cdde24e 100644 --- a/src/eva2/optimization/modules/Processor.java +++ b/src/eva2/optimization/modules/Processor.java @@ -192,8 +192,7 @@ public class Processor extends Thread implements InterfaceProcessor, InterfacePo LOGGER.log(Level.SEVERE, errMsg, e); try { JOptionPane.showMessageDialog(null, StringTools.wrapLine(errMsg, 60, 0.2), "Error in Optimization", JOptionPane.ERROR_MESSAGE); - } catch (Exception ex) { - } catch (Error error) { + } catch (Exception | Error ex) { } //statistics.stopOptimizationPerformed(false); setOptimizationRunning(false); // normal finish diff --git a/src/eva2/optimization/operator/cluster/ClusteringNearestBetter.java b/src/eva2/optimization/operator/cluster/ClusteringNearestBetter.java index 2c96c978..8fc11107 100644 --- a/src/eva2/optimization/operator/cluster/ClusteringNearestBetter.java +++ b/src/eva2/optimization/operator/cluster/ClusteringNearestBetter.java @@ -43,8 +43,6 @@ public class ClusteringNearestBetter implements InterfaceClustering, Serializabl private static final String initializedForKey = "initializedClustNearestBetterOnHash"; private static final String initializedRefData = "initializedClustNearestBetterData"; - private static boolean TRACE = false; - public ClusteringNearestBetter() { } @@ -216,9 +214,7 @@ public class ClusteringNearestBetter implements InterfaceClustering, Serializabl } } currentMeanDistance = createClusterTreeFromSortedPop(sorted); - if (TRACE) { - pop.putData(initializedForKey, pop.hashCode()); - } + pop.putData(initializedRefData, currentMeanDistance); return initializedRefData; } else { @@ -247,10 +243,6 @@ public class ClusteringNearestBetter implements InterfaceClustering, Serializabl } } - if (TRACE) { - System.out.println("Current pop measures: " + BeanInspector.toString(pop.getPopulationMeasures(metric)[0])); - System.out.println("Current threshold: " + currentDistThreshold()); - } if (isAdaptiveThreshold()) { // test if there was a valid initialization step if (!getRefData(referenceSet, pop)) { currentMeanDistance = createClusterTreeFromSortedPop(sorted); @@ -304,13 +296,7 @@ public class ClusteringNearestBetter implements InterfaceClustering, Serializabl } Double refDat = (Double) referenceSet.getData(initializedRefData); if (refDat != null) { - if (TRACE) { // check hash - Integer hash = (Integer) referenceSet.getData(initializedForKey); - if ((hash == null) || (hash != referenceSet.hashCode())) { - System.err.println("Warning, missing initialization before clustering for ClusteringNearestBetter!"); - return false; - } - } + currentMeanDistance = refDat.doubleValue(); return true; } else { @@ -362,14 +348,7 @@ public class ClusteringNearestBetter implements InterfaceClustering, Serializabl // so add it to the cluster, mark it, and proceed recursively. currentClust.add(sorted.get(children[current].get(i))); clustered[children[current].get(i)] = true; - if (TRACE) { - System.out.println("Assigned " + current); - } addChildren(children[current].get(i), clustered, sorted, currentClust); - } else { - if (TRACE) { - System.out.println("Not assigned " + current); - } } } } else { diff --git a/src/eva2/optimization/operator/constraint/AbstractConstraint.java b/src/eva2/optimization/operator/constraint/AbstractConstraint.java index bfbe6431..bd0fa5a9 100644 --- a/src/eva2/optimization/operator/constraint/AbstractConstraint.java +++ b/src/eva2/optimization/operator/constraint/AbstractConstraint.java @@ -18,7 +18,7 @@ public abstract class AbstractConstraint implements InterfaceDoubleConstraint, S // private transient GPFunctionProblem func = null; protected ConstraintRelationEnum relation = ConstraintRelationEnum.lessEqZero; protected ConstraintHandlingEnum handling = ConstraintHandlingEnum.specificTag; - protected static boolean TRACE = false; + protected double equalityEpsilon = 0.0001; // threshold below which equality constraints are seen as satisfied private AbstractEAIndividual currentIndy = null; @@ -31,11 +31,9 @@ public abstract class AbstractConstraint implements InterfaceDoubleConstraint, S relation = ConstraintRelationEnum.lessEqZero; penaltyFactor = 1.; paramCtrl = new ParameterControlManager(new NoParamAdaption()); -// penaltyFactAdaption = new NoParamAdaption(); } public AbstractConstraint(AbstractConstraint o) { -// penaltyFactAdaption = (ParamAdaption)o.penaltyFactAdaption.clone(); paramCtrl = new ParameterControlManager(o.paramCtrl); penaltyFactor = o.penaltyFactor; relation = o.relation; diff --git a/src/eva2/optimization/operator/constraint/ConstraintCollection.java b/src/eva2/optimization/operator/constraint/ConstraintCollection.java index 2befd017..98cfc24a 100644 --- a/src/eva2/optimization/operator/constraint/ConstraintCollection.java +++ b/src/eva2/optimization/operator/constraint/ConstraintCollection.java @@ -41,15 +41,10 @@ public class ConstraintCollection extends AbstractConstraint { @Override protected double getRawViolationValue(double[] indyX) { double v, sum = 0; - if (TRACE) { - System.out.println("Viol (pen " + getPenaltyFactor() + ")"); - } + for (AbstractConstraint constr : constraintArray) { v = constr.getViolation(indyX); sum += v; - if (TRACE) { - System.out.println(constr.getClass().getSimpleName() + " " + v); - } } return sum; } diff --git a/src/eva2/optimization/operator/constraint/GenericConstraint.java b/src/eva2/optimization/operator/constraint/GenericConstraint.java index 6fde36cd..ffda790d 100644 --- a/src/eva2/optimization/operator/constraint/GenericConstraint.java +++ b/src/eva2/optimization/operator/constraint/GenericConstraint.java @@ -62,10 +62,6 @@ public class GenericConstraint extends AbstractConstraint implements InterfaceDo if (constraintProgram == null) { System.err.println("Error: invalid expression: " + constraintString); } - if (TRACE) { - System.out.println("Compiled constraint " + constraintString); - System.out.println("Program: " + constraintProgram.getStringRepresentation()); - } } /** @@ -97,8 +93,6 @@ public class GenericConstraint extends AbstractConstraint implements InterfaceDo } else { return 0.; } -// case linearLessEqZero: -// return getViolation(evalLinearConstr(indy)); } EVAERROR.errorMsgOnce("Error: unknown relation for GenericConstraint!"); return 0.; @@ -111,9 +105,6 @@ public class GenericConstraint extends AbstractConstraint implements InterfaceDo public void setConstraintString(String constraintString) { this.constraintString = constraintString; constraintProgram = null; - if (TRACE) { - System.out.println(" NEW CONSTRAINT STRING SET! in " + this); - } } public String getName() { diff --git a/src/eva2/optimization/operator/crossover/CrossoverGAGINPoint.java b/src/eva2/optimization/operator/crossover/CrossoverGAGINPoint.java index dfd515f7..daf23db1 100644 --- a/src/eva2/optimization/operator/crossover/CrossoverGAGINPoint.java +++ b/src/eva2/optimization/operator/crossover/CrossoverGAGINPoint.java @@ -13,15 +13,14 @@ import java.util.BitSet; /** * The famous n-point crossover operator on a binary and integer genotype. Genotypes of - * parent individuals are recombined by exchanging subsegments within randomly - * selected points. Therefore, far-away allels (larger GA schemas) are more likely to be split + * parent individuals are recombined by exchanging sub-segments within randomly + * selected points. Therefore, far-away alleles (larger GA schemas) are more likely to be split * between individuals. * * @author mkron, streiche */ public class CrossoverGAGINPoint implements InterfaceCrossover, java.io.Serializable { private int numberOfCrossovers = 3; - private static boolean TRACE = false; public CrossoverGAGINPoint() { @@ -71,7 +70,6 @@ public class CrossoverGAGINPoint implements InterfaceCrossover, java.io.Serializ if (individual instanceof InterfaceGAIndividual || (individual instanceof InterfaceGIIndividual)) { int length = getGenotypeLength(individual); -// Object[][] tmpGenotypes = new Object[2][partners.size()+1]; Object[] origGenotypes = new Object[partners.size() + 1]; Object[] newGenotypes = new Object[partners.size() + 1]; @@ -83,14 +81,9 @@ public class CrossoverGAGINPoint implements InterfaceCrossover, java.io.Serializ newGenotypes[i + 1] = getGenotype(result[i + 1]); length = Math.max(length, getGenotypeLength(partners.getEAIndividual(i))); } - if (TRACE) { - System.out.println("Before CO: " + BeanInspector.toString(newGenotypes)); - } + int mixer = RNG.randomInt(0, partners.size()); // partner index with which to exchange genes int[] crossoverPoints = getCrossoverPoints(length, numberOfCrossovers); - if (TRACE) { - System.out.println("CO points: " + BeanInspector.toString(crossoverPoints)); - } for (int i = 0; i < length; i++) { // loop positions for (int j = 0; j < this.numberOfCrossovers; j++) { if (i == crossoverPoints[j]) { @@ -106,9 +99,6 @@ public class CrossoverGAGINPoint implements InterfaceCrossover, java.io.Serializ for (int i = 0; i < result.length; i++) { writeBack(result[i], newGenotypes[i]); } - if (TRACE) { - System.out.println("After CO: " + BeanInspector.toString(newGenotypes)); - } } return result; } diff --git a/src/eva2/optimization/operator/crossover/CrossoverGPDefault.java b/src/eva2/optimization/operator/crossover/CrossoverGPDefault.java index 60acd602..275e488e 100644 --- a/src/eva2/optimization/operator/crossover/CrossoverGPDefault.java +++ b/src/eva2/optimization/operator/crossover/CrossoverGPDefault.java @@ -10,11 +10,6 @@ import eva2.problems.InterfaceOptimizationProblem; import eva2.tools.math.RNG; /** - * Created by IntelliJ IDEA. - * User: streiche - * Date: 04.04.2003 - * Time: 16:37:05 - * To change this template use Options | File Templates. */ public class CrossoverGPDefault implements InterfaceCrossover, java.io.Serializable { /** @@ -23,7 +18,6 @@ public class CrossoverGPDefault implements InterfaceCrossover, java.io.Serializa private static final long serialVersionUID = 8900427365914281930L; private InterfaceOptimizationProblem optimizationProblem; private boolean maintainMaxDepth = true; - private static final boolean TRACE = false; public CrossoverGPDefault() { } @@ -60,11 +54,6 @@ public class CrossoverGPDefault implements InterfaceCrossover, java.io.Serializa for (int i = 0; i < partners.size(); i++) { result[i + 1] = (AbstractEAIndividual) ((AbstractEAIndividual) partners.get(i)).clone(); } - if (TRACE) { - for (int i = 0; i < result.length; i++) { - System.out.println("Before Crossover: " + result[i].getStringRepresentation()); - } - } if (partners.size() == 0) { return result; } @@ -94,10 +83,6 @@ public class CrossoverGPDefault implements InterfaceCrossover, java.io.Serializa selNodeOther = ((InterfaceGPIndividual) result[1]).getPGenotype()[t].getRandomLeaf(); } } - if (TRACE) { - System.out.println("Selected t " + selNodeThis.getStringRepresentation()); - System.out.println("Selected o " + selNodeOther.getStringRepresentation()); - } AbstractGPNode selNodeThisParent, selNodeOtherParent; selNodeThisParent = selNodeThis.getParent(); @@ -119,20 +104,15 @@ public class CrossoverGPDefault implements InterfaceCrossover, java.io.Serializa } } //in case the crossover was successfull lets give the mutation operators a chance to mate the strategy parameters - for (int i = 0; i < result.length; i++) { - ((GPIndividualProgramData) result[i]).checkDepth(); - result[i].getMutationOperator().crossoverOnStrategyParameters(indy1, partners); - } - if (TRACE) { - for (int i = 0; i < result.length; i++) { - System.out.println("After Crossover: " + result[i].getStringRepresentation()); - } + for (AbstractEAIndividual aResult : result) { + ((GPIndividualProgramData) aResult).checkDepth(); + aResult.getMutationOperator().crossoverOnStrategyParameters(indy1, partners); } return result; } /** - * This method allows you to evaluate wether two crossover operators + * This method allows you to evaluate whether two crossover operators * are actually the same. * * @param crossover The other crossover operator diff --git a/src/eva2/optimization/operator/mutation/CMAParamSet.java b/src/eva2/optimization/operator/mutation/CMAParamSet.java index 0f4900dd..f1ec4e8d 100644 --- a/src/eva2/optimization/operator/mutation/CMAParamSet.java +++ b/src/eva2/optimization/operator/mutation/CMAParamSet.java @@ -116,8 +116,6 @@ class CMAParamSet implements InterfacePopulationChangedEventListener, Serializab params.range = range; int dim = params.range.length; -// if (TRACE_1) System.out.println("WCMA initialize " + dim); -// if (TRACE_1) System.out.println("WCMA static initialize " + dim); params.eigenvalues = new double[dim]; Arrays.fill(params.eigenvalues, 1.); params.meanX = new double[dim]; @@ -219,9 +217,7 @@ class CMAParamSet implements InterfacePopulationChangedEventListener, Serializab public void registerPopulationStateChanged(Object source, String name) { if (name.equals(Population.POPULATION_INITIALIZED)) { Population pop = (Population) source; - if (MutateESRankMuCMA.TRACE_1) { - System.out.println("Event " + name + " arrived in CMAParamSet!!!"); - } + CMAParamSet params = (CMAParamSet) (pop.getData(MutateESRankMuCMA.cmaParamsKey)); int mu; if (pop.hasData(EvolutionStrategies.esMuParam)) { diff --git a/src/eva2/optimization/operator/mutation/MutateESCorrVector.java b/src/eva2/optimization/operator/mutation/MutateESCorrVector.java index 7bb673f3..f2f7c9b7 100644 --- a/src/eva2/optimization/operator/mutation/MutateESCorrVector.java +++ b/src/eva2/optimization/operator/mutation/MutateESCorrVector.java @@ -30,7 +30,6 @@ public class MutateESCorrVector implements InterfaceMutation, java.io.Serializab protected double rotationDev = 15.; protected boolean checkConstraints = true; public static final String vectorKey = "MutateESCorrVectorVector"; - public static final boolean TRACE = false; public MutateESCorrVector() { } @@ -128,7 +127,6 @@ public class MutateESCorrVector implements InterfaceMutation, java.io.Serializab */ @Override public void mutate(AbstractEAIndividual individual) { -// if (TRACE) System.out.println("Before Mutate: " + AbstractEAIndividual.getDefaultDataString(individual)); if (individual instanceof InterfaceESIndividual) { double[] genes = ((InterfaceESIndividual) individual).getDGenotype(); double[][] range = ((InterfaceESIndividual) individual).getDoubleRange(); @@ -137,9 +135,6 @@ public class MutateESCorrVector implements InterfaceMutation, java.io.Serializab // mutate the velocity vector and write it back if ((scalingDev > 0) || (rotationDev > 0)) { -// for (int i = 0; i < vel.length; i++) { -// vel[i] += ((range[i][1] -range[i][0])/2)*RNG.gaussianDouble(this.mutationStepSize); -// } double rotateRad = rotationDev * (Math.PI / 360.) * RNG.gaussianDouble(1.); // rotate with a gaussian distribution of deviation rotationDeg Mathematics.rotateAllAxes(vel, rotateRad, false); // rotate @@ -158,12 +153,6 @@ public class MutateESCorrVector implements InterfaceMutation, java.io.Serializab Mathematics.svMult(rScale, vel, vel); // mutate speed individual.putData(vectorKey, vel); - if (TRACE) { - System.out.println("rotated by " + rotateRad + ", scaled by " + rScale); - } - if (TRACE) { - System.out.println("-- dir is " + BeanInspector.toString(vel)); - } } // add velocity to the individual @@ -178,7 +167,6 @@ public class MutateESCorrVector implements InterfaceMutation, java.io.Serializab ((InterfaceESIndividual) individual).setDGenotype(genes); } -// if (TRACE) System.out.println("After Mutate: " + AbstractEAIndividual.getDefaultDataString(individual)); } /** @@ -192,21 +180,21 @@ public class MutateESCorrVector implements InterfaceMutation, java.io.Serializab public void crossoverOnStrategyParameters(AbstractEAIndividual indy1, Population partners) { ArrayList tmpList = new ArrayList(); if (indy1.getMutationOperator() instanceof MutateESCorrVector) { - tmpList.add(new Double(((MutateESCorrVector) indy1.getMutationOperator()).scalingDev)); + tmpList.add(((MutateESCorrVector) indy1.getMutationOperator()).scalingDev); } - for (int i = 0; i < partners.size(); i++) { - if (((AbstractEAIndividual) partners.get(i)).getMutationOperator() instanceof MutateESCorrVector) { - tmpList.add(new Double(((MutateESCorrVector) ((AbstractEAIndividual) partners.get(i)).getMutationOperator()).scalingDev)); + for (Object partner : partners) { + if (((AbstractEAIndividual) partner).getMutationOperator() instanceof MutateESCorrVector) { + tmpList.add(((MutateESCorrVector) ((AbstractEAIndividual) partner).getMutationOperator()).scalingDev); } } double[] list = new double[tmpList.size()]; for (int i = 0; i < tmpList.size(); i++) { - list[i] = tmpList.get(i).doubleValue(); + list[i] = tmpList.get(i); } if (list.length <= 1) { return; } - // discreete mutation for step size + // discrete mutation for step size this.scalingDev = list[RNG.randomInt(0, list.length - 1)]; } diff --git a/src/eva2/optimization/operator/mutation/MutateESCovarianceMatrixAdaption.java b/src/eva2/optimization/operator/mutation/MutateESCovarianceMatrixAdaption.java index 374ff470..91c4c319 100644 --- a/src/eva2/optimization/operator/mutation/MutateESCovarianceMatrixAdaption.java +++ b/src/eva2/optimization/operator/mutation/MutateESCovarianceMatrixAdaption.java @@ -10,11 +10,6 @@ import eva2.tools.math.Mathematics; import eva2.tools.math.RNG; /** - * Created by IntelliJ IDEA. - * User: streiche - * Date: 27.05.2003 - * Time: 17:47:45 - * To change this template use Options | File Templates. */ public class MutateESCovarianceMatrixAdaption implements InterfaceMutation, java.io.Serializable { diff --git a/src/eva2/optimization/operator/mutation/MutateESRankMuCMA.java b/src/eva2/optimization/operator/mutation/MutateESRankMuCMA.java index 1c88b804..ffbb8789 100644 --- a/src/eva2/optimization/operator/mutation/MutateESRankMuCMA.java +++ b/src/eva2/optimization/operator/mutation/MutateESRankMuCMA.java @@ -49,9 +49,6 @@ public class MutateESRankMuCMA implements InterfaceAdaptOperatorGenerational, In private boolean checkRange = true; public static final String cmaParamsKey = "RankMuCMAParameters"; - public static boolean TRACE_1 = false; // true for plotting CMA - public static boolean TRACE_2 = false; // true for plotting CMA - public static boolean TRACE_TEST = false; public MutateESRankMuCMA() { } @@ -67,7 +64,6 @@ public class MutateESRankMuCMA implements InterfaceAdaptOperatorGenerational, In @Override public Object clone() { -// if (TRACE) System.out.println("WCMA clone"); return new MutateESRankMuCMA(this); } @@ -162,26 +158,13 @@ public class MutateESRankMuCMA implements InterfaceAdaptOperatorGenerational, In return; } - if (TRACE_1) { - System.out.println("WCMA adaptGenerational **********"); -// System.out.println("newPop measures: " + BeanInspector.toString(newPop.getPopulationMeasures())); - System.out.println("mu_eff: " + CMAParamSet.getMuEff(params.weights, mu)); - System.out.println(params.toString()); - System.out.println("*********************************"); - } - double[] newMeanX = calcMeanX(params.weights, selectedSorted); - if (TRACE_1) { - System.out.println("newMeanX: " + BeanInspector.toString(newMeanX)); - } - int dim = params.meanX.length; double[] BDz = new double[dim]; for (int i = 0; i < dim; i++) { /* calculate xmean and BDz~N(0,C) */ // Eq. 4 from HK04, most right term BDz[i] = Math.sqrt(CMAParamSet.getMuEff(params.weights, mu)) * (newMeanX[i] - params.meanX[i]) / getSigma(params, i); } -// if (TRACE_2) System.out.println("BDz is " + BeanInspector.toString(BDz)); double[] newPathS = params.pathS.clone(); double[] newPathC = params.pathC.clone(); @@ -233,16 +216,6 @@ public class MutateESRankMuCMA implements InterfaceAdaptOperatorGenerational, In checkValidDouble(newPathC[i]); } - // TODO missing: "remove momentum in ps" - - if (TRACE_1) { - System.out.println("newPathC: " + BeanInspector.toString(newPathC)); - System.out.println("newPathS: " + BeanInspector.toString(newPathS)); - } - - if (TRACE_1) { - System.out.println("Bef: C is \n" + params.mC.toString()); - } if (params.meanX == null) { params.meanX = newMeanX; } @@ -250,10 +223,6 @@ public class MutateESRankMuCMA implements InterfaceAdaptOperatorGenerational, In updateCov(params, newPathC, newMeanX, hsig, mu, selectedSorted); updateBD(params); - if (TRACE_2) { - System.out.println("Aft: C is " + params.mC.toString()); - } - /* update of sigma */ double sigFact = Math.exp(((psNorm / expRandStepLen) - 1) * params.c_sig / params.d_sig); @@ -269,12 +238,6 @@ public class MutateESRankMuCMA implements InterfaceAdaptOperatorGenerational, In params = CMAParamSet.initCMAParams(params, mu, lambda, params.meanX, ((InterfaceDataTypeDouble) oldGen.getEAIndividual(0)).getDoubleRange(), params.firstSigma); } - if (TRACE_1) { - System.out.println("sigma=" + params.sigma); - System.out.print("psLen=" + (psNorm) + " "); - outputParams(params, mu); - } - // take over data params.meanX = newMeanX; params.pathC = newPathC; @@ -284,7 +247,6 @@ public class MutateESRankMuCMA implements InterfaceAdaptOperatorGenerational, In lastParams = (CMAParamSet) params.clone(); oldGen.putData(cmaParamsKey, params); selectedP.putData(cmaParamsKey, params); -// if (TRACE_2) System.out.println("sampling around " + BeanInspector.toString(meanX)); } /** @@ -319,19 +281,13 @@ public class MutateESRankMuCMA implements InterfaceAdaptOperatorGenerational, In if (iterations > 1 && (selected.size() > 1)) { // selected pop is sorted if (nearlySame(selected.getEAIndividual(0).getFitness(), selected.getEAIndividual(selected.size() - 1).getFitness())) { - if (TRACE_1) { - System.err.println("flat fitness landscape, consider reformulation of fitness, step-size increased"); - } params.sigma *= Math.exp(0.2 + params.c_sig / params.d_sig); -// sigma=0.1; } } if (!checkValidDouble(params.sigma)) { System.err.println("Error, unstable sigma!"); corrected = false; -// params.sigma=params.firstSigma; // MK TODO -// System.err.println( } /* Align (renormalize) scale C (and consequently sigma) */ @@ -347,7 +303,6 @@ public class MutateESRankMuCMA implements InterfaceAdaptOperatorGenerational, In } if (fac != 1.) { -// System.err.println("Scaling by " + fac); params.sigma /= fac; for (int i = 0; i < params.meanX.length; ++i) { params.pathC[i] *= fac; @@ -571,26 +526,6 @@ public class MutateESRankMuCMA implements InterfaceAdaptOperatorGenerational, In @Override public void init(AbstractEAIndividual individual, InterfaceOptimizationProblem opt) { -// firstAdaptionDone = false; -// range = ((InterfaceDataTypeDouble)individual).getDoubleRange(); -// dim = range.length; -// if (TRACE_1) System.out.println("WCMA initialize " + dim); -// c_c = (4./(dim+4)); -// c_sig = Double.NaN; // mark as not yet initialized -//// c_u_sig = Double.NaN; -// d_sig = Double.NaN; // initialize in first adaption step! -// if (TRACE_1) System.out.println("WCMA static initialize " + dim); -// eigenvalues = new double[dim]; -// Arrays.fill(eigenvalues, 1.); -// -// meanX = new double[dim]; -// pathC = new double[dim]; -// pathS = new double[dim]; -//// mBD = new double[dim]; -// mC = Matrix.identity(dim, dim); -// mB = Matrix.identity(dim, dim); -// sigma = 0.2; - // ^^^ moved to CMAParamSet initialization double[][] range = ((InterfaceDataTypeDouble) individual).getDoubleRange(); int dim = range.length; c_c = (4. / (dim + 4)); @@ -600,21 +535,15 @@ public class MutateESRankMuCMA implements InterfaceAdaptOperatorGenerational, In @Override public void mutate(AbstractEAIndividual individual) { -// if (!firstAdaptionDone) { -// if (TRACE) System.out.println("No mutation before first adaptions step"); -// return; -// } if (individual instanceof InterfaceDataTypeDouble) { double[] x = ((InterfaceDataTypeDouble) individual).getDoubleData(); -// if (TRACE) System.out.println("WCMA mutate, bef: " + BeanInspector.toString(x)); double[][] range = ((InterfaceDataTypeDouble) individual).getDoubleRange(); // this is a critical point: where do the CMA parameters for this individual's mutation come from? - // for GA and ES we can expect that selection occured directly before the mutation cycle, - // so we take the parameter set from the last adpation step. + // for GA and ES we can expect that selection occurred directly before the mutation cycle, + // so we take the parameter set from the last adaption step. ((InterfaceDataTypeDouble) individual).setDoubleGenotype(mutate(lastParams, x, range, 0)); -// if (TRACE) System.out.println("WCMA mutate, aft: " + BeanInspector.toString(x)); } else { System.err.println("Error, expecting InterfaceDataTypeDouble"); } @@ -626,7 +555,6 @@ public class MutateESRankMuCMA implements InterfaceAdaptOperatorGenerational, In System.err.println("Error in MutateESRankMuCMA.mutate !"); Mathematics.projectToRange(params.meanX, range); } -// System.out.println("--- In mutate!"); if (params != null && (params.firstAdaptionDone)) { double[] sampl = new double[dim]; // generate scaled random vector (D * z) for (int i = 0; i < dim; ++i) { @@ -677,9 +605,6 @@ public class MutateESRankMuCMA implements InterfaceAdaptOperatorGenerational, In if (!Mathematics.isInRange(params.meanX, range)) { System.err.println("Error B in MutateESRankMuCMA.mutate !"); } - if (TRACE_1) { - System.out.println("mutated indy: " + BeanInspector.toString(x)); - } return x; } @@ -788,7 +713,6 @@ public class MutateESRankMuCMA implements InterfaceAdaptOperatorGenerational, In * @return */ public boolean testAllDistBelow(Population pop, double tolX) { -// if all(sigma*(max(abs(pc), sqrt(diag(C)))) < stopTolX) boolean res = true; CMAParamSet params = (CMAParamSet) pop.getData(cmaParamsKey); int i = 0; @@ -796,11 +720,7 @@ public class MutateESRankMuCMA implements InterfaceAdaptOperatorGenerational, In res = res && (getSigma(params, i) * Math.max(Math.abs(params.pathC[i]), Math.sqrt(params.mC.get(i, i))) < tolX); i++; } - if (TRACE_TEST) { - if (res) { - System.out.println("testAllDistBelow hit"); - } - } + return res; } @@ -827,11 +747,6 @@ public class MutateESRankMuCMA implements InterfaceAdaptOperatorGenerational, In res = res && (params.meanX[i] == (params.meanX[i] + d * getSigma(params, i) * ev_k[i])); i++; } - if (TRACE_TEST) { - if (res) { - System.out.println("testNoChangeAddingDevAxis hit"); - } - } return res; } @@ -842,8 +757,6 @@ public class MutateESRankMuCMA implements InterfaceAdaptOperatorGenerational, In * @return */ public boolean testNoEffectCoord(Population pop, double d) { -// if any(xmean == xmean + 0.2*sigma*sqrt(diag(C))) -// stopflag(end+1) = {'warnnoeffectcoord'}; boolean ret = false; CMAParamSet params = (CMAParamSet) pop.getData(cmaParamsKey); int i = 0; @@ -851,11 +764,6 @@ public class MutateESRankMuCMA implements InterfaceAdaptOperatorGenerational, In ret = ret || (params.meanX[i] == (params.meanX[i] + d * getSigma(params, i) * Math.sqrt(params.mC.get(i, i)))); i++; } - if (TRACE_TEST) { - if (ret) { - System.out.println("testNoEffectCoord hit"); - } - } return ret; } @@ -867,18 +775,9 @@ public class MutateESRankMuCMA implements InterfaceAdaptOperatorGenerational, In * @return true, if a diagonal entry is <= 0 or >= d, else false */ public boolean testCCondition(Population pop, double d) { -// if (min(diag(D)) <= 0) || (max(diag(D)) > 1e14*min(diag(D))) -// stopflag(end+1) = {'warnconditioncov'}; CMAParamSet params = (CMAParamSet) pop.getData(cmaParamsKey); Pair minMax = params.mC.getMinMaxDiag(); - if ((minMax.head <= 0) || (minMax.tail >= d)) { - if (TRACE_TEST) { - System.out.println("testCCondition hit"); - } - return true; - } else { - return false; - } + return (minMax.head <= 0) || (minMax.tail >= d); } /** diff --git a/src/eva2/optimization/operator/paramcontrol/AbstractParameterControl.java b/src/eva2/optimization/operator/paramcontrol/AbstractParameterControl.java index fa01f1d6..d5812b04 100644 --- a/src/eva2/optimization/operator/paramcontrol/AbstractParameterControl.java +++ b/src/eva2/optimization/operator/paramcontrol/AbstractParameterControl.java @@ -16,7 +16,6 @@ import eva2.optimization.population.Population; */ public abstract class AbstractParameterControl implements InterfaceParameterControl { public Object[] initialValues = null; - protected static boolean TRACE = false; public AbstractParameterControl() { } @@ -57,10 +56,6 @@ public abstract class AbstractParameterControl implements InterfaceParameterCont if (!BeanInspector.setMem(obj, params[i], vals[i])) { System.err.println("Error: failed to set parameter from parameter control " + this.getClass().getName()); System.err.println(" Tried to set name/val: " + params[i] + " / " + BeanInspector.toString(vals[i])); - } else { - if (TRACE) { - System.out.println("Successfully set " + params[i] + " / " + BeanInspector.toString(vals[i]) + " at " + iteration); - } } } } diff --git a/src/eva2/optimization/operator/paramcontrol/ConstraintBasedAdaption.java b/src/eva2/optimization/operator/paramcontrol/ConstraintBasedAdaption.java index 308bbc61..f7c48975 100644 --- a/src/eva2/optimization/operator/paramcontrol/ConstraintBasedAdaption.java +++ b/src/eva2/optimization/operator/paramcontrol/ConstraintBasedAdaption.java @@ -30,9 +30,6 @@ public class ConstraintBasedAdaption implements ParamAdaption, Serializable { LinkedList lastBestSatisfactionState = new LinkedList(); - // private double endAct=0; -// private double deltaInertness = 0.1; - private static boolean TRACE = false; private static String target = "penaltyFactor"; @@ -44,8 +41,6 @@ public class ConstraintBasedAdaption implements ParamAdaption, Serializable { betaInc = o.betaInc; betaDec = o.betaDec; genGap = o.genGap; -// endAct = o.endAct; -// deltaInertness = o.deltaInertness; } @Override @@ -59,9 +54,6 @@ public class ConstraintBasedAdaption implements ParamAdaption, Serializable { if (!(obj instanceof AbstractConstraint)) { System.err.println(this.getClass().getSimpleName() + " cant control " + obj.getClass().getSimpleName() + " ! "); } else { - if (TRACE) { - System.out.println("calc value at it " + iteration + " of " + maxIteration); - } if (lastBestSatisfactionState.size() == genGap) { lastBestSatisfactionState.poll(); } @@ -80,9 +72,6 @@ public class ConstraintBasedAdaption implements ParamAdaption, Serializable { currentFactor = maxPenalty / initialPenalty; curPen = maxPenalty; } - if (TRACE && changed) { - System.out.println("NEW penalty: " + curPen); - } return curPen; } @@ -101,18 +90,10 @@ public class ConstraintBasedAdaption implements ParamAdaption, Serializable { if (allValid) { currentFactor *= betaDec; changed = true; - if (TRACE) { - System.out.println("all valid, new fact is " + currentFactor + " times " + initialPenalty); - } } else if (allInvalid) { changed = true; currentFactor *= betaInc; - if (TRACE) { - System.out.println("all invalid, new fact is " + currentFactor + " times " + initialPenalty); - } } - } else if (TRACE) { - System.out.println("not yet looking at " + genGap + " individuals..."); } return changed; } diff --git a/src/eva2/optimization/operator/paramcontrol/PSOActivityFeedbackControl.java b/src/eva2/optimization/operator/paramcontrol/PSOActivityFeedbackControl.java index d9b5553e..4edac604 100644 --- a/src/eva2/optimization/operator/paramcontrol/PSOActivityFeedbackControl.java +++ b/src/eva2/optimization/operator/paramcontrol/PSOActivityFeedbackControl.java @@ -27,7 +27,6 @@ public class PSOActivityFeedbackControl implements ParamAdaption, Serializable { private double startAct = 0.17; private double endAct = 0.01; private double deltaInertness = 0.1; - private static boolean TRACE = false; private boolean exponentialSchedule = true; private static String target = "inertnessOrChi"; @@ -71,9 +70,7 @@ public class PSOActivityFeedbackControl implements ParamAdaption, Serializable { private double calcNewInertness(double currentInertness, double currentAct, double desiredActivity) { - if (TRACE) { - System.out.println("Activity was " + currentAct + ", desired: " + desiredActivity); - } + if (currentAct < desiredActivity) { // increase inertness return Math.min(maxInert, currentInertness + deltaInertness); } else if (currentAct > desiredActivity) { // too high act, so decrease inertness diff --git a/src/eva2/optimization/operator/paramcontrol/ParameterControlManager.java b/src/eva2/optimization/operator/paramcontrol/ParameterControlManager.java index 7a5a669c..5386df78 100644 --- a/src/eva2/optimization/operator/paramcontrol/ParameterControlManager.java +++ b/src/eva2/optimization/operator/paramcontrol/ParameterControlManager.java @@ -27,7 +27,6 @@ import java.util.Vector; public class ParameterControlManager implements InterfaceParameterControl, Serializable { public Object[] initialValues = null; private ParamAdaption[] singleAdapters = new ParamAdaption[]{}; - protected static boolean TRACE = false; public ParameterControlManager() { } @@ -111,13 +110,6 @@ public class ParameterControlManager implements InterfaceParameterControl, Seria if (!BeanInspector.setMem(obj, params[i], vals[i])) { System.err.println("Error: failed to set parameter from parameter control " + this.getClass().getName()); System.err.println(" Tried to set name/val: " + params[i] + " / " + BeanInspector.toString(vals[i])); - } else { - if (TRACE) { - System.out.println("Successfully set " + params[i] + " / " + BeanInspector.toString(vals[i]) + " at " + iteration); - } -// if (!oldVal.equals(vals[i])) { -// if (obj instanceof InterfaceParamControllable) ((InterfaceParamControllable)obj).notifyParamChanged(params[i], oldVal, vals[i]); -// } } } Object[] args = new Object[]{null, pop, iteration, maxIteration}; @@ -140,8 +132,8 @@ public class ParameterControlManager implements InterfaceParameterControl, Seria public String[] getControlledParameters() { if (singleAdapters != null) { Vector names = new Vector(singleAdapters.length); - for (int i = 0; i < singleAdapters.length; i++) { - String prm = singleAdapters[i].getControlledParam(); + for (ParamAdaption singleAdapter : singleAdapters) { + String prm = singleAdapter.getControlledParam(); if (prm != null) { names.add(prm); } diff --git a/src/eva2/optimization/operator/paretofrontmetrics/MetricS.java b/src/eva2/optimization/operator/paretofrontmetrics/MetricS.java index acce0cf2..08a209a4 100644 --- a/src/eva2/optimization/operator/paretofrontmetrics/MetricS.java +++ b/src/eva2/optimization/operator/paretofrontmetrics/MetricS.java @@ -13,7 +13,6 @@ import eva2.problems.AbstractMultiObjectiveOptimizationProblem; public class MetricS implements InterfaceParetoFrontMetric, java.io.Serializable { private double[][] objectiveSpaceRange; - private static boolean TRACE = false; public MetricS() { @@ -57,35 +56,17 @@ public class MetricS implements InterfaceParetoFrontMetric, java.io.Serializable @Override public double calculateMetricOn(Population pop, AbstractMultiObjectiveOptimizationProblem problem) { this.objectiveSpaceRange = problem.getObjectiveSpaceRange(); - if (TRACE) { - System.out.println("Border: " + BeanInspector.toString(objectiveSpaceRange)); - } + double smetric = this.calculateSMetric(pop, this.objectiveSpaceRange, this.objectiveSpaceRange.length); double reference = 1; - for (int i = 0; i < this.objectiveSpaceRange.length; i++) { - reference *= (this.objectiveSpaceRange[i][1] - this.objectiveSpaceRange[i][0]); + for (double[] anObjectiveSpaceRange : this.objectiveSpaceRange) { + reference *= (anObjectiveSpaceRange[1] - anObjectiveSpaceRange[0]); } //System.out.println("SMetric: "+smetric +" Reference: " + reference); double res = ((Math.abs(smetric) / Math.abs(reference)) * 100); - if (TRACE) { - System.out.println("Res is " + res); - } return res; } -// /** This method gives a metric how to evaluate -// * an achieved Pareto-Front -// */ -// public double calculateMetricOn(Population pop) { -// double smetric = this.calculateSMetric(pop, this.objectiveSpaceRange, this.objectiveSpaceRange.length); -// double reference = 1; -// for (int i = 0; i < this.objectiveSpaceRange.length; i++) { -// reference *= (this.objectiveSpaceRange[i][1] - this.objectiveSpaceRange[i][0]); -// } -// //System.out.println("SMetric: "+smetric +" Reference: " + reference); -// return ((Math.abs(smetric)/Math.abs(reference))*100); -// } - /** * This method will calculate the s-metric from a double array of * fitness cases diff --git a/src/eva2/optimization/operator/postprocess/PostProcess.java b/src/eva2/optimization/operator/postprocess/PostProcess.java index 7133ab3e..44e75c71 100644 --- a/src/eva2/optimization/operator/postprocess/PostProcess.java +++ b/src/eva2/optimization/operator/postprocess/PostProcess.java @@ -46,7 +46,6 @@ import java.util.Vector; */ public class PostProcess { protected static InterfaceDistanceMetric metric = new PhenotypeMetric(); - private static final boolean TRACE = false; // the default mutation step size for HC post processing private static double defaultMutationStepSize = 0.01; @@ -175,17 +174,7 @@ public class PostProcess { result.setSameParams(pop); clustering.initClustering(pop); Population[] clusters = clustering.cluster(pop, null); - if (TRACE) { - System.out.println("found " + clusters.length + " clusters!"); - int sum = 0; - for (int j = 0; j < clusters.length; j++) { - sum += clusters[j].size(); - if (TRACE) { - System.out.print(j + " w " + clusters[j].size() + ", "); - } - } - System.out.println("\nsum was " + sum); - } + for (int j = 0; j < clusters.length; j++) { if (j == 0) { // cluster 0 contains non-assigned individuals if (lonerMode == DISCARD_LONERS) { @@ -580,9 +569,7 @@ public class PostProcess { case nelderMead: double[][] range = ((InterfaceDataTypeDouble) candidates.getEAIndividual(index)).getDoubleRange(); double perturb = findNMSPerturb(candidates, index, relToAbsPerturb(maxRelativePerturbation, range)); - if (TRACE) { - System.out.println("perturb " + index + " is " + perturb); - } + subPop = NelderMeadSimplex.createNMSPopulation(candidates.getEAIndividual(index), absToRelPerturb(perturb, range), range, false); } return subPop; @@ -636,9 +623,7 @@ public class PostProcess { return evalsDone; } else { int stepsPerCand = (steps - (candCnt * (dim - 1))) / candCnt; - if (TRACE) { - System.out.println("employing " + stepsPerCand + " steps per cand."); - } + if (stepsPerCand < dim) { System.err.println("Too few steps allowed in processSingleCandidates!"); System.err.println("Method: " + method + ", cands: " + candidates.size() + ", steps: " + steps); @@ -689,9 +674,7 @@ public class PostProcess { if (term == null) { int stepsPerCand = 10 * (nmPops.get(0).size() - 1); // == 10*dim for NM - if (TRACE) { - System.out.println("employing " + stepsPerCand + " per candidate."); - } + if (stepsPerCand < 1) { System.err.println("Too few steps allowed!"); return 0; @@ -959,18 +942,11 @@ public class PostProcess { double[] meanFit = clust.getMeanFitness(); - if (TRACE) { - System.out.println("BEF: funcalls done: " + pop.getFunctionCalls() + ", now allowed: " + funCalls); - } - int evalsDone = processSingleCandidates(method, clust, funCalls, sigmaCluster / 2., problem, mute); clust.setFunctionCalls(evalsBefore + evalsDone); double improvement = EuclideanMetric.euclideanDistance(meanFit, clust.getMeanFitness()); - if (TRACE) { - System.out.println("improvement by " + improvement + " funcalls done: " + evalsDone); - } return new Pair(clust, improvement); } @@ -990,7 +966,6 @@ public class PostProcess { listener.println("max peak ratio is " + mmkProb.getMaximumPeakRatio(getFoundOptima(solutions, mmkProb.getRealOptima(), mmkProb.getDefaultAccuracy(), true))); if (mmkProb.fullListAvailable()) { for (double epsilon = 0.1; epsilon > 0.00000001; epsilon /= 10.) { -// out.println("no optima found: " + ((InterfaceMultimodalProblemKnown)mmProb).getNumberOfFoundOptima(pop)); listener.println("found " + getFoundOptima(solutions, mmkProb.getRealOptima(), epsilon, true).size() + " for epsilon = " + epsilon + ", maxPeakRatio: " + mmkProb.getMaximumPeakRatio(solutions)); } } diff --git a/src/eva2/optimization/operator/terminators/PopulationMeasureTerminator.java b/src/eva2/optimization/operator/terminators/PopulationMeasureTerminator.java index 4e1790d6..09f8f865 100644 --- a/src/eva2/optimization/operator/terminators/PopulationMeasureTerminator.java +++ b/src/eva2/optimization/operator/terminators/PopulationMeasureTerminator.java @@ -22,15 +22,13 @@ import java.io.Serializable; * * @author mkron */ -public abstract class PopulationMeasureTerminator implements InterfaceTerminator, - Serializable { +public abstract class PopulationMeasureTerminator implements InterfaceTerminator, Serializable { public enum ChangeTypeEnum {relativeChange, absoluteChange, absoluteValue} public enum DirectionTypeEnum {decrease, bidirectional} public enum StagnationTypeEnum {fitnessCallBased, generationBased} - protected static boolean TRACE = false; private double convThresh = 0.01; //, convThreshLower=0.02; private double oldMeasure = -1; private int stagTime = 1000; @@ -96,9 +94,7 @@ public abstract class PopulationMeasureTerminator implements InterfaceTerminator @Override public boolean isTerminated(PopulationInterface pop) { if (!firstTime && isStillConverged(pop)) { - if (TRACE) { - System.out.println("Converged at " + pop.getGeneration() + "/" + pop.getFunctionCalls() + ", measure " + calcPopulationMeasure(pop)); - } + if (stagnationTimeHasPassed(pop)) { // population hasnt changed much for max time, criterion is met msg = getTerminationMessage(); @@ -226,18 +222,6 @@ public abstract class PopulationMeasureTerminator implements InterfaceTerminator break; } ret = (measure <= allowedUpper) && (measure >= allowedLower); - // Old Version: -// if (isRelativeConvergence()) { -// double delta = oldMeasure*convThresh; -// if (doCheckImprovement()) ret = (measure >= (oldMeasure - delta)); -// else ret = ((measure >= (oldMeasure-delta)) && (measure <= (oldMeasure+delta))); // check for rel. change which must be within +/- thresh -// } else { // check absolute values -// if (doCheckImprovement()) ret = (measure < oldMeasure+convThresh); // absolute improvement below fixed number -// else ret = ((measure < oldMeasure+convThresh) && (measure > oldMeasure-convThresh)); // absolute change within fixed range -// } - if (TRACE) { - System.out.println("isStillConverged returns " + ret + ", measure " + measure + ", old measure " + BeanInspector.toString(oldMeasure) + ", bounds: [" + allowedLower + " , " + allowedUpper + "]"); - } return ret; } @@ -277,16 +261,6 @@ public abstract class PopulationMeasureTerminator implements InterfaceTerminator return "Ratio of improvement/change or absolute value of improvement/change to determine convergence."; } -// public void setConvergenceThresholdLower(double x) { -// convThreshLower = x; -// } -// public double getConvergenceThresholdLower() { -// return convThreshLower; -// } -// public String convergenceThresholdUpperTipText() { -// return "Lower threshold value in case of detecting absolute change, meaning the bounds [measure-convThresh,measure+convThresh] must be kept to assume convergence."; -// } - public void setStagnationTime(int k) { stagTime = k; } diff --git a/src/eva2/optimization/population/Population.java b/src/eva2/optimization/population/Population.java index a7e533cd..81be69e7 100644 --- a/src/eva2/optimization/population/Population.java +++ b/src/eva2/optimization/population/Population.java @@ -1853,24 +1853,8 @@ public class Population extends ArrayList implements PopulationInterface, Clonea * an array of three */ public double[] getPopulationMeasures(InterfaceDistanceMetric metric) { -// Integer lastMeasuresModCount = (Integer)getData(lastPopMeasuresFlagKey); -// if (lastMeasuresModCount!=null && (lastMeasuresModCount==modCount)) { -// double[] measures = (double[])getData(lastPopMeasuresDatKey); -// if (TRACE ) { -// double[] verify = calcPopulationMeasures(metric); -// if (Mathematics.dist(measures, verify, 2)>1e-10) { -// System.out.println(getStringRepresentation()); -// System.err.println("Warning, invalid measures!!!"); -// -// } -// } -// return measures; -// } + double[] res = getPopulationMeasures(this, metric); -// putData(lastPopMeasuresFlagKey, new Integer(modCount)); -// putData(lastPopMeasuresDatKey, res); -// System.out.println(getStringRepresentation()); -// System.out.println("0-1-dist: " + BeanInspector.toString(metric.distance((AbstractEAIndividual)this.get(0), (AbstractEAIndividual)this.get(1)))); return res; } diff --git a/src/eva2/optimization/stat/EvAStatisticalEvaluation.java b/src/eva2/optimization/stat/EvAStatisticalEvaluation.java index ed41a75f..bd3e680c 100644 --- a/src/eva2/optimization/stat/EvAStatisticalEvaluation.java +++ b/src/eva2/optimization/stat/EvAStatisticalEvaluation.java @@ -19,29 +19,6 @@ public class EvAStatisticalEvaluation { public static EvAStatisticalEvaluationParams statsParams = new EvAStatisticalEvaluationParams(); -// public static void evaluate(OptimizationJob[] jobList, int[] selectedIndices) { -// if (TRACE) System.out.println("Job list: " + BeanInspector.toString(jobList)); -// JTextoutputFrame textout = new JTextoutputFrame("Statistics"); -// textout.setShow(true); -// ArrayList jobsToWorkWith = new ArrayList(); -// for (int i=0; i commonFields = getCommonFields(jobsToWorkWith); -// if (commonFields!=null && !commonFields.isEmpty()) for (String field : commonFields) { -// textout.println("Checking field " + field); -// -// for (int i=0; i setOfSubswarms = new Vector(); boolean reinitSuperfl = true; - boolean TRACEMTHD = false; - // ... and use the corresponding particles to create the subswarms - if (TRACEMTHD) { - System.out.println("---------"); - } for (Set connSet : connectedComps) { if (connSet.size() > 1) {// create niche Population pop = new Population(connSet.size()); @@ -540,16 +535,9 @@ public class ANPSO extends NichePSO implements InterfaceOptimizer, InterfaceAddi } pop.add(indy); } - if (TRACEMTHD) { - System.out.print(" subswarm size ssize " + pop.size()); - } if (maxInitialSubSwarmSize > 0 && (pop.size() > maxInitialSubSwarmSize)) { - if (TRACEMTHD) { - System.out.print(" removing " + (pop.size() - maxInitialSubSwarmSize)); - } tmpPop = pop.getWorstNIndividuals(pop.size() - maxInitialSubSwarmSize, -1); tmpPop.synchSize(); -// Population testPop=(Population)pop.clone(); pop.removeMembers(tmpPop, true); if (reinitSuperfl) { for (int i = 0; i < tmpPop.size(); i++) { @@ -565,9 +553,6 @@ public class ANPSO extends NichePSO implements InterfaceOptimizer, InterfaceAddi pop.synchSize(); } setOfSubswarms.add(pop); - if (TRACEMTHD) { - System.out.print("\nNew subswarm of size: " + pop.size()); - } } else { // move particles corresponding to unconnected vertices to the mainswarm Iterator it = connSet.iterator(); Integer index = Integer.valueOf(it.next()); @@ -575,17 +560,10 @@ public class ANPSO extends NichePSO implements InterfaceOptimizer, InterfaceAddi newMainPop.add(indy); } } -// for (int i=0; i(); - //reinitedSwarm = new Vector(); + deactivatedSwarm = new Vector<>(); // merging mergingOccurd = false; - borg = new Vector(); - others = new Vector(); - borgbest = new Vector(); - othersbest = new Vector(); + borg = new Vector<>(); + others = new Vector<>(); + borgbest = new Vector<>(); + othersbest = new Vector<>(); // absorbtion absorbtionOccurd = false; - indytoabsorb = new Vector(); + indytoabsorb = new Vector<>(); // subswarmcreation creationOccurd = false; - indyconverged = new Vector(); - convergedneighbor = new Vector(); + indyconverged = new Vector<>(); + convergedneighbor = new Vector<>(); //clearing - deprecated //reinitoccurd = false; @@ -751,21 +725,10 @@ public class ANPSO extends NichePSO implements InterfaceOptimizer, InterfaceAddi currentsubswarm = (Population) getSubSwarms().get(i).getPopulation().clone(); metapop.addPopulation(currentsubswarm); } - for (int i = 0; i < inactiveSubSwarms.size(); ++i) { // in the case of ANPSO - currentsubswarm = (Population) inactiveSubSwarms.get(i).getPopulation().clone(); + for (ParticleSubSwarmOptimization inactiveSubSwarm : inactiveSubSwarms) { // in the case of ANPSO + currentsubswarm = (Population) inactiveSubSwarm.getPopulation().clone(); metapop.addPopulation(currentsubswarm); } - // add the best pbest particle to the population -// if (metapop.size() != 0){ -// AbstractEAIndividual hero = (AbstractEAIndividual)metapop.getEAIndividual(0).getData("PersonalBestKey"); -// for (int i = 0; i < metapop.size(); ++i){ -// AbstractEAIndividual currentPBest = (AbstractEAIndividual)metapop.getEAIndividual(i).getData("PersonalBestKey"); -// if (currentPBest.isDominating(hero)){ -// hero = currentPBest; -// } -// } -// metapop.add(hero); -// } // set correct number of generations metapop.setGeneration(getMainSwarm().getPopulation().getGeneration()); @@ -774,9 +737,7 @@ public class ANPSO extends NichePSO implements InterfaceOptimizer, InterfaceAddi int calls = getMainSwarm().getPopulation().getFunctionCalls(); for (int i = 0; i < getSubSwarms().size(); ++i) { ParticleSubSwarmOptimization subswarm = getSubSwarms().get(i); - // if (subswarm.isActive()){ calls += subswarm.getPopulation().getFunctionCalls(); - // } } // calls from inactivated subswarms were transfered to the mainswarm, see useAsSubSwarms method @@ -795,17 +756,13 @@ public class ANPSO extends NichePSO implements InterfaceOptimizer, InterfaceAddi int mainSize = 0; //if (includeMainSwarm) mainSize = getMainSwarm().getPopulation().size(); Population elitePop = new Population(getSubSwarms().size() + inactiveSubSwarms.size() + mainSize); -// if (includeMainSwarm){ -// for (int i = 0; i < mainSize; ++i){ -// elite[i] = getMainSwarm().getPopulation().getEAIndividual(i); -// } -// } + for (int i = 0; i < getSubSwarms().size(); ++i) { AbstractEAIndividual bestSS = getSubSwarms().get(i).getBestIndividual(); elitePop.addIndividual((AbstractEAIndividual) getSubSwarms().get(i).bestIndividual.clone()); } - for (int i = 0; i < inactiveSubSwarms.size(); ++i) { - elitePop.addIndividual((AbstractEAIndividual) inactiveSubSwarms.get(i).bestIndividual.clone()); + for (ParticleSubSwarmOptimization inactiveSubSwarm : inactiveSubSwarms) { + elitePop.addIndividual((AbstractEAIndividual) inactiveSubSwarm.bestIndividual.clone()); } return elitePop; } @@ -821,7 +778,6 @@ public class ANPSO extends NichePSO implements InterfaceOptimizer, InterfaceAddi for (int i = 0; i < getSubSwarms().size() + inactiveSubSwarms.size(); ++i) { result += elite.getEAIndividual(i).getStringRepresentation() + "\n"; } - //result += "\n"; return result; } @@ -863,15 +819,8 @@ public class ANPSO extends NichePSO implements InterfaceOptimizer, InterfaceAddi if (!currentsubswarm.isActive()) { plotCircleForIndy((AbstractEAIndividual) best, "[I]"); } else { - if (!getSubswarmOptimizerTemplate().isGcpso()) { - //plotCircleForIndy((AbstractEAIndividual)best,getMaxStdDevFromSwarmAsString(currentsubswarm)); - } if (getSubswarmOptimizerTemplate().isGcpso()) { String rhoAsString = String.format("%6.3f", currentsubswarm.getRho()); - //plotCircleForIndy((AbstractEAIndividual)best,rhoAsString); - if (currentsubswarm.gbestParticle != null) { - //plotCircleForIndy((AbstractEAIndividual)currentsubswarm.gbestParticle,"gbest"); - } } } @@ -921,12 +870,6 @@ public class ANPSO extends NichePSO implements InterfaceOptimizer, InterfaceAddi return "ANPSO-" + getMainSwarmSize(); } -// -// public double getMinimalR() { -// return minimalR; -// } - - public void SetMinimalR(double minimalR) { this.minimalR = minimalR; } diff --git a/src/eva2/optimization/strategies/BinaryScatterSearch.java b/src/eva2/optimization/strategies/BinaryScatterSearch.java index 88316430..85d750b9 100644 --- a/src/eva2/optimization/strategies/BinaryScatterSearch.java +++ b/src/eva2/optimization/strategies/BinaryScatterSearch.java @@ -30,8 +30,6 @@ import java.util.BitSet; */ @Description("A basic implementation of a Binary ScatterSearch") public class BinaryScatterSearch implements InterfaceOptimizer, java.io.Serializable, InterfacePopulationChangedEventListener { - - private static boolean TRACE = false; transient private InterfacePopulationChangedEventListener populationChangedEventListener = null; private String identifier = "BinaryScatterSearch"; private int MaxImpIter = 5; @@ -236,17 +234,9 @@ public class BinaryScatterSearch implements InterfaceOptimizer, java.io.Serializ int numToInit = this.poolSize - pop.size(); if (numToInit > 0) { pop.addAll(generateG1((int) (numToInit * this.g1))); - if (TRACE) { - System.out.println("s1: " + pop.size()); - } + generateG2(pop, (int) (numToInit * this.g2)); - if (TRACE) { - System.out.println("s2: " + pop.size()); - } generateG3(pop, poolSize - pop.size()); - if (TRACE) { - System.out.println("s3: " + pop.size()); - } } return pop; } @@ -272,8 +262,9 @@ public class BinaryScatterSearch implements InterfaceOptimizer, java.io.Serializ * 000...000, then 010101...01, 101010...10, 001001001...001, * 110110110...110 and so on * - * @param pop the initial Population - * @return the new Population + * @param targetSize The size of the new Population + * @param template The template individual to use + * @return a new Population */ public static Population generateG1Pop(int targetSize, AbstractEAIndividual template) { boolean method1 = true; @@ -716,8 +707,7 @@ public class BinaryScatterSearch implements InterfaceOptimizer, java.io.Serializ // generate a new Pool this.pool = new Population(); ArrayList newSubsets = generateSubsets(); - for (int i = 0; i < newSubsets.size(); i++) { - Population s = newSubsets.get(i); + for (Population s : newSubsets) { AbstractEAIndividual x = combineSolution(s); if (!contains((InterfaceDataTypeBinary) x, this.pool) && this.pool.size() <= this.poolSize) { this.pool.add(x); diff --git a/src/eva2/optimization/strategies/ClusterBasedNichingEA.java b/src/eva2/optimization/strategies/ClusterBasedNichingEA.java index b8fb3003..bfbcae34 100644 --- a/src/eva2/optimization/strategies/ClusterBasedNichingEA.java +++ b/src/eva2/optimization/strategies/ClusterBasedNichingEA.java @@ -69,7 +69,6 @@ public class ClusterBasedNichingEA implements InterfacePopulationChangedEventLis private int populationSize = 50; private int convergedCnt = 0; private int collisions = 0; - private static boolean TRACE = false, TRACE_STATE = false, TRACE_EVTS = false; private int showCycle = 0; transient private TopoPlot topologyPlot; private int haltingWindow = 15; @@ -450,88 +449,43 @@ public class ClusterBasedNichingEA implements InterfacePopulationChangedEventLis return ret; } else { return (histComparator.compare(firstIndy, secIndy) > 0); -// return (secIndy.isDominatingDebConstraints(firstIndy)); } } private Population optimizeSpecies(Population species, boolean minorPlot) { optimizer.setPopulation(species); -// optimizer.initializeByPopulation(species, false); if (optimizer instanceof EvolutionStrategies) { EvolutionStrategies es = (EvolutionStrategies) optimizer; int mu = Math.max(1, (int) (muLambdaRatio * species.size())); if (mu >= species.size()) { - if (TRACE) { - System.err.println("warning, muLambdaRatio produced mu >= lambda.. reducing to mu=lambda-1"); - } mu = Math.max(1, species.size() - 1); } es.setMu(mu); es.setLambda(species.size()); - if (TRACE) { - System.out.println("mu: " + es.getMu() + " / lambda: " + es.getLambda()); - } - } - if (TRACE) { - System.out.println("Bef: spec size: " + species.size() + ", target size " + species.getTargetSize()); - System.out.println("Best bef: " + BeanInspector.toString(optimizer.getPopulation().getBestFitness())); } if (BeanInspector.hasMethod(optimizer, "getLastModelPopulation", null) != null) { Object pc = BeanInspector.callIfAvailable(optimizer, "getLastTrainingPatterns", null); -// System.out.println("MAPSO train set bef optSpec: " + BeanInspector.callIfAvailable(pc, "getStringRepresentation", null)); } this.optimizer.optimize(); Population retPop = optimizer.getPopulation(); - - if (TRACE) { - System.out.println("Aft: spec size: " + retPop.size() + ", target size " + retPop.getTargetSize()); - System.out.println("Best aft: " + BeanInspector.toString(retPop.getBestFitness())); - } if (retPop.size() != retPop.getTargetSize()) { - if (TRACE) { - System.out.println("correcting popsize after opt: " + retPop.getTargetSize() + " to " + retPop.size()); - } retPop.synchSize(); } - -// if (useDistraction) { // distraction step -// if ((distraction != null) && (!distraction.isEmpty())) { -// System.out.println("Distraction step!!!"); -// boolean distrHappened = false; -// for (int i=0; i 0) { reinitPop = this.initializeIndividuals(doomedPopulation.size()); // do not add these to undifferentiated yet, that would mess up the evaluation count doomedPopulation.clear(); -// if (TRACE) -// System.out.println("At " + undifferentiatedPopulation.getFunctionCalls() + " reinited " + reinitPop.size() + " indies... "); } int countIndies = (reinitPop != null ? reinitPop.size() : 0) + undifferentiatedPopulation.size(); - for (int i = 0; i < species.size(); i++) { - countIndies += species.get(i).size(); - } - if (TRACE) { - System.out.println("NumIndies: " + countIndies); + for (Population specy1 : species) { + countIndies += specy1.size(); } if (this.showCycle > 0) { if (undifferentiatedPopulation.getGeneration() <= 1) { @@ -550,7 +504,6 @@ public class ClusterBasedNichingEA implements InterfacePopulationChangedEventLis // optimize D_0 this.undifferentiatedPopulation.synchSize(); if (undifferentiatedPopulation.size() > 0) { -// this.capMutationRate(this.undifferentiatedPopulation, 0); // MK this sets mutation rate to 0! why? possibly to guarantee contraction of the species? undifferentiatedPopulation.putData(InterfaceSpeciesAware.populationTagKey, InterfaceSpeciesAware.explorerPopTag); undifferentiatedPopulation = optimizeSpecies(undifferentiatedPopulation, false); } else { @@ -560,40 +513,17 @@ public class ClusterBasedNichingEA implements InterfacePopulationChangedEventLis Population curSpecies; // optimize the clustered species for (int i = this.species.size() - 1; i >= 0; i--) { - if (TRACE) { - System.out.println("-Deme " + i + " size: " + this.species.get(i).size()); - } curSpecies = this.species.get(i); curSpecies.setFunctionCalls(0); curSpecies.synchSize(); -// if (isActive(curSpecies)) { // Lets have only active species... if ((haltingWindow > 0) && (this.testSpeciesForConvergence(curSpecies))) { -///////////////////////////////////////////// Halting Window ///////////////////////////////////////////////// -// if (this.debug) { -// System.out.println("Undiff.Size: " + this.undifferentiatedPopulation.size() +"/"+this.undifferentiatedPopulation.getPopulationSize()); -// System.out.println("Diff.Size : " + ((Population)this.species.get(i)).size() +"/"+((Population)this.species.get(i)).getPopulationSize()); -// } convergedCnt++; - if (TRACE_EVTS) { - System.out.println("!!!! Converged Spec!"); - } - if (TRACE) { - testSpeciesForConvergence(curSpecies); - System.out.print("--Converged: " + convergedCnt + " - " + testSpeciesForConvergence(curSpecies)); - } - if (TRACE) { - System.out.println(curSpecies.getBestEAIndividual()); - } - - // memorize the best one.... -// AbstractEAIndividual best = (AbstractEAIndividual)curSpecies.getBestEAIndividual().getClone(); AbstractEAIndividual best = curSpecies.getBestHistoric(); // usually we want the best alltogether if (best == null) { best = (AbstractEAIndividual) curSpecies.getBestEAIndividual().getClone(); } int toReinit = 0; populationArchive.add(best); -// System.out.println((""+ population.getFunctionCalls() + " " + (BeanInspector.toString(best.getDoublePosition())).replaceAll(";|\\[|\\]", ""))); species.remove(i); // remove the converged Species toReinit = curSpecies.size(); // those will not be optimized anymore, so we dont need to doom them, but can directly add them to undiff! @@ -609,17 +539,13 @@ public class ClusterBasedNichingEA implements InterfacePopulationChangedEventLis // } // This is necessary to keep track of the function calls needed undifferentiatedPopulation.incrFunctionCallsBy(curSpecies.getFunctionCalls()); - if (TRACE) { - System.out.println("### funcalls: " + undifferentiatedPopulation.getFunctionCalls()); - } } - ////////////////////// synchronized (population) { // fill the population instance with the current individuals from undiff, spec, etc. this.population = (Population) this.undifferentiatedPopulation.clone(); population.setUseHistory(true); - for (int i = 0; i < this.species.size(); i++) { - this.population.addPopulation(this.species.get(i)); + for (Population specy : this.species) { + this.population.addPopulation(specy); } if (doomedPopulation.size() > 0) { population.addPopulation(reinitPop); @@ -627,34 +553,15 @@ public class ClusterBasedNichingEA implements InterfacePopulationChangedEventLis population.synchSize(); } - ////////////////////// - if ((this.undifferentiatedPopulation.getFunctionCalls() + (reinitPop == null ? 0 : (reinitPop.size()))) % this.populationSize != 0) { - if (TRACE) { - System.out.println("### mismatching number of funcalls, inactive species?"); - }// Correcting by " + (populationSize - (undifferentiatedPopulation.getFunctionCalls() % populationSize))); -// if (TRACE) System.out.println("### undiff " + ((isActive(undifferentiatedPopulation)) ? "active!" : "inactive!")); -// undifferentiatedPopulation.incrFunctionCallsBy(populationSize - (undifferentiatedPopulation.getFunctionCalls() % populationSize)); - } //else if (TRACE) System.out.println("### undiff active: " + isActive(undifferentiatedPopulation)); - // possible species differentiation and convergence if (this.undifferentiatedPopulation.getGeneration() % this.speciesCycle == 0) { - if (TRACE) { - System.out.println("Species cycle:"); - } initClustering(); if (this.useSpeciesDifferentiation) { -///////////////////////////// species differentiation phase - if (TRACE) { - printState("---Species Differentation", reinitPop); - } Population[] clusters; ArrayList newSpecies = new ArrayList(); //cluster the undifferentiated population clusters = this.caForSpeciesDifferentation.cluster(this.undifferentiatedPopulation, population); - if (TRACE) { - System.out.println("clustered undiff to " + clusters.length); - } for (int j = 1; j < clusters.length; j++) { // loop new clusters splitFromFirst(undifferentiatedPopulation, clusters[j], false); newSpecies.add(clusters[j]); @@ -662,12 +569,8 @@ public class ClusterBasedNichingEA implements InterfacePopulationChangedEventLis replaceUndifferentiated(clusters[0]); for (int i = 0; i < this.species.size(); i++) { // loop old species curSpecies = this.species.get(i); -// if (curSpecies.size()>minGroupSize) { // only active populations are clustered // check if a species has differentiated any further clusters = this.caForSpeciesDifferentation.cluster(curSpecies, population); - if (TRACE) { - System.out.println("clustered " + i + " to " + clusters.length); - } if (clusters[0].size() > 0) { mergeToFirst(undifferentiatedPopulation, clusters[0], false); } @@ -683,17 +586,8 @@ public class ClusterBasedNichingEA implements InterfacePopulationChangedEventLis newSpecies.add(clusters[j]); } -// } else { -// // small populations are kept directly -// newSpecies.add(curSpecies); -// } } this.species = newSpecies; - if (TRACE) { - printState("---After differentiation", reinitPop); - } - - //if (this.show) this.plot(); } // end of species differentiation // plot the populations @@ -704,17 +598,10 @@ public class ClusterBasedNichingEA implements InterfacePopulationChangedEventLis } if (this.mergeSpecies && (species.size() > 0)) { -///////////////////////////// species merging phase - if (TRACE) { - System.out.println("-Species merge:"); - } // first test if loners belong to any species int[] assocSpec = caForSpeciesMerging.associateLoners(undifferentiatedPopulation, species.toArray(new Population[species.size()]), population); for (int i = undifferentiatedPopulation.size() - 1; i >= 0; i--) { // backwards or die! if (assocSpec[i] >= 0) { - if (TRACE_EVTS) { - System.out.println("!!! Loner merge to " + i); - } // loner i should be merged to species assocSpec[i] AbstractEAIndividual tmpIndy = (AbstractEAIndividual) this.undifferentiatedPopulation.get(i); if (topologyPlot != null) { @@ -724,9 +611,6 @@ public class ClusterBasedNichingEA implements InterfacePopulationChangedEventLis species.get(assocSpec[i]).add(tmpIndy); // TODO merge information from loners? } } - if (TRACE) { - printState("---After loner-merges", reinitPop); - } Population spec1, spec2; // test if species are close to already archived solutions - deactivate them if so assocSpec = caForSpeciesMerging.associateLoners(populationArchive, species.toArray(new Population[species.size()]), population); @@ -740,16 +624,6 @@ public class ClusterBasedNichingEA implements InterfacePopulationChangedEventLis // the species has not yet been deactivated specToRemove.add(assocSpec[i]); collisions++; - if (TRACE) { - System.out.println("Inactive merge - resetting " + spec1.size() + " surplus indies"); - } - if (spec1.getBestEAIndividual().isDominating(aIndy)) { - // update the archived one with the better one? No rather not - it may happen that a large species is assoctiated which is quite large and spans over several optima - in that case an earlier found may get lost -// populationArchive.set(i, spec1.getBestEAIndividual()); - } - if (TRACE_EVTS) { - System.out.println("!!! Reinit Spec " + assocSpec[i] + ", fit " + spec1.getBestEAIndividual()); - } doomedPopulation.addPopulation(spec1); } } @@ -760,15 +634,9 @@ public class ClusterBasedNichingEA implements InterfacePopulationChangedEventLis if (specIndex > lastRemoved) { System.err.println("Stupid queue!!!"); } - if (TRACE) { - System.out.println("Removing species at index " + specIndex); - } species.remove(specIndex); // warning, dont try to remove Integer object but index i! lastRemoved = specIndex; } - if (TRACE) { - printState("---After archive-merges", reinitPop); - } // Now test if species should be merged among each other for (int i1 = 0; i1 < this.species.size(); i1++) { spec1 = this.species.get(i1); @@ -776,39 +644,24 @@ public class ClusterBasedNichingEA implements InterfacePopulationChangedEventLis spec2 = this.species.get(i2); if (this.caForSpeciesMerging.mergingSpecies(spec1, spec2, population)) { - if (TRACE_EVTS || TRACE) { - System.out.println("!!! -Merging species (" + i1 + ", " + i2 + ") [" + spec1.size() + "/" + spec2.size() + "]"); - } mergeToFirst(spec1, spec2, true); this.species.remove(i2); i2--; } } } - if (TRACE) { - printState("---After merging", reinitPop); - } } /// end of species merging if (maxSpeciesSize >= minGroupSize) { // reinit worst n individuals from all species which are too large - for (int i = 0; i < species.size(); i++) { - Population curSpec = species.get(i); + for (Population curSpec : species) { if (curSpec.size() > maxSpeciesSize) { - if (TRACE_EVTS) { - System.out.println("!!! Reinit indies " + (maxSpeciesSize - curSpec.size())); - } ArrayList sorted = curSpec.getSorted(reduceSizeComparator); for (int k = maxSpeciesSize; k < sorted.size(); k++) { if (curSpec.remove(sorted.get(k))) { doomedPopulation.add(sorted.get(k)); } } -// reinitCount = sorted.size()-maxSpeciesSize; -// curSpec.setPopulationSize(maxSpeciesSize); -// if (TRACE) System.out.println("Reduced spec " + i + " to size " + curSpec.size() + ", reinit of " + reinitCount + " indies immanent..."); -// this.undifferentiatedPopulation.addPopulation(this.initializeIndividuals(reinitCount)); -// this.undifferentiatedPopulation.setPopulationSize(this.undifferentiatedPopulation.getPopulationSize()+reinitCount); } } } @@ -821,40 +674,21 @@ public class ClusterBasedNichingEA implements InterfacePopulationChangedEventLis } undifferentiatedPopulation.setTargetSize(undifferentiatedPopulation.size()); // output the result - if (TRACE) { - System.out.println("-Funcalls: " + this.undifferentiatedPopulation.getFunctionCalls()); - } synchronized (population) { // fill the population instance with the current individuals from undiff, spec, etc. this.population = (Population) this.undifferentiatedPopulation.clone(); population.setUseHistory(true); - for (int i = 0; i < this.species.size(); i++) { - this.population.addPopulation(this.species.get(i)); + for (Population specy : this.species) { + this.population.addPopulation(specy); } if (doomedPopulation.size() > 0) { population.addPopulation(doomedPopulation); } // this is just so that the numbers match up... population.synchSize(); - if (TRACE) { - System.out.println("Doomed size: " + doomedPopulation.size()); - System.out.println("Population size: " + this.population.size()); - } if (population.size() != populationSize) { System.err.println("Warning: Invalid population size in CBNEA! " + population.size()); } - if (TRACE_STATE) { - printState("---- EoCBN", doomedPopulation); - System.out.println("Archive: " + populationArchive.getStringRepresentation()); - } } -// if (TRACE) { -// // this is just a test adding all species centers as distractors with high strength -// Distraction distr = new Distraction(5., 0, species); -// if (!distr.isEmpty()) { -// double[] distVect = distr.calcDistractionFor(undifferentiatedPopulation.getBestEAIndividual()); -// System.out.println("species distract best towards " + BeanInspector.toString(distVect)); -// } -// } this.firePropertyChangedEvent(Population.NEXT_GENERATION_PERFORMED); } @@ -866,9 +700,6 @@ public class ClusterBasedNichingEA implements InterfacePopulationChangedEventLis if (getClusterDiffDist() > 0) { // assume that it should be set if (this.caForSpeciesDifferentation instanceof InterfaceClusteringDistanceParam) { ((InterfaceClusteringDistanceParam) caForSpeciesDifferentation).setClustDistParam(getClusterDiffDist()); - if (TRACE) { - System.out.println("### Clustering distance parameter set to " + getClusterDiffDist()); - } } else { EVAERROR.errorMsgOnce("Warning: cluster distance is defined in CBN but the clustering method " + caForSpeciesDifferentation.getClass() + " cant interpret it!"); } @@ -876,49 +707,16 @@ public class ClusterBasedNichingEA implements InterfacePopulationChangedEventLis this.caForSpeciesDifferentation.initClustering(population); } -// -// /** -// * Unite all current species and the undiff. pop and return -// * the merged set. Note that data such as generation, evaluations etc -// * are not copied! -// * -// * @return -// */ -// private Population getCurrentPop() { -// Population pop = new Population(getPopulationSize()); -// pop.addPopulation(undifferentiatedPopulation); -// for (int i=0; i 0) { - sum += species.get(0).size(); - System.out.print(specTag(species.get(0))); - for (int i = 1; i < species.size(); i++) { - System.out.print(", " + specTag(species.get(i))); - sum += species.get(i).size(); - } - } - System.out.println(", reinit: " + (reinit == null ? 0 : reinit.size()) + ", sum: " + sum); - } - private String specTag(Population spec) { return spec.size() + "(" + spec.getGeneration() + ((spec.hasData("MAPSOModelInformation")) ? "/" + (BeanInspector.callIfAvailable(spec.getData("MAPSOModelInformation"), "getStringRepresentation", null)) : "") + ")"; } @@ -927,11 +725,11 @@ public class ClusterBasedNichingEA implements InterfacePopulationChangedEventLis * Merge two species by adding the second to the first. Keep the longer * history. The second species should be deactivated after merging. * - * @param pop1 - * @param pop2 + * @param spec1 + * @param spec2 + * @param plot */ protected void mergeToFirst(Population spec1, Population spec2, boolean plot) { -// System.out.println("Merging " + spec2.size() + " to " + spec1.size()); if (plot && (topologyPlot != null)) { plotLine(topologyPlot, spec1.getBestEAIndividual(), spec2.getBestEAIndividual()); } diff --git a/src/eva2/optimization/strategies/ClusteringHillClimbing.java b/src/eva2/optimization/strategies/ClusteringHillClimbing.java index 13e780fc..9799d5e8 100644 --- a/src/eva2/optimization/strategies/ClusteringHillClimbing.java +++ b/src/eva2/optimization/strategies/ClusteringHillClimbing.java @@ -40,7 +40,6 @@ public class ClusteringHillClimbing implements InterfacePopulationChangedEventLi InterfaceOptimizer, Serializable, InterfaceAdditionalPopulationInformer { transient private InterfacePopulationChangedEventListener populationChangedEventListener; - public static final boolean TRACE = false; transient private String identifier = ""; private Population population = new Population(); private transient Population archive = new Population(); @@ -48,7 +47,6 @@ public class ClusteringHillClimbing implements InterfacePopulationChangedEventLi private int hcEvalCycle = 1000; private int initialPopSize = 100; private int loopCnt = 0; - // private int baseEvalCnt = 0; private int notifyGuiEvery = 50; private double sigmaClust = 0.01; private double minImprovement = 0.000001; @@ -198,9 +196,6 @@ public class ClusteringHillClimbing implements InterfacePopulationChangedEventLi evalsNow = hcEvalCycle; } do { - if (TRACE) { - System.out.println("evalCycle: " + hcEvalCycle + ", evals now: " + evalsNow); - } popD = PostProcess.clusterLocalSearch(localSearchMethod, population, (AbstractOptimizationProblem) optimizationProblem, sigmaClust, evalsNow, 0.5, mutator); // (population, (AbstractOptimizationProblem)problem, sigmaClust, hcEvalCycle - (population.getFunctionCalls() % hcEvalCycle), 0.5); if (popD.head().getFunctionCalls() == funCallsBefore) { @@ -210,21 +205,12 @@ public class ClusteringHillClimbing implements InterfacePopulationChangedEventLi } while (popD.head().getFunctionCalls() == funCallsBefore); improvement = popD.tail(); population = popD.head(); - if (TRACE) { - System.out.println("num inds after clusterLS: " + population.size()); - } popD.head().setGeneration(population.getGeneration() + 1); if (doReinitialization && (improvement < minImprovement)) { - if (TRACE) { - System.out.println("improvement below " + minImprovement); - } if ((localSearchMethod != PostProcessMethod.hillClimber) || (mutator.getSigma() < stepSizeThreshold)) { // reinit! // is performed for nm and cma, and if hc has too low sigma - if (TRACE) { - System.out.println("REINIT!!"); - } if (localSearchMethod == PostProcessMethod.hillClimber) { mutator.setSigma(initialStepSize); @@ -252,12 +238,8 @@ public class ClusteringHillClimbing implements InterfacePopulationChangedEventLi System.err.println("Invalid case in ClusteringHillClimbing!"); } mutator.setSigma(mutator.getSigma() * reduceFactor); - if (TRACE) { - System.out.println("mutation stepsize reduced to " + mutator.getSigma()); - } } } -// System.out.println("funcalls: " + evalCnt); this.firePropertyChangedEvent(Population.NEXT_GENERATION_PERFORMED); } @@ -266,17 +248,10 @@ public class ClusteringHillClimbing implements InterfacePopulationChangedEventLi public void registerPopulationStateChanged(Object source, String name) { // The events of the interim hill climbing population will be caught here if (name.compareTo(Population.FUN_CALL_INTERVAL_REACHED) == 0) { -// if ((((Population)source).size() % 50) > 0) { -// System.out.println("bla"); -// } // set funcalls to real value population.setFunctionCalls(((Population) source).getFunctionCalls()); -// System.out.println("FunCallIntervalReached at " + (((Population)source).getFunctionCalls())); this.firePropertyChangedEvent(Population.NEXT_GENERATION_PERFORMED); } - // do not react to NextGenerationPerformed - //else System.err.println("ERROR, event was " + name); - } /** diff --git a/src/eva2/optimization/strategies/EsDpiNiching.java b/src/eva2/optimization/strategies/EsDpiNiching.java index 37b9e08e..deab42dc 100644 --- a/src/eva2/optimization/strategies/EsDpiNiching.java +++ b/src/eva2/optimization/strategies/EsDpiNiching.java @@ -91,7 +91,6 @@ import java.util.Formatter; + "in parallel, which are reclustered in each iteration based on the dynamic peak set.") public class EsDpiNiching implements InterfaceOptimizer, Serializable, InterfaceAdditionalPopulationInformer, InterfacePopulationChangedEventListener { - private static final boolean TRACE = false, TRACE_DEMES = false; private double nicheRadius = 0.3; private int expectedPeaks = 5; private int explorerPeaks = 0; @@ -250,7 +249,6 @@ public class EsDpiNiching implements InterfaceOptimizer, Serializable, Interface population.incrFunctionCallsBy(peakOpts[i].getPopulation().getFunctionCalls()); } // possibly reduce immigrants to produce a conforming number of initial evaluations (same number as in later iterations: numPeaks*muLambda+immigrants) -// int initialImmigrants = (fullNumPeaks()*lambdaPerPeak+getNumRndImmigrants())-(fullNumPeaks()*muPerPeak+getNumRndImmigrants()); if (getNumRndImmigrants() > 0) { generateEvalImmigrants(getNumRndImmigrants()); } @@ -319,7 +317,6 @@ public class EsDpiNiching implements InterfaceOptimizer, Serializable, Interface } r = 0.5 * Math.sqrt(dim); } -// setNicheRadius(r*Math.pow(numExpectedPeaks, -1./(double)dim)); return r * Math.pow(numExpectedOptima, -1. / (double) dim); } @@ -347,8 +344,6 @@ public class EsDpiNiching implements InterfaceOptimizer, Serializable, Interface } private int increaseExpectedPeaksCriterion() { -// if ((getPopulation().getGeneration() % 5) == 0) return 1; -// else return 0; if (isDoNumPeakAdaption() && (archive.size() >= getExpectedPeaks())) { return (int) Math.max(((double) getExpectedPeaks()) * 1.2, 2.); } else { @@ -374,9 +369,6 @@ public class EsDpiNiching implements InterfaceOptimizer, Serializable, Interface if (increaseExpectedPeaksCriterion() > 0) { addExpectedPeaks(increaseExpectedPeaksCriterion()); } - if (TRACE) { - System.out.println("--- FULL POP SIZE: " + population.size() + " , funcalls: " + population.getFunctionCalls() + ", gen " + population.getGeneration()); - } ClusteringDynPeakIdent dpiClustering = new ClusteringDynPeakIdent(getExpectedPeaks(), getLambdaPerPeak(), nicheRadius, true, metric); // perform dynamic peak identification resulting in the dynamic peak set dps dpiClustering.initClustering(population); @@ -386,20 +378,12 @@ public class EsDpiNiching implements InterfaceOptimizer, Serializable, Interface peakPopSet[i].removePopulationChangedEventListener(this); } setGeneration(population.getGeneration(), peakPopSet); - if (TRACE_DEMES) { - printDemes("After clustering: ", peakPopSet); - } int curNumPeaks = peakPopSet.length - 1; -// boolean copyHashFromParents=true; // transfer population hash data along the peaks -> for each peak chose the original last population // and transfer the data to the new cluster -// if (copyHashFromParents) { copyDataFromParents(peakPopSet); -// } else { -// copyDataFromClosest(clusteredPeakPops); -// } int reqNewPeaks = 0; if (curNumPeaks < getExpectedPeaks()) { @@ -427,10 +411,6 @@ public class EsDpiNiching implements InterfaceOptimizer, Serializable, Interface // add missing and explorer peaks as new random individuals (or old unclustered ones) peakPopSet = generateMissingSpecies(peakPopSet, getMuPerPeak(), reqNewPeaks, false); - if (TRACE_DEMES) { - printDemes("After expansion: ", peakPopSet); - } - if (archive != null && (archive.size() > 0) && isReinitOnCollision()) { double origNicheRad = dpiClustering.getNicheRadius(); dpiClustering.setNicheRadius(collisionDetNicheRadius); @@ -443,28 +423,12 @@ public class EsDpiNiching implements InterfaceOptimizer, Serializable, Interface // the new found species is actually better than the archived solution archive.set(i, peakPopSet[assoc[i]].getBestEAIndividual().clone()); // replace archived indy } - if (TRACE) { - System.out.println(" Converged on archived solution.. resetting peak pop " + assoc[i]); - } peakPopSet[assoc[i]] = initRandomPeakPop(getMuPerPeak()); } } dpiClustering.setNicheRadius(origNicheRad); - if (TRACE_DEMES) { - printDemes("After archivie-merge: ", peakPopSet); - } } - if (TRACE) { - for (int k = 0; k < peakPopSet.length - 1; k++) { - for (int j = k + 1; j < peakPopSet.length; j++) { - Population cut = peakPopSet[k].setCut(peakPopSet[j]); - if (cut.size() > 0) { - System.err.println("duplicate inherited in EsDpiNiching! OK if explorer peaks exist that are not always reinited and " + j + ">" + getExpectedPeaks() + " and " + k + "==0."); - } - } - } - } plot = null; // now generate the lambda offsprings // nextGeneration = this.generateEvalChildren(dps); // create lambda new ones from mu parents @@ -475,9 +439,6 @@ public class EsDpiNiching implements InterfaceOptimizer, Serializable, Interface if (curSpecies.size() == 1 && (!isAllowSingularPeakPops())) { // Quoting SB05: "In case that the niche only contains one individual, the second parent will be the best indidivual of another niche." AbstractEAIndividual bestOther = (AbstractEAIndividual) selectBestFromOtherSpecies(clustIndex, peakPopSet).clone(); - if (TRACE) { - System.out.println("Adding best from other species: " + bestOther); - } curSpecies.add(bestOther); } else if (curSpecies.size() == 0) { System.err.println("Warning, empty niche population in EsDpiNiching!"); @@ -497,19 +458,10 @@ public class EsDpiNiching implements InterfaceOptimizer, Serializable, Interface if (doDraw(population.getGeneration())) { drawPeakPop("" + clustIndex, curSpecies); } - if (TRACE) { - System.out.println("Optimizing cluster index " + (clustIndex) + ", size " + curSpecies.size()); - } peakOpts[clustIndex - 1].optimize(); // !!!!!!!! Actual optimization step optimizedSpecies = peakOpts[clustIndex - 1].getPopulation(); optimizedSpecies.putData(origPeakIndyKey, curPeak); population.incrFunctionCallsBy(optimizedSpecies.size()); -// optimizedSpecies.incrGeneration(); // is already done in the .optimize() call above -// optimizedSpecies.incrFunctionCallsBy(optimizedSpecies.size()); - if (TRACE) { - System.out.println(" ..." + optimizedSpecies.size() + " more funcalls... "); - } - } // we may have a problem if, by chance, all species have been deactivated simultaneously AND there are no unclustered ! @@ -518,21 +470,6 @@ public class EsDpiNiching implements InterfaceOptimizer, Serializable, Interface peakOpts[0].getPopulation().addPopulation(initRandomPeakPop(getMuPerPeak())); } - if (TRACE) { - for (int k = 0; k < peakPopSet.length - 1; k++) { - for (int j = k + 1; j < peakPopSet.length; j++) { - Population cut = peakPopSet[k].setCut(peakPopSet[j]); - if (cut.size() > 1) { - // one may happen after a cluster had a size of one, since then another leader is added - if (cut.size() == 2 && (peakPopSet[k].size() == 2) && (peakPopSet[j].size() == 2)) { - // two may happen since they can be added reciprocally to each other - } else { - System.err.println("duplicate indy in EsDpiNiching. OK if explorer peaks exist that are not always reinited and " + j + ">" + getExpectedPeaks() + " and " + k + "==0."); - } - } - } - } - } if (doEtaPreselection) { // this basically replaces ES-environment selection // select the eta best from the offspring per peak population // fill up to muPerPeak by adding from the old peak population @@ -545,9 +482,6 @@ public class EsDpiNiching implements InterfaceOptimizer, Serializable, Interface System.err.println("Warning: fewer clusters than expected peaks in EsDpiNiching!"); offspring.clear(); // empty set to avoid duplicates! } else { - if (TRACE) { - System.out.println("EtaPresel: from " + offspring.size() + " offspring selecting " + eta); - } Population selected = selBest.selectFrom(offspring, eta); if (!selected.isSubSet(offspring)) { System.err.println("fatal problem in EsDpiNiching!!!"); @@ -558,33 +492,16 @@ public class EsDpiNiching implements InterfaceOptimizer, Serializable, Interface int delta = muPerPeak - eta; if (delta > 0) { Population filterPeakPop = peakPopSet[i + 1].filter(selected); - if (TRACE) { - System.out.println("Adding " + Math.min(delta, filterPeakPop.size()) + " from peak population."); - } // (few) duplicates may happen because parents are copied to another peak population // if a cluster had a size of 1 AND parents may survive due to elitism. selected.addPopulation(selBest.selectFrom(filterPeakPop, Math.min(delta, filterPeakPop.size())), false); if (selected.size() < muPerPeak && (addLonersToPeaks)) { delta = Math.min(muPerPeak - selected.size(), loners.size()); - if (TRACE) { - System.out.println("filling up with lucky loners: " + delta); - } // fill up with loner indies SelectRandom selRnd = new SelectRandom(false); // no duplicates wanted! Population luckyLosers = selRnd.selectFrom(loners, delta); selected.addPopulation(luckyLosers, true); loners.removeMembers(luckyLosers, true); - // fill up with random indies - // Population randomNewIndies = new Population(lambdaPerPeak - selected.size()); - // problem.initializePopulation(randomNewIndies); // function calls?? - // selected.addAll(randomNewIndies); - } - } - if (TRACE) { - for (int k = 0; k < i; k++) { - if (selected.setCut(peakOpts[k].getPopulation()).size() > 2) { //one may happen after a cluster had size one (see above) - System.err.println("Warning, nonempty set cut between " + k + " and " + i + " !"); - } } } peakOpts[i].population.clear(); @@ -595,7 +512,7 @@ public class EsDpiNiching implements InterfaceOptimizer, Serializable, Interface } } } -// System.out.println("Best of second peak: " + clusteredPeakPops[2].getBestEAIndividual()); + if (doDraw(population.getGeneration()) && archive != null) { for (int i = 0; i < this.archive.size(); i++) { ClusterBasedNichingEA.plotIndy(plot, 'x', (InterfaceDataTypeDouble) archive.get(i)); @@ -605,7 +522,6 @@ public class EsDpiNiching implements InterfaceOptimizer, Serializable, Interface generateEvalImmigrants(getNumRndImmigrants()); } collectPopulationIncGen(population, peakOpts, randomNewIndies); - //this.firePropertyChangedEvent(Population.NEXT_GENERATION_PERFORMED); // moved this to registerPopulationStateChanged which is called from the population } private Population deactivateSpecies(int clustIndex, boolean resetRandomly) { @@ -634,7 +550,6 @@ public class EsDpiNiching implements InterfaceOptimizer, Serializable, Interface Population origPop = peakOpts[origEsPop].getPopulation(); clusteredPeakPops[i].copyHashData(origPop); clusteredPeakPops[i].SetHistory(origPop.getHistory()); // copy the history for deactivation! -// System.out.println("Copied hash for peak " + clusteredPeakPops[i].getBestEAIndividual() + ", cluster " + i + " from " + origEsPop); } else { // ok in the first iteration of if the indy was a random immigrant if (population.getGeneration() > 1 && (getNumRndImmigrants() == 0)) { System.err.println("Error, empty original es pop ID!"); @@ -643,30 +558,6 @@ public class EsDpiNiching implements InterfaceOptimizer, Serializable, Interface } } - // /** -// * For each new cluster copy the additional data from the closest parent population. -// * -// * @param clusteredPeakPops -// */ -// private void copyDataFromClosest(Population[] clusteredPeakPops) { -// Population centers = new Population(clusteredPeakPops.length); -// AbstractEAIndividual indy; -// // collect leaders -// for (int i=0; i closestIdDist = Population.getClosestFarthestIndy(clusteredPeakPops[i].getBestEAIndividual(), centers, metric, true); -// Population closestPop = peakOpts[closestIdDist.head()].getPopulation(); -// System.out.println("Closest to new peak " + indy.toString() + " is old pop " + closestPop.getData(origPeakIndyKey)); -// System.out.println(" meanX was " + (MutateESRankMuCMA.getMeanXOfPop(closestPop))); -// clusteredPeakPops[i].copyHashData(closestPop); -// } -// } private void printDemes(String prefix, Population[] peakPops) { System.out.print(prefix + " demes: "); for (int i = 0; i < peakPops.length; i++) { @@ -743,9 +634,6 @@ public class EsDpiNiching implements InterfaceOptimizer, Serializable, Interface for (int i = 0; i < origClusters.length; i++) { newClusters[i] = origClusters[i]; } - if (TRACE) { - System.out.println("Generated missing peak species..."); - } return newClusters; } } @@ -776,9 +664,6 @@ public class EsDpiNiching implements InterfaceOptimizer, Serializable, Interface problem.initializePopulation(randomNewIndies); problem.evaluate(randomNewIndies); population.incrFunctionCallsBy(cnt); - if (TRACE) { - System.out.println("evaluated immigrants: " + randomNewIndies.size()); - } } else { randomNewIndies = null; } @@ -802,9 +687,6 @@ public class EsDpiNiching implements InterfaceOptimizer, Serializable, Interface if (rndIndex == i) { rndIndex++; } - if (TRACE) { - System.out.println("selected spec index " + rndIndex); - } return clusteredSpecies[rndIndex].getBestEAIndividual(); } @@ -828,7 +710,6 @@ public class EsDpiNiching implements InterfaceOptimizer, Serializable, Interface } ClusterBasedNichingEA.plotPopConnected(plot, npop); plot.drawIndividual(1, 0, "", npop.getBestEAIndividual()); -// plot.drawPopulation(prefix, npop); } catch (Exception e) { plot = null; } @@ -926,18 +807,13 @@ public class EsDpiNiching implements InterfaceOptimizer, Serializable, Interface // (few) duplicates may happen because parents are copied to another peak population // if a cluster had a size of 1 AND parents may survive due to elitism. pop.addPopulation(pi, false); -// if (i==0) pop.setGeneration(pi.getGeneration()); -// else if (pop.getGeneration()!=pi.getGeneration()) System.err.println("Error, mismatching generation in collectPopulation"); } if (immigrants != null) { - immigrants.putDataAllIndies(originalPeakPop, new Integer(-2)); + immigrants.putDataAllIndies(originalPeakPop, -2); pop.addPopulation(immigrants, true); } pop.incrGeneration(); pop.synchSize(); - if (TRACE) { - System.out.println("Collected " + pop.size() + " indies in pop."); - } } /** diff --git a/src/eva2/optimization/strategies/GradientDescentAlgorithm.java b/src/eva2/optimization/strategies/GradientDescentAlgorithm.java index 97e77d37..641bd0d0 100644 --- a/src/eva2/optimization/strategies/GradientDescentAlgorithm.java +++ b/src/eva2/optimization/strategies/GradientDescentAlgorithm.java @@ -1,6 +1,5 @@ package eva2.optimization.strategies; -import eva2.gui.BeanInspector; import eva2.optimization.go.InterfacePopulationChangedEventListener; import eva2.optimization.individuals.AbstractEAIndividual; import eva2.optimization.individuals.InterfaceDataTypeDouble; @@ -47,7 +46,6 @@ public class GradientDescentAlgorithm implements InterfaceOptimizer, java.io.Ser // These variables are necessary for the more complex LectureGUI enviroment transient private String identifier = ""; private Population population; - private static boolean TRACE = false; private static final String lockKey = "gdaLockDataKey"; private static final String lastFitnessKey = "gdaLastFitDataKey"; private static final String stepSizeKey = "gdaStepSizeDataKey"; @@ -155,10 +153,8 @@ public class GradientDescentAlgorithm implements InterfaceOptimizer, java.io.Ser int[] lock = (int[]) indy.getData(lockKey); double indystepsize = ((Double) indy.getData(stepSizeKey)).doubleValue(); - // System.out.println("indystepsize" + indystepsize); if ((this.optimizationProblem instanceof InterfaceFirstOrderDerivableProblem) && (indy instanceof InterfaceDataTypeDouble)) { -// Hashtable history = (Hashtable) indyhash.get(indy); for (int iterations = 0; iterations < this.iterations; iterations++) { double[] oldgradient = indy.hasData(gradientKey) ? (double[]) indy.getData(gradientKey) : null; @@ -166,9 +162,6 @@ public class GradientDescentAlgorithm implements InterfaceOptimizer, java.io.Ser double[] oldchange = null; double[] gradient = ((InterfaceFirstOrderDerivableProblem) optimizationProblem).getFirstOrderGradients(params); - if (TRACE) { - System.out.println("GDA: " + BeanInspector.toString(params) + ", grad: " + BeanInspector.toString(gradient)); - } if ((oldgradient != null) && (wstepsize != null)) { // LOCAL adaption for (int li = 0; li < wstepsize.length; li++) { double prod = gradient[li] * oldgradient[li]; @@ -180,7 +173,6 @@ public class GradientDescentAlgorithm implements InterfaceOptimizer, java.io.Ser wstepsize[li] = (wstepsize[li] < localminstepsize) ? localminstepsize : wstepsize[li]; wstepsize[li] = (wstepsize[li] > localmaxstepsize) ? localmaxstepsize : wstepsize[li]; -// System.out.println("wstepsize "+ li + " " + wstepsize[li]); } } @@ -251,11 +243,8 @@ public class GradientDescentAlgorithm implements InterfaceOptimizer, java.io.Ser if (this.recovery) { for (int i = 0; i < this.population.size(); i++) { indy = ((AbstractEAIndividual) this.population.get(i)); -// Hashtable history = (Hashtable) indyhash.get(indy); if (indy.getFitness()[0] > recoverythreshold) { - if (TRACE) { - System.out.println("Gradient Descent: Fitness critical:" + indy.getFitness()[0]); - } + ((InterfaceDataTypeDouble) indy).setDoublePhenotype((double[]) indy.getData(oldParamsKey)); double[] changes = (double[]) indy.getData(changesKey); int[] lock = (int[]) indy.getData(lockKey); @@ -282,8 +271,7 @@ public class GradientDescentAlgorithm implements InterfaceOptimizer, java.io.Ser //System.out.println("gsa main"); for (int i = 0; i < this.population.size(); i++) { indy = ((AbstractEAIndividual) this.population.get(i)); -// Hashtable history = (Hashtable) indyhash.get(indy); -// if (history == null) break; + if (indy.getData(lastFitnessKey) != null) { double lastfit = ((Double) indy.getData(lastFitnessKey)).doubleValue(); double indystepsize = ((Double) indy.getData(stepSizeKey)).doubleValue(); @@ -296,7 +284,7 @@ public class GradientDescentAlgorithm implements InterfaceOptimizer, java.io.Ser //System.out.println("newstepsize" + indystepsize); indystepsize = (indystepsize > globalmaxstepsize) ? globalmaxstepsize : indystepsize; indystepsize = (indystepsize < globalminstepsize) ? globalminstepsize : indystepsize; - indy.putData(stepSizeKey, new Double(indystepsize)); + indy.putData(stepSizeKey, indystepsize); } //System.out.println("newstepsize in bounds" + indystepsize); diff --git a/src/eva2/optimization/strategies/IslandModelEA.java b/src/eva2/optimization/strategies/IslandModelEA.java index 1f980a0f..0edef4ab 100644 --- a/src/eva2/optimization/strategies/IslandModelEA.java +++ b/src/eva2/optimization/strategies/IslandModelEA.java @@ -50,7 +50,6 @@ public class IslandModelEA implements InterfacePopulationChangedEventListener, I transient private Plot plot = null; transient private String identifier = ""; transient private InterfacePopulationChangedEventListener populationChangedEventListener; - transient private final boolean TRACE = false; public IslandModelEA() { } @@ -203,15 +202,9 @@ public class IslandModelEA implements InterfacePopulationChangedEventListener, I for (int i = 0; i < this.islands.length; i++) { if (this.islands[i].getPopulation().size() > 0) { this.islands[i].optimize(); - if (TRACE) { - System.out.println(BeanInspector.toString(islands[i].getPopulation())); - } } else { this.islands[i].getPopulation().incrGeneration(); } - if (TRACE) { - System.out.println("----"); - } } this.population.incrGeneration(); if ((this.population.getGeneration() % this.migrationRate) == 0) { diff --git a/src/eva2/optimization/strategies/MemeticAlgorithm.java b/src/eva2/optimization/strategies/MemeticAlgorithm.java index 428d36e5..20565588 100644 --- a/src/eva2/optimization/strategies/MemeticAlgorithm.java +++ b/src/eva2/optimization/strategies/MemeticAlgorithm.java @@ -34,9 +34,6 @@ public class MemeticAlgorithm implements InterfaceOptimizer, private int subsetsize = 5; private int globalSearchIterations = 1; private boolean lamarckism = true; - // int counter = 0; !? - // int maxfunctioncalls = 1000; !? - private boolean TRACE = false; private String identifier = ""; private InterfaceOptimizationProblem optimizationProblem = new F1Problem(); private InterfaceOptimizer globalOptimizer = new GeneticAlgorithm(); @@ -94,20 +91,13 @@ public class MemeticAlgorithm implements InterfaceOptimizer, @Override public void optimize() { - - if (TRACE) { - System.out.println("global search"); - } this.globalOptimizer.optimize(); if ((globalSearchIterations > 0) && (((this.globalOptimizer.getPopulation().getGeneration() % this.globalSearchIterations) == 0)) && (this.localSearchSteps > 0) && (this.optimizationProblem instanceof InterfaceLocalSearchable)) { // here the local search is performed - if (TRACE) { - System.out.println("Performing local search on " + subsetsize - + " individuals."); - } + Population gop = this.globalOptimizer.getPopulation(); Population subset = selectorPlug.selectFrom(gop, subsetsize); Population subsetclone = new Population(); @@ -164,17 +154,9 @@ public class MemeticAlgorithm implements InterfaceOptimizer, gop.setFunctionCalls(gop.getFunctionCalls() + (int) Math.round(localSearchSteps * cost * subset.size())); - if (TRACE) { - System.out.println("Population size after local search:" + gop.size()); - } - this.setPopulation(gop); } - if (TRACE) { - System.out.println("function calls" - + this.globalOptimizer.getPopulation().getFunctionCalls()); - } this.firePropertyChangedEvent(Population.NEXT_GENERATION_PERFORMED); } @@ -205,9 +187,6 @@ public class MemeticAlgorithm implements InterfaceOptimizer, */ protected void firePropertyChangedEvent(String name) { if (this.populationChangedEventListener != null) { - if (TRACE) { - System.out.println("firePropertyChangedEvent MA"); - } this.populationChangedEventListener.registerPopulationStateChanged(this, name); } } diff --git a/src/eva2/optimization/strategies/ParticleFilterOptimization.java b/src/eva2/optimization/strategies/ParticleFilterOptimization.java index 54299c17..247700d5 100644 --- a/src/eva2/optimization/strategies/ParticleFilterOptimization.java +++ b/src/eva2/optimization/strategies/ParticleFilterOptimization.java @@ -47,7 +47,6 @@ public class ParticleFilterOptimization implements InterfaceOptimizer, java.io.S transient private int indCount = 0; transient private InterfacePopulationChangedEventListener populationChangedEventListener; transient Plot myPlot = null; - public static final boolean TRACE = false; public ParticleFilterOptimization() { if (withShow) { @@ -167,9 +166,6 @@ public class ParticleFilterOptimization implements InterfaceOptimizer, java.io.S parents.add(immi); } parents.synchSize(); - if (TRACE) { - System.out.println("Added " + i + " random individuals"); - } } parents.setFunctionCalls(pop.getFunctionCalls()); @@ -249,14 +245,9 @@ public class ParticleFilterOptimization implements InterfaceOptimizer, java.io.S // predict step predict(nextGeneration); - if (TRACE) { - System.out.println("Speed is " + BeanInspector.toString(ParticleSwarmOptimization.getPopulationVelSpeed(population, 3, MutateESCorrVector.vectorKey, null, null)) + " popM " + BeanInspector.toString(population.getPopulationMeasures(new EuclideanMetric()))); - } population = evaluatePopulation(nextGeneration); -// collectStatistics(population); - this.firePropertyChangedEvent(Population.NEXT_GENERATION_PERFORMED); } diff --git a/src/eva2/optimization/strategies/ParticleSwarmOptimization.java b/src/eva2/optimization/strategies/ParticleSwarmOptimization.java index de09b635..dfd50ecd 100644 --- a/src/eva2/optimization/strategies/ParticleSwarmOptimization.java +++ b/src/eva2/optimization/strategies/ParticleSwarmOptimization.java @@ -103,7 +103,6 @@ public class ParticleSwarmOptimization implements InterfaceOptimizer, java.io.Se // parameter for exponential moving average private int emaPeriods = 0; // for debugging only - transient private static boolean TRACE = false; transient protected boolean show = false; transient protected Plot plot; private boolean externalInitialPop = false; @@ -778,7 +777,7 @@ public class ParticleSwarmOptimization implements InterfaceOptimizer, java.io.Se for (int i = 0; i < this.population.size(); i++) { double[] succVel = (double[]) population.getEAIndividual(i).getData(lastSuccessKey); if (succVel != null) { - successes.add(new Integer(i)); + successes.add(i); } } if (successes.size() > 0) { @@ -1250,15 +1249,6 @@ public class ParticleSwarmOptimization implements InterfaceOptimizer, java.io.Se * Do some preparations in the beginning of the loop. */ protected void startOptimize() { - if (TRACE) { - for (int i = 0; i < population.size(); i++) { - AbstractEAIndividual indy = population.getEAIndividual(i); - System.out.println(BeanInspector.toString(indy.getData(partTypeKey))); - System.out.println(BeanInspector.toString(indy.getData(partBestPosKey))); - System.out.println(BeanInspector.toString(indy.getData(partBestFitKey))); - System.out.println(BeanInspector.toString(indy.getData(partVelKey))); - } - } if (this.show) { this.show(); } @@ -1580,9 +1570,6 @@ public class ParticleSwarmOptimization implements InterfaceOptimizer, java.io.Se initIndividualMemory(indy); indy.putData(indexKey, i); indy.setIndividualIndex(i); - if (TRACE) { - System.err.println("initialize indy " + i + " " + AbstractEAIndividual.getDefaultDataString(indy)); - } } } } diff --git a/src/eva2/optimization/strategies/ScatterSearch.java b/src/eva2/optimization/strategies/ScatterSearch.java index 8609f8b2..650feac2 100644 --- a/src/eva2/optimization/strategies/ScatterSearch.java +++ b/src/eva2/optimization/strategies/ScatterSearch.java @@ -70,7 +70,6 @@ public class ScatterSearch implements InterfaceOptimizer, java.io.Serializable, private double nelderMeadInitPerturbation = 0.01; private double improvementEpsilon = 0.1; // minimal relative fitness improvement for a candidate to be taken over into the refset private double minDiversityEpsilon = 0.0001; // minimal phenotypic distance for a candidate to be taken over into the refset - private static boolean TRACE = false; public ScatterSearch() { GenericObjectEditor.setHideProperty(this.getClass(), "population", true); @@ -137,14 +136,9 @@ public class ScatterSearch implements InterfaceOptimizer, java.io.Serializable, */ private void initRefSet(Population pop) { optimizationProblem.evaluate(pop); - if (TRACE) { - System.out.println("building ref set from pop with avg dist " + pop.getPopulationMeasures()[0]); - } refSet = getRefSetFitBased(new Population(refSetSize), pop); refSet.incrFunctionCallsBy(pop.size()); - if (TRACE) { - System.out.println("ref set size " + refSet.size() + " avg dist " + refSet.getPopulationMeasures()[0]); - } + refSet.addPopulationChangedEventListener(this); refSet.setNotifyEvalInterval(generationCycle); } @@ -166,9 +160,6 @@ public class ScatterSearch implements InterfaceOptimizer, java.io.Serializable, } probDim = (Integer) dim; range = ((InterfaceDataTypeDouble) template).getDoubleRange(); - if (TRACE) { - System.out.println("Range is " + BeanInspector.toString(range)); - } } } @@ -228,27 +219,15 @@ public class ScatterSearch implements InterfaceOptimizer, java.io.Serializable, int funCallsStart = refSet.getFunctionCalls(); do { if (combinations == null || combinations.size() == 0) { - if (TRACE) { - System.out.println("Improvements: " + lastImprovementCount); - System.out.println("---------- best: " + refSet.getBestEAIndividual().getFitness(0)); - } combinations = generateCombinations(refSet); oldRefSet = (Population) refSet.clone(); lastImprovementCount = 0; } - if (TRACE) { - System.out.println("No combinations: " + combinations.size()); - } if (combinations.size() > 0) { updateRefSet(refSet, combinations, oldRefSet); } } while (refSet.getFunctionCalls() - funCallsStart < generationCycle); optimizationProblem.evaluatePopulationEnd(refSet); - - if (TRACE) { - System.out.println("Improvements: " + lastImprovementCount); - } - } private boolean isDoLocalSolver(AbstractEAIndividual cand, Population refSet) { @@ -271,15 +250,9 @@ public class ScatterSearch implements InterfaceOptimizer, java.io.Serializable, Population diversifiedPop = diversify(); int keep = refSetSize / 2; Population newRefSet = refSet.cloneWithoutInds(); - if (TRACE) { - System.out.println("regen after " + refSet.getFunctionCalls() + ", best is " + refSet.getBestEAIndividual().getFitness(0)); - } newRefSet.addAll(refSet.getBestNIndividuals(keep, fitCrit)); - if (TRACE) { - System.out.println("keeping " + keep + " indies from former ref set, best is " + newRefSet.getBestEAIndividual().getFitness(0)); - } int h = newRefSet.size(); ArrayList distVects = new ArrayList(); @@ -364,10 +337,6 @@ public class ScatterSearch implements InterfaceOptimizer, java.io.Serializable, AbstractEAIndividual bestCand = candidates.getEAIndividual(bestIndex); AbstractEAIndividual worstRef = refSet.getWorstEAIndividual(); - if (TRACE) { - System.out.println("best cand: " + bestCand.getFitness(0)); - } - if (isDoLocalSolver(bestCand, refSet)) { Pair lsRet = localSolver(bestCand, localSearchSteps); if ((Math.abs(lsRet.tail() - localSearchSteps) / localSearchSteps) > 0.05) { @@ -375,33 +344,21 @@ public class ScatterSearch implements InterfaceOptimizer, java.io.Serializable, } bestCand = lsRet.head(); refSet.incrFunctionCallsBy(lsRet.tail()); - if (TRACE) { - System.out.println("best cand after: " + bestCand.getFitness(0)); - } } if (bestCand.isDominatingEqual(worstRef)) { - if (TRACE) { - System.out.println("cand is dominating worst ref!"); - } if (diversityCriterionFulfilled(bestCand, refSet, oldRefSet)) { -// System.out.println("diversity criterion is fulfilled! replacing fit " + worstRef.getFitness(0)); int replIndex = refSet.indexOf(worstRef); refSet.set(replIndex, bestCand); lastImprovementCount++; } else if (bestCand.isDominating(refSet.getBestEAIndividual())) { // exception: always accept best solution found so far int closestIndex = getClosestIndy(bestCand, refSet); -// if (TRACE) System.out.println("replacing due to best fit"); refSet.set(closestIndex, bestCand); lastImprovementCount++; } -// System.out.println("Improvements: " + lastImprovementCount); candidates.remove(bestIndex); } else { - if (TRACE) { - System.out.println("cand is too bad!"); - } // if the best candidate is worse and no local search is performed, all following will be worse - at least in the uni-criterial case // so we can just clear the rest of the candidates if (!doLocalSearch && (bestCand.getFitness().length == 1)) { @@ -422,7 +379,6 @@ public class ScatterSearch implements InterfaceOptimizer, java.io.Serializable, private Pair localSolverHC(AbstractEAIndividual cand, int hcSteps) { // use HC for a start... -// double[] fitBefore = cand.getFitness(); Population hcPop = new Population(1); hcPop.add(cand); int stepsDone = PostProcess.processWithHC(hcPop, optimizationProblem, hcSteps); @@ -481,7 +437,6 @@ public class ScatterSearch implements InterfaceOptimizer, java.io.Serializable, for (int i = 0; i < half - 1; i++) { // better-better AbstractEAIndividual indy1 = refSorted.getEAIndividual(i); for (int j = i + 1; j < half; j++) { -// if (TRACE) System.out.println("combi T bb, " + i+ "/" + j); AbstractEAIndividual indy2 = refSorted.getEAIndividual(j); combs.add(combineTypeOne(indy1, indy2)); combs.add(combineTypeTwo(indy1, indy2)); @@ -493,7 +448,6 @@ public class ScatterSearch implements InterfaceOptimizer, java.io.Serializable, for (int i = 0; i < half; i++) { // better-worse AbstractEAIndividual indy1 = refSorted.getEAIndividual(i); for (int j = half; j < refSet.size(); j++) { -// if (TRACE) System.out.println("combi T bw, " + i+ "/" + j); AbstractEAIndividual indy2 = refSorted.getEAIndividual(j); combs.add(combineTypeOne(indy1, indy2)); combs.add(combineTypeTwo(indy1, indy2)); @@ -504,7 +458,6 @@ public class ScatterSearch implements InterfaceOptimizer, java.io.Serializable, for (int i = half; i < refSet.size() - 1; i++) { // worse-worse AbstractEAIndividual indy1 = refSorted.getEAIndividual(i); for (int j = i + 1; j < refSet.size(); j++) { -// if (TRACE) System.out.println("combi T ww, " + i+ "/" + j); AbstractEAIndividual indy2 = refSorted.getEAIndividual(j); combs.add(combineTypeTwo(indy1, indy2)); if (RNG.flipCoin(0.5)) { @@ -514,10 +467,6 @@ public class ScatterSearch implements InterfaceOptimizer, java.io.Serializable, } } } - - if (TRACE) { - System.out.println("created combinations " + combs.size() + " best is " + combs.getBestEAIndividual().getFitness(0)); - } return combs; } @@ -649,9 +598,7 @@ public class ScatterSearch implements InterfaceOptimizer, java.io.Serializable, pop.add(createDiverseIndy(freq)); } pop.setTargetSize(poolSize); - if (TRACE) { - System.out.println("created diverse pop size " + pop.size()); - } + return pop; } diff --git a/src/eva2/optimization/strategies/Tribes.java b/src/eva2/optimization/strategies/Tribes.java index e09be179..bfbbe3ae 100644 --- a/src/eva2/optimization/strategies/Tribes.java +++ b/src/eva2/optimization/strategies/Tribes.java @@ -134,7 +134,6 @@ import java.util.List; @Description("TRIBES: a parameter free PSO implementation by Maurice Clerc.") public class Tribes implements InterfaceOptimizer, java.io.Serializable { - public static final boolean TRACE = false; protected String identifier = "TRIBES"; transient private InterfacePopulationChangedEventListener listener = null; protected AbstractOptimizationProblem optimizationProblem; @@ -322,16 +321,7 @@ public class Tribes implements InterfaceOptimizer, java.io.Serializable { } optimizationProblem.evaluatePopulationEnd(population); -// this.population.incrFunctionCallsby(evals); this.population.incrGeneration(); - //this.firePropertyChangedEvent("NextGenerationPerformed"); // This is now done implicitely, as after every evaluation, addEvals is called - - if (TRACE) { - System.out.println("loop finished after " + population.getFunctionCalls() + " evaluations"); - //for (int i=0; i samples.length) { K = samples.length; } @@ -72,11 +67,11 @@ public class KMEANSJAVA { for (int indexofc = 0; indexofc < c.length; indexofc++) { double[] newcenter = new double[samples[0].length]; int treffer = 0; - for (int j = 0; j < indices.length; j++) { //System.out.println("j="+j); - if (indices[j] == indexofc) { + for (int indice : indices) { //System.out.println("j="+j); + if (indice == indexofc) { treffer++; for (int d = 0; d < newcenter.length; d++) { - newcenter[d] += c[indices[j]][d]; + newcenter[d] += c[indice][d]; //newcenter[d] = newcenter[d] + samples[j][d]; } } @@ -88,7 +83,6 @@ public class KMEANSJAVA { } // determine the new centers } - //System.out.println("out"); } /** @@ -115,9 +109,9 @@ public class KMEANSJAVA { System.out.println(""); } System.out.println("test"); - for (int i = 0; i < test.length; i++) { - for (int j = 0; j < test[i].length; j++) { - System.out.print(test[i][j] + " "); + for (double[] aTest : test) { + for (int j = 0; j < aTest.length; j++) { + System.out.print(aTest[j] + " "); } System.out.println(""); } diff --git a/src/eva2/tools/ReflectPackage.java b/src/eva2/tools/ReflectPackage.java index e3ae0c44..7219c226 100644 --- a/src/eva2/tools/ReflectPackage.java +++ b/src/eva2/tools/ReflectPackage.java @@ -25,13 +25,9 @@ import java.util.jar.JarInputStream; * @author mkron */ public class ReflectPackage { - - final static boolean TRACE = false; static int missedJarsOnClassPath = 0; static boolean useFilteredClassPath = true; - // static boolean usePathMap = true; static String[] dynCP = null; -// static HashMap> pathMap = new HashMap>(); static class ClassComparator implements Comparator { @Override @@ -59,26 +55,15 @@ public class ReflectPackage { } dir = path + "/" + pckgname.replace(".", "/"); - if (TRACE) { - System.out.println(".. opening " + path); - } - directory = new File(dir); } catch (NullPointerException x) { - if (TRACE) { - System.err.println(directory.getPath() + " not found in " + path); - System.err.println("directory " + (directory.exists() ? "exists" : "doesnt exist")); - } return 0; } if (directory.exists()) { // Get the list of the files contained in the package return getClassesFromDirFltr(set, directory, pckgname, includeSubs, reqSuperCls); } else { - if (TRACE) { - System.err.println(directory.getPath() + " doesnt exist in " + path + ", dir was " + dir); - } return 0; } } catch (ClassNotFoundException e) { @@ -88,21 +73,17 @@ public class ReflectPackage { } } -// public static ArrayList getClassesFromDir(File directory, String pckgname, boolean includeSubs) { -// return getClassesFromDirFltr(directory, pckgname, includeSubs, null); -// } - public static int getClassesFromDirFltr(HashSet set, File directory, String pckgname, boolean includeSubs, Class reqSuperCls) { int cntAdded = 0; if (directory.exists()) { // Get the list of the files contained in the package String[] files = directory.list(); - for (int i = 0; i < files.length; i++) { + for (String file : files) { // we are only interested in .class files - if (files[i].endsWith(".class")) { + if (file.endsWith(".class")) { // removes the .class extension try { - Class cls = Class.forName(pckgname + '.' + files[i].substring(0, files[i].length() - 6)); + Class cls = Class.forName(pckgname + '.' + file.substring(0, file.length() - 6)); if (reqSuperCls != null) { if (reqSuperCls.isAssignableFrom(cls)) { cntAdded += addClass(set, cls); @@ -111,15 +92,15 @@ public class ReflectPackage { cntAdded += addClass(set, cls); } } catch (Exception e) { - System.err.println("ReflectPackage: Couldnt get Class from jar for " + pckgname + '.' + files[i] + ": " + e.getMessage()); + System.err.println("ReflectPackage: Couldnt get Class from jar for " + pckgname + '.' + file + ": " + e.getMessage()); } catch (Error e) { - System.err.println("ReflectPackage: Couldnt get Class from jar for " + pckgname + '.' + files[i] + ": " + e.getMessage()); + System.err.println("ReflectPackage: Couldnt get Class from jar for " + pckgname + '.' + file + ": " + e.getMessage()); } } else if (includeSubs) { // do a recursive search over subdirs - File subDir = new File(directory.getAbsolutePath() + File.separatorChar + files[i]); + File subDir = new File(directory.getAbsolutePath() + File.separatorChar + file); if (subDir.exists() && subDir.isDirectory()) { - cntAdded += getClassesFromDirFltr(set, subDir, pckgname + "." + files[i], includeSubs, reqSuperCls); + cntAdded += getClassesFromDirFltr(set, subDir, pckgname + "." + file, includeSubs, reqSuperCls); } } } @@ -136,9 +117,6 @@ public class ReflectPackage { } private static int addClass(HashSet set, Class cls) { - if (TRACE) { - System.out.println("adding class " + cls.getName()); - } if (set.contains(cls)) { System.err.println("warning, Class " + cls.getName() + " not added twice!"); return 0; @@ -150,12 +128,9 @@ public class ReflectPackage { public static ArrayList filterAssignableClasses(ArrayList classes, Class reqSuperCls) { ArrayList assClasses = new ArrayList(); - for (int i = 0; i < classes.size(); i++) { - if (reqSuperCls.isAssignableFrom(classes.get(i))) { - if (TRACE) { - System.out.println(" taking over " + classes.get(i)); - } - assClasses.add(classes.get(i)); + for (Class aClass : classes) { + if (reqSuperCls.isAssignableFrom(aClass)) { + assClasses.add(aClass); } } return assClasses; @@ -173,9 +148,6 @@ public class ReflectPackage { int cntAdded = 0; packageName = packageName.replaceAll("\\.", "/"); - if (TRACE) { - System.out.println("Jar " + jarName + " looking for " + packageName); - } try { JarInputStream jarFile = new JarInputStream (new FileInputStream(jarName)); @@ -183,7 +155,6 @@ public class ReflectPackage { while ((jarEntry = jarFile.getNextJarEntry()) != null) { String jarEntryName = jarEntry.getName(); -// if (TRACE) System.out.println("- " + jarEntry.getName()); if ((jarEntryName.startsWith(packageName)) && (jarEntryName.endsWith(".class"))) { // subpackages are hit here as well! @@ -203,25 +174,20 @@ public class ReflectPackage { } else { cntAdded += addClass(set, cls); } - } catch (Exception e) { - System.err.println("ReflectPackage: Couldnt get Class from jar for " + clsName + ": " + e.getMessage()); - } catch (Error e) { - System.err.println("ReflectPackage: Couldnt get Class from jar for " + clsName + ": " + e.getMessage()); + } catch (Exception | Error e) { + System.err.println("ReflectPackage: Couldn't get Class from jar for " + clsName + ": " + e.getMessage()); } } - -// classes.add (jarEntry.getName().replaceAll("/", "\\.")); } } } catch (IOException e) { missedJarsOnClassPath++; if (missedJarsOnClassPath == 0) { - System.err.println("Couldnt open jar from class path: " + e.getMessage()); + System.err.println("Couldn't open jar from class path: " + e.getMessage()); System.err.println("Dirty class path?"); } else if (missedJarsOnClassPath == 2) { - System.err.println("Couldnt open jar from class path more than once..."); + System.err.println("Couldn't open jar from class path more than once..."); } - //e.printStackTrace(); } return cntAdded; } @@ -230,13 +196,13 @@ public class ReflectPackage { * Collect all classes from a given package on the classpath. If includeSubs is true, * the sub-packages are listed as well. * - * @param pckg - * @param includeSubs - * @param bSort sort alphanumerically by class name + * @param pkg Package name + * @param includeSubs Whether to include sub packages + * @param bSort sort alphanumerically by class name * @return An ArrayList of Class objects contained in the package which may be empty if an error occurs. */ - public static Class[] getAllClassesInPackage(String pckg, boolean includeSubs, boolean bSort) { - return getClassesInPackageFltr(new HashSet(), pckg, includeSubs, bSort, null); + public static Class[] getAllClassesInPackage(String pkg, boolean includeSubs, boolean bSort) { + return getClassesInPackageFltr(new HashSet(), pkg, includeSubs, bSort, null); } /** @@ -244,14 +210,11 @@ public class ReflectPackage { * as superclass or superinterface. If includeSubs is true, * the sub-packages are listed as well. * - * @param pckg + * @param pkg * @return - * @see Class.assignableFromClass(Class cls) */ - public static Class[] getClassesInPackageFltr(HashSet set, String pckg, boolean includeSubs, boolean bSort, Class reqSuperCls) { - String classPath = null; + public static Class[] getClassesInPackageFltr(HashSet set, String pkg, boolean includeSubs, boolean bSort, Class reqSuperCls) { if (!useFilteredClassPath || (dynCP == null)) { - classPath = System.getProperty("java.class.path", "."); if (useFilteredClassPath) { try { dynCP = getValidCPArray(); @@ -263,20 +226,11 @@ public class ReflectPackage { } } - if (TRACE) { - System.out.println("classpath is " + classPath); - } - for (int i = 0; i < dynCP.length; i++) { - if (TRACE) { - System.out.println("reading element " + dynCP[i]); - } - if (dynCP[i].endsWith(".jar")) { - getClassesFromJarFltr(set, dynCP[i], pckg, includeSubs, reqSuperCls); + for (String aDynCP : dynCP) { + if (aDynCP.endsWith(".jar")) { + getClassesFromJarFltr(set, aDynCP, pkg, includeSubs, reqSuperCls); } else { - if (TRACE) { - System.out.println("reading from files: " + dynCP[i] + " " + pckg); - } - getClassesFromFilesFltr(set, dynCP[i], pckg, includeSubs, reqSuperCls); + getClassesFromFilesFltr(set, aDynCP, pkg, includeSubs, reqSuperCls); } } Object[] clsArr = set.toArray(); @@ -298,9 +252,6 @@ public class ReflectPackage { public static String getResourcePathFromCP(String res) { String[] cpEntries = getClassPathElements(); URL url = ClassLoader.getSystemResource(res); - if (TRACE) { - System.out.println(res + ((url == null) ? " not" : " was") + " found by classloader."); - } if (url != null) { File f; try { @@ -319,15 +270,9 @@ public class ReflectPackage { fNameSep = System.getProperty("file.separator") + res; } - for (int i = 0; i < cpEntries.length; i++) { - if (!cpEntries[i].endsWith(".jar")) { // its a fs directory (hopefully) - if (TRACE) { - System.out.println("reading element " + cpEntries[i]); - } - f = new File(cpEntries[i] + fNameSep); - if (TRACE) { - System.out.println(res + ((!f.exists()) ? " not" : " was") + " found in " + cpEntries[i]); - } + for (String cpEntry : cpEntries) { + if (!cpEntry.endsWith(".jar")) { // its a fs directory (hopefully) + f = new File(cpEntry + fNameSep); if (f.exists()) { return f.getAbsolutePath(); } @@ -345,9 +290,6 @@ public class ReflectPackage { public static InputStream getResourceStreamFromCP(String res) { InputStream in = BasicResourceLoader.instance().getStreamFromResourceLocation(res); - if (TRACE) { - System.out.println(res + ((in == null) ? " not" : " was") + " found by classloader."); - } if (in != null) { return in; } @@ -362,15 +304,9 @@ public class ReflectPackage { fNameSep = System.getProperty("file.separator") + res; } - for (int i = 0; i < cpEntries.length; i++) { - if (!cpEntries[i].endsWith(".jar")) { // its a fs directory (hopefully) - if (TRACE) { - System.out.println("reading element " + cpEntries[i]); - } - f = new File(cpEntries[i] + fNameSep); - if (TRACE) { - System.out.println(res + ((!f.exists()) ? " not" : " was") + " found in " + cpEntries[i]); - } + for (String cpEntry : cpEntries) { + if (!cpEntry.endsWith(".jar")) { // its a fs directory (hopefully) + f = new File(cpEntry + fNameSep); if (f.exists()) { try { return new FileInputStream(f); @@ -387,12 +323,10 @@ public class ReflectPackage { String[] pathElements = getClassPathElements(); File f; ArrayList valids = new ArrayList(pathElements.length); - for (int i = 0; i < pathElements.length; i++) { -// System.err.println(pathElements[i]); - f = new File(pathElements[i]); -// if (f.canRead()) {valids.add(pathElements[i]);} + for (String pathElement : pathElements) { + f = new File(pathElement); if (f.exists() && f.canRead()) { - valids.add(pathElements[i]); + valids.add(pathElement); } } return valids; @@ -400,7 +334,6 @@ public class ReflectPackage { public static String[] getValidCPArray() { ArrayList valids = getValidCPEntries(); -// vp = valids.toArray(dynCP); // this causes Matlab to crash meanly. String[] vp = new String[valids.size()]; for (int i = 0; i < valids.size(); i++) { vp[i] = valids.get(i); @@ -416,9 +349,6 @@ public class ReflectPackage { * @return */ public static Class[] getAssignableClassesInPackage(String pckg, Class reqSuperCls, boolean includeSubs, boolean bSort) { - if (TRACE) { - System.out.println("requesting classes assignable from " + reqSuperCls.getName()); - } return getClassesInPackageFltr(new HashSet(), pckg, includeSubs, bSort, reqSuperCls); } @@ -426,8 +356,9 @@ public class ReflectPackage { * Retrieve assignable classes of the given package from classpath given by full class and package String, * such as eva2.problems.AbstractOptimizationProblem. * - * @param pckg String denoting the package - * @param reqSuperCls + * @param pckgClassName String denoting the package + * @param includeSubs + * @param bSort * @return */ public static Class[] getAssignableClasses(String pckgClassName, boolean includeSubs, boolean bSort) { @@ -450,13 +381,8 @@ public class ReflectPackage { public static void main(String[] args) { ClassLoader cld = Thread.currentThread().getContextClassLoader(); - System.out.println("1: " + cld.getResource("/eva2/server")); - System.out.println("2: " + cld.getResource("eva2/server")); -// BasicResourceLoader rld = BasicResourceLoader.instance(); -// byte[] b = rld.getBytesFromResourceLocation("images/Sub24.gif"); -// System.out.println((b == null) ? "null" : b.toString()); -// b = rld.getBytesFromResourceLocation("src/eva2/client/SplashScreen.java"); -// System.out.println((b == null) ? "null" : b.toString()); + System.out.println("1: " + cld.getResource("/eva2/optimization")); + System.out.println("2: " + cld.getResource("eva2/optimization")); HashSet h = new HashSet(20); @@ -466,27 +392,10 @@ public class ReflectPackage { for (String string : h) { System.out.println("+ " + string); } - -// String[] pathElements = getClassPathElements(); -// for (int i=0; i> paramValuePairs) { Object o = getInstance(clsName, args); @@ -555,8 +456,6 @@ public class ReflectPackage { if (!succ) { System.err.println("Error, unable to set " + nameVal.head + " to " + nameVal.tail + " in object " + o); return null; - } else if (TRACE) { - System.out.println("Successfully set " + nameVal.head + " to " + nameVal.tail + " in object " + o); } } } diff --git a/src/eva2/tools/chart2d/DArea.java b/src/eva2/tools/chart2d/DArea.java index 1c0b3a11..b54daaa7 100644 --- a/src/eva2/tools/chart2d/DArea.java +++ b/src/eva2/tools/chart2d/DArea.java @@ -29,16 +29,13 @@ public class DArea extends JComponent implements DParent, Printable { /** * the default minimal rectangle which is shown */ - public static final DRectangle DEFAULT_MIN_RECT = new DRectangle(-1, -1, 2, - 2); + public static final DRectangle DEFAULT_MIN_RECT = new DRectangle(-1, -1, 2, 2); /** * */ private static final long serialVersionUID = 1461387400381365146L; - private static final boolean TRACE = false; - private boolean auto_focus = false, auto_grid = false, grid_to_front = false; @@ -358,9 +355,6 @@ public class DArea extends JComponent implements DParent, Printable { */ @Override public void paint(Graphics g) { - if (TRACE) { - System.out.println("DArea.paint(Graphics)"); - } if (auto_focus) { container.restore(); visible_rect = (DRectangle) container.getRectangle().clone(); @@ -388,9 +382,6 @@ public class DArea extends JComponent implements DParent, Printable { * auto_grid option */ private void paintGrid(DMeasures m) { - if (TRACE) { - System.out.println("DArea.paintGrid(DMeasures)"); - } grid.rectangle = getDRectangle(); if (auto_grid) { Border b = getBorder(); @@ -417,9 +408,6 @@ public class DArea extends JComponent implements DParent, Printable { * @param m the measures of the area */ private void paintGrid(ScaledBorder sb, DMeasures m) { - if (TRACE) { - System.out.println("DArea.paintGrid(ScaledBorder, DMeasures)"); - } Dimension d = getSize(); FontMetrics fm = m.getGraphics().getFontMetrics(); grid.setDistances(sb.getSrcdX(fm, d), sb.getSrcdY(fm, d)); @@ -479,9 +467,6 @@ public class DArea extends JComponent implements DParent, Printable { */ @Override public int print(Graphics g, PageFormat pf, int pi) { - if (TRACE) { - System.out.println("DArea.print(...)"); - } if (pi > 0) { return Printable.NO_SUCH_PAGE; } @@ -553,9 +538,6 @@ public class DArea extends JComponent implements DParent, Printable { */ @Override public void repaint(DRectangle r) { - if (TRACE) { - System.out.println("DArea.repaint(DRectangle)" + r); - } if (r == null) { throw new IllegalArgumentException( "Cannot repaint a null DRectangle"); @@ -580,9 +562,6 @@ public class DArea extends JComponent implements DParent, Printable { @Override public void restoreBorder() { dborder = container.getDBorder(); - if (TRACE) { - System.out.println("DArea.restoreBorder -> " + dborder); - } } /** @@ -659,9 +638,7 @@ public class DArea extends JComponent implements DParent, Printable { * @param aFlag visible or not */ public void setGridVisible(boolean aFlag) { - if (TRACE) { - System.out.println("DArea.setGridVisisble: " + aFlag); - } + grid.rectangle = getDRectangle(); grid.setVisible(aFlag); } @@ -784,9 +761,6 @@ public class DArea extends JComponent implements DParent, Printable { * @param rect the visible DRectangle in DArea coordinates */ public void setVisibleRectangle(DRectangle rect) { - if (TRACE) { - System.out.println("DArea.setVisibleRectangle(DRectangle)"); - } if (rect.isEmpty()) { throw new IllegalArgumentException( "You should never try to set an empty rectangle\n"