Remove last traces of the TRACE variable.

This commit is contained in:
Fabian Becker 2014-10-19 14:19:54 +02:00
parent d9cc88e60d
commit 7d6a9faf66
45 changed files with 127 additions and 1211 deletions

View File

@ -22,7 +22,6 @@ public class EvATreeSelectionListener implements TreeSelectionListener, Property
private PropertyEditor goe = null; private PropertyEditor goe = null;
private EvATreeNode root = null; private EvATreeNode root = null;
private JTree jtree = 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 * 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 @Override
public void valueChanged(TreeSelectionEvent e) { public void valueChanged(TreeSelectionEvent e) {
if (TRACE) {
System.out.println("valueChanged to " + BeanInspector.toString(e.getPath()));
}
TreePath tp = 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(); EvATreeNode leafNode = (EvATreeNode) tp.getLastPathComponent();
// goe.setValue(leafNode.getUserObject());
Component editComp = goe.getCustomEditor(); Component editComp = goe.getCustomEditor();
if (editComp instanceof OptimizationEditorPanel) { if (editComp instanceof OptimizationEditorPanel) {
// update the object in the main OptimizationEditorPanel // update the object in the main OptimizationEditorPanel
@ -69,9 +60,6 @@ public class EvATreeSelectionListener implements TreeSelectionListener, Property
@Override @Override
public void propertyChange(PropertyChangeEvent evt) { public void propertyChange(PropertyChangeEvent evt) {
if (TRACE) {
System.out.println("EvATreeNode received change event " + evt);
}
root.setObject(evt.getNewValue(), true); root.setObject(evt.getNewValue(), true);
if (jtree != null) { if (jtree != null) {
jtree.setModel(new DefaultTreeModel(root)); jtree.setModel(new DefaultTreeModel(root));

View File

@ -11,8 +11,6 @@ import java.io.Serializable;
* *
*/ */
public class PropertySheetPanelStat extends JPanel implements Serializable { public class PropertySheetPanelStat extends JPanel implements Serializable {
public final static boolean TRACE = false;
private Object[] values; private Object[] values;
private JCheckBoxFlag[] views; private JCheckBoxFlag[] views;
private JLabel[] labels; private JLabel[] labels;
@ -38,8 +36,6 @@ public class PropertySheetPanelStat extends JPanel implements Serializable {
setLayout(gbLayout); setLayout(gbLayout);
setVisible(false); setVisible(false);
int rowHeight = 12;
values = new Object[flag.length]; values = new Object[flag.length];
views = new JCheckBoxFlag[flag.length]; views = new JCheckBoxFlag[flag.length];
labels = new JLabel[names.length]; labels = new JLabel[names.length];

View File

@ -426,7 +426,6 @@ public class FunctionArea extends DArea implements Serializable {
minY = Math.min(minY, pSet.getMinYVal()); minY = Math.min(minY, pSet.getMinYVal());
} }
} }
// if (TRACE) System.out.println("min is " + minY);
return (minY > 0); return (minY > 0);
} }

View File

@ -25,12 +25,10 @@ public class TopoPlot extends Plot {
*/ */
public TopoPlot(String PlotName, String xname, String yname) { public TopoPlot(String PlotName, String xname, String yname) {
super(PlotName, xname, yname, true); 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) { public TopoPlot(String PlotName, String xname, String yname, double[] a, double[] b) {
super(PlotName, xname, yname, a, 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 deltaY = sizeXY[1] / gridy;
double maxDeriv = 0; double maxDeriv = 0;
double[] pos = new double[2]; 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; double fitRange = 0, max = -Double.MAX_VALUE, min = Double.MAX_VALUE, tmp;
for (int x = 0; x < gridx; x++) { for (int x = 0; x < gridx; x++) {
for (int y = 0; y < gridy; y++) { for (int y = 0; y < gridy; y++) {
pos[0] = border[0][0] + x * deltaX; pos[0] = border[0][0] + x * deltaX;
pos[1] = border[1][0] + y * deltaY; pos[1] = border[1][0] + y * deltaY;
tmp = (float) (problem.functionValue(pos)); tmp = (float) (problem.functionValue(pos));
if (TRACEMETH) {
System.out.println(pos[0] + " " + pos[1] + " " + tmp);
}
if (tmp < min) { if (tmp < min) {
min = tmp; min = tmp;
} }

View File

@ -22,7 +22,6 @@ public abstract class AbstractGPNode implements InterfaceProgram, java.io.Serial
protected AbstractGPNode parentNode; protected AbstractGPNode parentNode;
protected AbstractGPNode[] nodes = new AbstractGPNode[0]; protected AbstractGPNode[] nodes = new AbstractGPNode[0];
protected int depth = 0; protected int depth = 0;
private static final boolean TRACE = false;
/** /**
* This method allows you to clone the Nodes * 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)); System.err.println("String has ambiguous prefix: " + str + " -- " + BeanInspector.toString(matchSet));
} else { // exactly one match: } else { // exactly one match:
AbstractGPNode currentNode = (AbstractGPNode) matchSet.get(0).clone(); AbstractGPNode currentNode = (AbstractGPNode) matchSet.get(0).clone();
if (TRACE) {
System.out.println("Found match: " + currentNode.getOpIdentifier() + "/" + currentNode.getArity());
}
int cutFront = currentNode.getOpIdentifier().length(); int cutFront = currentNode.getOpIdentifier().length();
String restStr; String restStr;
if (currentNode.getArity() == 0) { if (currentNode.getArity() == 0) {
@ -163,9 +159,6 @@ public abstract class AbstractGPNode implements InterfaceProgram, java.io.Serial
e.printStackTrace(); e.printStackTrace();
} }
} }
if (TRACE) {
System.out.println("read " + currentNode.getName() + ", rest: " + restStr);
}
return new Pair<AbstractGPNode, String>(currentNode, restStr); return new Pair<AbstractGPNode, String>(currentNode, restStr);
} }
} }

View File

@ -261,7 +261,7 @@ public class ParetoFrontView2D extends JPanel implements InterfaceParetoFrontVie
InterfaceOptimizationObjective[] tmpObj = ((InterfaceMultiObjectiveDeNovoProblem) this.moccoViewer.moccoStandalone.state.currentProblem).getProblemObjectives(); InterfaceOptimizationObjective[] tmpObj = ((InterfaceMultiObjectiveDeNovoProblem) this.moccoViewer.moccoStandalone.state.currentProblem).getProblemObjectives();
fitness = new double[tmpObj.length]; fitness = new double[tmpObj.length];
for (int k = 0; k < tmpObj.length; k++) { 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]); point = new DPoint(fitness[indexX], fitness[indexY]);

View File

@ -192,8 +192,7 @@ public class Processor extends Thread implements InterfaceProcessor, InterfacePo
LOGGER.log(Level.SEVERE, errMsg, e); LOGGER.log(Level.SEVERE, errMsg, e);
try { try {
JOptionPane.showMessageDialog(null, StringTools.wrapLine(errMsg, 60, 0.2), "Error in Optimization", JOptionPane.ERROR_MESSAGE); JOptionPane.showMessageDialog(null, StringTools.wrapLine(errMsg, 60, 0.2), "Error in Optimization", JOptionPane.ERROR_MESSAGE);
} catch (Exception ex) { } catch (Exception | Error ex) {
} catch (Error error) {
} }
//statistics.stopOptimizationPerformed(false); //statistics.stopOptimizationPerformed(false);
setOptimizationRunning(false); // normal finish setOptimizationRunning(false); // normal finish

View File

@ -43,8 +43,6 @@ public class ClusteringNearestBetter implements InterfaceClustering, Serializabl
private static final String initializedForKey = "initializedClustNearestBetterOnHash"; private static final String initializedForKey = "initializedClustNearestBetterOnHash";
private static final String initializedRefData = "initializedClustNearestBetterData"; private static final String initializedRefData = "initializedClustNearestBetterData";
private static boolean TRACE = false;
public ClusteringNearestBetter() { public ClusteringNearestBetter() {
} }
@ -216,9 +214,7 @@ public class ClusteringNearestBetter implements InterfaceClustering, Serializabl
} }
} }
currentMeanDistance = createClusterTreeFromSortedPop(sorted); currentMeanDistance = createClusterTreeFromSortedPop(sorted);
if (TRACE) {
pop.putData(initializedForKey, pop.hashCode());
}
pop.putData(initializedRefData, currentMeanDistance); pop.putData(initializedRefData, currentMeanDistance);
return initializedRefData; return initializedRefData;
} else { } 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 (isAdaptiveThreshold()) { // test if there was a valid initialization step
if (!getRefData(referenceSet, pop)) { if (!getRefData(referenceSet, pop)) {
currentMeanDistance = createClusterTreeFromSortedPop(sorted); currentMeanDistance = createClusterTreeFromSortedPop(sorted);
@ -304,13 +296,7 @@ public class ClusteringNearestBetter implements InterfaceClustering, Serializabl
} }
Double refDat = (Double) referenceSet.getData(initializedRefData); Double refDat = (Double) referenceSet.getData(initializedRefData);
if (refDat != null) { 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(); currentMeanDistance = refDat.doubleValue();
return true; return true;
} else { } else {
@ -362,14 +348,7 @@ public class ClusteringNearestBetter implements InterfaceClustering, Serializabl
// so add it to the cluster, mark it, and proceed recursively. // so add it to the cluster, mark it, and proceed recursively.
currentClust.add(sorted.get(children[current].get(i))); currentClust.add(sorted.get(children[current].get(i)));
clustered[children[current].get(i)] = true; clustered[children[current].get(i)] = true;
if (TRACE) {
System.out.println("Assigned " + current);
}
addChildren(children[current].get(i), clustered, sorted, currentClust); addChildren(children[current].get(i), clustered, sorted, currentClust);
} else {
if (TRACE) {
System.out.println("Not assigned " + current);
}
} }
} }
} else { } else {

View File

@ -18,7 +18,7 @@ public abstract class AbstractConstraint implements InterfaceDoubleConstraint, S
// private transient GPFunctionProblem func = null; // private transient GPFunctionProblem func = null;
protected ConstraintRelationEnum relation = ConstraintRelationEnum.lessEqZero; protected ConstraintRelationEnum relation = ConstraintRelationEnum.lessEqZero;
protected ConstraintHandlingEnum handling = ConstraintHandlingEnum.specificTag; protected ConstraintHandlingEnum handling = ConstraintHandlingEnum.specificTag;
protected static boolean TRACE = false;
protected double equalityEpsilon = 0.0001; // threshold below which equality constraints are seen as satisfied protected double equalityEpsilon = 0.0001; // threshold below which equality constraints are seen as satisfied
private AbstractEAIndividual currentIndy = null; private AbstractEAIndividual currentIndy = null;
@ -31,11 +31,9 @@ public abstract class AbstractConstraint implements InterfaceDoubleConstraint, S
relation = ConstraintRelationEnum.lessEqZero; relation = ConstraintRelationEnum.lessEqZero;
penaltyFactor = 1.; penaltyFactor = 1.;
paramCtrl = new ParameterControlManager(new NoParamAdaption()); paramCtrl = new ParameterControlManager(new NoParamAdaption());
// penaltyFactAdaption = new NoParamAdaption();
} }
public AbstractConstraint(AbstractConstraint o) { public AbstractConstraint(AbstractConstraint o) {
// penaltyFactAdaption = (ParamAdaption)o.penaltyFactAdaption.clone();
paramCtrl = new ParameterControlManager(o.paramCtrl); paramCtrl = new ParameterControlManager(o.paramCtrl);
penaltyFactor = o.penaltyFactor; penaltyFactor = o.penaltyFactor;
relation = o.relation; relation = o.relation;

View File

@ -41,15 +41,10 @@ public class ConstraintCollection extends AbstractConstraint {
@Override @Override
protected double getRawViolationValue(double[] indyX) { protected double getRawViolationValue(double[] indyX) {
double v, sum = 0; double v, sum = 0;
if (TRACE) {
System.out.println("Viol (pen " + getPenaltyFactor() + ")");
}
for (AbstractConstraint constr : constraintArray) { for (AbstractConstraint constr : constraintArray) {
v = constr.getViolation(indyX); v = constr.getViolation(indyX);
sum += v; sum += v;
if (TRACE) {
System.out.println(constr.getClass().getSimpleName() + " " + v);
}
} }
return sum; return sum;
} }

View File

@ -62,10 +62,6 @@ public class GenericConstraint extends AbstractConstraint implements InterfaceDo
if (constraintProgram == null) { if (constraintProgram == null) {
System.err.println("Error: invalid expression: " + constraintString); 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 { } else {
return 0.; return 0.;
} }
// case linearLessEqZero:
// return getViolation(evalLinearConstr(indy));
} }
EVAERROR.errorMsgOnce("Error: unknown relation for GenericConstraint!"); EVAERROR.errorMsgOnce("Error: unknown relation for GenericConstraint!");
return 0.; return 0.;
@ -111,9 +105,6 @@ public class GenericConstraint extends AbstractConstraint implements InterfaceDo
public void setConstraintString(String constraintString) { public void setConstraintString(String constraintString) {
this.constraintString = constraintString; this.constraintString = constraintString;
constraintProgram = null; constraintProgram = null;
if (TRACE) {
System.out.println(" NEW CONSTRAINT STRING SET! in " + this);
}
} }
public String getName() { public String getName() {

View File

@ -13,15 +13,14 @@ import java.util.BitSet;
/** /**
* The famous n-point crossover operator on a binary and integer genotype. Genotypes of * The famous n-point crossover operator on a binary and integer genotype. Genotypes of
* parent individuals are recombined by exchanging subsegments within randomly * parent individuals are recombined by exchanging sub-segments within randomly
* selected points. Therefore, far-away allels (larger GA schemas) are more likely to be split * selected points. Therefore, far-away alleles (larger GA schemas) are more likely to be split
* between individuals. * between individuals.
* *
* @author mkron, streiche * @author mkron, streiche
*/ */
public class CrossoverGAGINPoint implements InterfaceCrossover, java.io.Serializable { public class CrossoverGAGINPoint implements InterfaceCrossover, java.io.Serializable {
private int numberOfCrossovers = 3; private int numberOfCrossovers = 3;
private static boolean TRACE = false;
public CrossoverGAGINPoint() { public CrossoverGAGINPoint() {
@ -71,7 +70,6 @@ public class CrossoverGAGINPoint implements InterfaceCrossover, java.io.Serializ
if (individual instanceof InterfaceGAIndividual || (individual instanceof InterfaceGIIndividual)) { if (individual instanceof InterfaceGAIndividual || (individual instanceof InterfaceGIIndividual)) {
int length = getGenotypeLength(individual); int length = getGenotypeLength(individual);
// Object[][] tmpGenotypes = new Object[2][partners.size()+1];
Object[] origGenotypes = new Object[partners.size() + 1]; Object[] origGenotypes = new Object[partners.size() + 1];
Object[] newGenotypes = 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]); newGenotypes[i + 1] = getGenotype(result[i + 1]);
length = Math.max(length, getGenotypeLength(partners.getEAIndividual(i))); 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 mixer = RNG.randomInt(0, partners.size()); // partner index with which to exchange genes
int[] crossoverPoints = getCrossoverPoints(length, numberOfCrossovers); 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 i = 0; i < length; i++) { // loop positions
for (int j = 0; j < this.numberOfCrossovers; j++) { for (int j = 0; j < this.numberOfCrossovers; j++) {
if (i == crossoverPoints[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++) { for (int i = 0; i < result.length; i++) {
writeBack(result[i], newGenotypes[i]); writeBack(result[i], newGenotypes[i]);
} }
if (TRACE) {
System.out.println("After CO: " + BeanInspector.toString(newGenotypes));
}
} }
return result; return result;
} }

View File

@ -10,11 +10,6 @@ import eva2.problems.InterfaceOptimizationProblem;
import eva2.tools.math.RNG; 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 { 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 static final long serialVersionUID = 8900427365914281930L;
private InterfaceOptimizationProblem optimizationProblem; private InterfaceOptimizationProblem optimizationProblem;
private boolean maintainMaxDepth = true; private boolean maintainMaxDepth = true;
private static final boolean TRACE = false;
public CrossoverGPDefault() { public CrossoverGPDefault() {
} }
@ -60,11 +54,6 @@ public class CrossoverGPDefault implements InterfaceCrossover, java.io.Serializa
for (int i = 0; i < partners.size(); i++) { for (int i = 0; i < partners.size(); i++) {
result[i + 1] = (AbstractEAIndividual) ((AbstractEAIndividual) partners.get(i)).clone(); 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) { if (partners.size() == 0) {
return result; return result;
} }
@ -94,10 +83,6 @@ public class CrossoverGPDefault implements InterfaceCrossover, java.io.Serializa
selNodeOther = ((InterfaceGPIndividual) result[1]).getPGenotype()[t].getRandomLeaf(); 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; AbstractGPNode selNodeThisParent, selNodeOtherParent;
selNodeThisParent = selNodeThis.getParent(); 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 //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++) { for (AbstractEAIndividual aResult : result) {
((GPIndividualProgramData) result[i]).checkDepth(); ((GPIndividualProgramData) aResult).checkDepth();
result[i].getMutationOperator().crossoverOnStrategyParameters(indy1, partners); aResult.getMutationOperator().crossoverOnStrategyParameters(indy1, partners);
}
if (TRACE) {
for (int i = 0; i < result.length; i++) {
System.out.println("After Crossover: " + result[i].getStringRepresentation());
}
} }
return result; 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. * are actually the same.
* *
* @param crossover The other crossover operator * @param crossover The other crossover operator

View File

@ -116,8 +116,6 @@ class CMAParamSet implements InterfacePopulationChangedEventListener, Serializab
params.range = range; params.range = range;
int dim = params.range.length; 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]; params.eigenvalues = new double[dim];
Arrays.fill(params.eigenvalues, 1.); Arrays.fill(params.eigenvalues, 1.);
params.meanX = new double[dim]; params.meanX = new double[dim];
@ -219,9 +217,7 @@ class CMAParamSet implements InterfacePopulationChangedEventListener, Serializab
public void registerPopulationStateChanged(Object source, String name) { public void registerPopulationStateChanged(Object source, String name) {
if (name.equals(Population.POPULATION_INITIALIZED)) { if (name.equals(Population.POPULATION_INITIALIZED)) {
Population pop = (Population) source; Population pop = (Population) source;
if (MutateESRankMuCMA.TRACE_1) {
System.out.println("Event " + name + " arrived in CMAParamSet!!!");
}
CMAParamSet params = (CMAParamSet) (pop.getData(MutateESRankMuCMA.cmaParamsKey)); CMAParamSet params = (CMAParamSet) (pop.getData(MutateESRankMuCMA.cmaParamsKey));
int mu; int mu;
if (pop.hasData(EvolutionStrategies.esMuParam)) { if (pop.hasData(EvolutionStrategies.esMuParam)) {

View File

@ -30,7 +30,6 @@ public class MutateESCorrVector implements InterfaceMutation, java.io.Serializab
protected double rotationDev = 15.; protected double rotationDev = 15.;
protected boolean checkConstraints = true; protected boolean checkConstraints = true;
public static final String vectorKey = "MutateESCorrVectorVector"; public static final String vectorKey = "MutateESCorrVectorVector";
public static final boolean TRACE = false;
public MutateESCorrVector() { public MutateESCorrVector() {
} }
@ -128,7 +127,6 @@ public class MutateESCorrVector implements InterfaceMutation, java.io.Serializab
*/ */
@Override @Override
public void mutate(AbstractEAIndividual individual) { public void mutate(AbstractEAIndividual individual) {
// if (TRACE) System.out.println("Before Mutate: " + AbstractEAIndividual.getDefaultDataString(individual));
if (individual instanceof InterfaceESIndividual) { if (individual instanceof InterfaceESIndividual) {
double[] genes = ((InterfaceESIndividual) individual).getDGenotype(); double[] genes = ((InterfaceESIndividual) individual).getDGenotype();
double[][] range = ((InterfaceESIndividual) individual).getDoubleRange(); 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 // mutate the velocity vector and write it back
if ((scalingDev > 0) || (rotationDev > 0)) { 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.); double rotateRad = rotationDev * (Math.PI / 360.) * RNG.gaussianDouble(1.);
// rotate with a gaussian distribution of deviation rotationDeg // rotate with a gaussian distribution of deviation rotationDeg
Mathematics.rotateAllAxes(vel, rotateRad, false); // rotate 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 Mathematics.svMult(rScale, vel, vel); // mutate speed
individual.putData(vectorKey, vel); 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 // add velocity to the individual
@ -178,7 +167,6 @@ public class MutateESCorrVector implements InterfaceMutation, java.io.Serializab
((InterfaceESIndividual) individual).setDGenotype(genes); ((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) { public void crossoverOnStrategyParameters(AbstractEAIndividual indy1, Population partners) {
ArrayList<Double> tmpList = new ArrayList<Double>(); ArrayList<Double> tmpList = new ArrayList<Double>();
if (indy1.getMutationOperator() instanceof MutateESCorrVector) { 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++) { for (Object partner : partners) {
if (((AbstractEAIndividual) partners.get(i)).getMutationOperator() instanceof MutateESCorrVector) { if (((AbstractEAIndividual) partner).getMutationOperator() instanceof MutateESCorrVector) {
tmpList.add(new Double(((MutateESCorrVector) ((AbstractEAIndividual) partners.get(i)).getMutationOperator()).scalingDev)); tmpList.add(((MutateESCorrVector) ((AbstractEAIndividual) partner).getMutationOperator()).scalingDev);
} }
} }
double[] list = new double[tmpList.size()]; double[] list = new double[tmpList.size()];
for (int i = 0; i < tmpList.size(); i++) { for (int i = 0; i < tmpList.size(); i++) {
list[i] = tmpList.get(i).doubleValue(); list[i] = tmpList.get(i);
} }
if (list.length <= 1) { if (list.length <= 1) {
return; return;
} }
// discreete mutation for step size // discrete mutation for step size
this.scalingDev = list[RNG.randomInt(0, list.length - 1)]; this.scalingDev = list[RNG.randomInt(0, list.length - 1)];
} }

View File

@ -10,11 +10,6 @@ import eva2.tools.math.Mathematics;
import eva2.tools.math.RNG; 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 { public class MutateESCovarianceMatrixAdaption implements InterfaceMutation, java.io.Serializable {

View File

@ -49,9 +49,6 @@ public class MutateESRankMuCMA implements InterfaceAdaptOperatorGenerational, In
private boolean checkRange = true; private boolean checkRange = true;
public static final String cmaParamsKey = "RankMuCMAParameters"; 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() { public MutateESRankMuCMA() {
} }
@ -67,7 +64,6 @@ public class MutateESRankMuCMA implements InterfaceAdaptOperatorGenerational, In
@Override @Override
public Object clone() { public Object clone() {
// if (TRACE) System.out.println("WCMA clone");
return new MutateESRankMuCMA(this); return new MutateESRankMuCMA(this);
} }
@ -162,26 +158,13 @@ public class MutateESRankMuCMA implements InterfaceAdaptOperatorGenerational, In
return; 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); double[] newMeanX = calcMeanX(params.weights, selectedSorted);
if (TRACE_1) {
System.out.println("newMeanX: " + BeanInspector.toString(newMeanX));
}
int dim = params.meanX.length; int dim = params.meanX.length;
double[] BDz = new double[dim]; double[] BDz = new double[dim];
for (int i = 0; i < dim; i++) { /* calculate xmean and BDz~N(0,C) */ for (int i = 0; i < dim; i++) { /* calculate xmean and BDz~N(0,C) */
// Eq. 4 from HK04, most right term // Eq. 4 from HK04, most right term
BDz[i] = Math.sqrt(CMAParamSet.getMuEff(params.weights, mu)) * (newMeanX[i] - params.meanX[i]) / getSigma(params, i); 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[] newPathS = params.pathS.clone();
double[] newPathC = params.pathC.clone(); double[] newPathC = params.pathC.clone();
@ -233,16 +216,6 @@ public class MutateESRankMuCMA implements InterfaceAdaptOperatorGenerational, In
checkValidDouble(newPathC[i]); 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) { if (params.meanX == null) {
params.meanX = newMeanX; params.meanX = newMeanX;
} }
@ -250,10 +223,6 @@ public class MutateESRankMuCMA implements InterfaceAdaptOperatorGenerational, In
updateCov(params, newPathC, newMeanX, hsig, mu, selectedSorted); updateCov(params, newPathC, newMeanX, hsig, mu, selectedSorted);
updateBD(params); updateBD(params);
if (TRACE_2) {
System.out.println("Aft: C is " + params.mC.toString());
}
/* update of sigma */ /* update of sigma */
double sigFact = Math.exp(((psNorm / expRandStepLen) - 1) * params.c_sig double sigFact = Math.exp(((psNorm / expRandStepLen) - 1) * params.c_sig
/ params.d_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); 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 // take over data
params.meanX = newMeanX; params.meanX = newMeanX;
params.pathC = newPathC; params.pathC = newPathC;
@ -284,7 +247,6 @@ public class MutateESRankMuCMA implements InterfaceAdaptOperatorGenerational, In
lastParams = (CMAParamSet) params.clone(); lastParams = (CMAParamSet) params.clone();
oldGen.putData(cmaParamsKey, params); oldGen.putData(cmaParamsKey, params);
selectedP.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)) { if (iterations > 1 && (selected.size() > 1)) {
// selected pop is sorted // selected pop is sorted
if (nearlySame(selected.getEAIndividual(0).getFitness(), selected.getEAIndividual(selected.size() - 1).getFitness())) { 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); params.sigma *= Math.exp(0.2 + params.c_sig / params.d_sig);
// sigma=0.1;
} }
} }
if (!checkValidDouble(params.sigma)) { if (!checkValidDouble(params.sigma)) {
System.err.println("Error, unstable sigma!"); System.err.println("Error, unstable sigma!");
corrected = false; corrected = false;
// params.sigma=params.firstSigma; // MK TODO
// System.err.println(
} }
/* Align (renormalize) scale C (and consequently sigma) */ /* Align (renormalize) scale C (and consequently sigma) */
@ -347,7 +303,6 @@ public class MutateESRankMuCMA implements InterfaceAdaptOperatorGenerational, In
} }
if (fac != 1.) { if (fac != 1.) {
// System.err.println("Scaling by " + fac);
params.sigma /= fac; params.sigma /= fac;
for (int i = 0; i < params.meanX.length; ++i) { for (int i = 0; i < params.meanX.length; ++i) {
params.pathC[i] *= fac; params.pathC[i] *= fac;
@ -571,26 +526,6 @@ public class MutateESRankMuCMA implements InterfaceAdaptOperatorGenerational, In
@Override @Override
public void init(AbstractEAIndividual individual, public void init(AbstractEAIndividual individual,
InterfaceOptimizationProblem opt) { 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(); double[][] range = ((InterfaceDataTypeDouble) individual).getDoubleRange();
int dim = range.length; int dim = range.length;
c_c = (4. / (dim + 4)); c_c = (4. / (dim + 4));
@ -600,21 +535,15 @@ public class MutateESRankMuCMA implements InterfaceAdaptOperatorGenerational, In
@Override @Override
public void mutate(AbstractEAIndividual individual) { public void mutate(AbstractEAIndividual individual) {
// if (!firstAdaptionDone) {
// if (TRACE) System.out.println("No mutation before first adaptions step");
// return;
// }
if (individual instanceof InterfaceDataTypeDouble) { if (individual instanceof InterfaceDataTypeDouble) {
double[] x = ((InterfaceDataTypeDouble) individual).getDoubleData(); double[] x = ((InterfaceDataTypeDouble) individual).getDoubleData();
// if (TRACE) System.out.println("WCMA mutate, bef: " + BeanInspector.toString(x));
double[][] range = ((InterfaceDataTypeDouble) individual).getDoubleRange(); double[][] range = ((InterfaceDataTypeDouble) individual).getDoubleRange();
// this is a critical point: where do the CMA parameters for this individual's mutation come from? // 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, // for GA and ES we can expect that selection occurred directly before the mutation cycle,
// so we take the parameter set from the last adpation step. // so we take the parameter set from the last adaption step.
((InterfaceDataTypeDouble) individual).setDoubleGenotype(mutate(lastParams, x, range, 0)); ((InterfaceDataTypeDouble) individual).setDoubleGenotype(mutate(lastParams, x, range, 0));
// if (TRACE) System.out.println("WCMA mutate, aft: " + BeanInspector.toString(x));
} else { } else {
System.err.println("Error, expecting InterfaceDataTypeDouble"); System.err.println("Error, expecting InterfaceDataTypeDouble");
} }
@ -626,7 +555,6 @@ public class MutateESRankMuCMA implements InterfaceAdaptOperatorGenerational, In
System.err.println("Error in MutateESRankMuCMA.mutate !"); System.err.println("Error in MutateESRankMuCMA.mutate !");
Mathematics.projectToRange(params.meanX, range); Mathematics.projectToRange(params.meanX, range);
} }
// System.out.println("--- In mutate!");
if (params != null && (params.firstAdaptionDone)) { if (params != null && (params.firstAdaptionDone)) {
double[] sampl = new double[dim]; // generate scaled random vector (D * z) double[] sampl = new double[dim]; // generate scaled random vector (D * z)
for (int i = 0; i < dim; ++i) { for (int i = 0; i < dim; ++i) {
@ -677,9 +605,6 @@ public class MutateESRankMuCMA implements InterfaceAdaptOperatorGenerational, In
if (!Mathematics.isInRange(params.meanX, range)) { if (!Mathematics.isInRange(params.meanX, range)) {
System.err.println("Error B in MutateESRankMuCMA.mutate !"); System.err.println("Error B in MutateESRankMuCMA.mutate !");
} }
if (TRACE_1) {
System.out.println("mutated indy: " + BeanInspector.toString(x));
}
return x; return x;
} }
@ -788,7 +713,6 @@ public class MutateESRankMuCMA implements InterfaceAdaptOperatorGenerational, In
* @return * @return
*/ */
public boolean testAllDistBelow(Population pop, double tolX) { public boolean testAllDistBelow(Population pop, double tolX) {
// if all(sigma*(max(abs(pc), sqrt(diag(C)))) < stopTolX)
boolean res = true; boolean res = true;
CMAParamSet params = (CMAParamSet) pop.getData(cmaParamsKey); CMAParamSet params = (CMAParamSet) pop.getData(cmaParamsKey);
int i = 0; 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); res = res && (getSigma(params, i) * Math.max(Math.abs(params.pathC[i]), Math.sqrt(params.mC.get(i, i))) < tolX);
i++; i++;
} }
if (TRACE_TEST) {
if (res) {
System.out.println("testAllDistBelow hit");
}
}
return res; 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])); res = res && (params.meanX[i] == (params.meanX[i] + d * getSigma(params, i) * ev_k[i]));
i++; i++;
} }
if (TRACE_TEST) {
if (res) {
System.out.println("testNoChangeAddingDevAxis hit");
}
}
return res; return res;
} }
@ -842,8 +757,6 @@ public class MutateESRankMuCMA implements InterfaceAdaptOperatorGenerational, In
* @return * @return
*/ */
public boolean testNoEffectCoord(Population pop, double d) { public boolean testNoEffectCoord(Population pop, double d) {
// if any(xmean == xmean + 0.2*sigma*sqrt(diag(C)))
// stopflag(end+1) = {'warnnoeffectcoord'};
boolean ret = false; boolean ret = false;
CMAParamSet params = (CMAParamSet) pop.getData(cmaParamsKey); CMAParamSet params = (CMAParamSet) pop.getData(cmaParamsKey);
int i = 0; 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)))); ret = ret || (params.meanX[i] == (params.meanX[i] + d * getSigma(params, i) * Math.sqrt(params.mC.get(i, i))));
i++; i++;
} }
if (TRACE_TEST) {
if (ret) {
System.out.println("testNoEffectCoord hit");
}
}
return ret; return ret;
} }
@ -867,18 +775,9 @@ public class MutateESRankMuCMA implements InterfaceAdaptOperatorGenerational, In
* @return true, if a diagonal entry is <= 0 or >= d, else false * @return true, if a diagonal entry is <= 0 or >= d, else false
*/ */
public boolean testCCondition(Population pop, double d) { 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); CMAParamSet params = (CMAParamSet) pop.getData(cmaParamsKey);
Pair<Double, Double> minMax = params.mC.getMinMaxDiag(); Pair<Double, Double> minMax = params.mC.getMinMaxDiag();
if ((minMax.head <= 0) || (minMax.tail >= d)) { return (minMax.head <= 0) || (minMax.tail >= d);
if (TRACE_TEST) {
System.out.println("testCCondition hit");
}
return true;
} else {
return false;
}
} }
/** /**

View File

@ -16,7 +16,6 @@ import eva2.optimization.population.Population;
*/ */
public abstract class AbstractParameterControl implements InterfaceParameterControl { public abstract class AbstractParameterControl implements InterfaceParameterControl {
public Object[] initialValues = null; public Object[] initialValues = null;
protected static boolean TRACE = false;
public AbstractParameterControl() { public AbstractParameterControl() {
} }
@ -57,10 +56,6 @@ public abstract class AbstractParameterControl implements InterfaceParameterCont
if (!BeanInspector.setMem(obj, params[i], vals[i])) { 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("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])); 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);
}
} }
} }
} }

View File

@ -30,9 +30,6 @@ public class ConstraintBasedAdaption implements ParamAdaption, Serializable {
LinkedList<Boolean> lastBestSatisfactionState = new LinkedList<Boolean>(); LinkedList<Boolean> lastBestSatisfactionState = new LinkedList<Boolean>();
// private double endAct=0;
// private double deltaInertness = 0.1;
private static boolean TRACE = false;
private static String target = "penaltyFactor"; private static String target = "penaltyFactor";
@ -44,8 +41,6 @@ public class ConstraintBasedAdaption implements ParamAdaption, Serializable {
betaInc = o.betaInc; betaInc = o.betaInc;
betaDec = o.betaDec; betaDec = o.betaDec;
genGap = o.genGap; genGap = o.genGap;
// endAct = o.endAct;
// deltaInertness = o.deltaInertness;
} }
@Override @Override
@ -59,9 +54,6 @@ public class ConstraintBasedAdaption implements ParamAdaption, Serializable {
if (!(obj instanceof AbstractConstraint)) { if (!(obj instanceof AbstractConstraint)) {
System.err.println(this.getClass().getSimpleName() + " cant control " + obj.getClass().getSimpleName() + " ! "); System.err.println(this.getClass().getSimpleName() + " cant control " + obj.getClass().getSimpleName() + " ! ");
} else { } else {
if (TRACE) {
System.out.println("calc value at it " + iteration + " of " + maxIteration);
}
if (lastBestSatisfactionState.size() == genGap) { if (lastBestSatisfactionState.size() == genGap) {
lastBestSatisfactionState.poll(); lastBestSatisfactionState.poll();
} }
@ -80,9 +72,6 @@ public class ConstraintBasedAdaption implements ParamAdaption, Serializable {
currentFactor = maxPenalty / initialPenalty; currentFactor = maxPenalty / initialPenalty;
curPen = maxPenalty; curPen = maxPenalty;
} }
if (TRACE && changed) {
System.out.println("NEW penalty: " + curPen);
}
return curPen; return curPen;
} }
@ -101,18 +90,10 @@ public class ConstraintBasedAdaption implements ParamAdaption, Serializable {
if (allValid) { if (allValid) {
currentFactor *= betaDec; currentFactor *= betaDec;
changed = true; changed = true;
if (TRACE) {
System.out.println("all valid, new fact is " + currentFactor + " times " + initialPenalty);
}
} else if (allInvalid) { } else if (allInvalid) {
changed = true; changed = true;
currentFactor *= betaInc; 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; return changed;
} }

View File

@ -27,7 +27,6 @@ public class PSOActivityFeedbackControl implements ParamAdaption, Serializable {
private double startAct = 0.17; private double startAct = 0.17;
private double endAct = 0.01; private double endAct = 0.01;
private double deltaInertness = 0.1; private double deltaInertness = 0.1;
private static boolean TRACE = false;
private boolean exponentialSchedule = true; private boolean exponentialSchedule = true;
private static String target = "inertnessOrChi"; private static String target = "inertnessOrChi";
@ -71,9 +70,7 @@ public class PSOActivityFeedbackControl implements ParamAdaption, Serializable {
private double calcNewInertness(double currentInertness, double currentAct, private double calcNewInertness(double currentInertness, double currentAct,
double desiredActivity) { double desiredActivity) {
if (TRACE) {
System.out.println("Activity was " + currentAct + ", desired: " + desiredActivity);
}
if (currentAct < desiredActivity) { // increase inertness if (currentAct < desiredActivity) { // increase inertness
return Math.min(maxInert, currentInertness + deltaInertness); return Math.min(maxInert, currentInertness + deltaInertness);
} else if (currentAct > desiredActivity) { // too high act, so decrease inertness } else if (currentAct > desiredActivity) { // too high act, so decrease inertness

View File

@ -27,7 +27,6 @@ import java.util.Vector;
public class ParameterControlManager implements InterfaceParameterControl, Serializable { public class ParameterControlManager implements InterfaceParameterControl, Serializable {
public Object[] initialValues = null; public Object[] initialValues = null;
private ParamAdaption[] singleAdapters = new ParamAdaption[]{}; private ParamAdaption[] singleAdapters = new ParamAdaption[]{};
protected static boolean TRACE = false;
public ParameterControlManager() { public ParameterControlManager() {
} }
@ -111,13 +110,6 @@ public class ParameterControlManager implements InterfaceParameterControl, Seria
if (!BeanInspector.setMem(obj, params[i], vals[i])) { 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("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])); 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}; Object[] args = new Object[]{null, pop, iteration, maxIteration};
@ -140,8 +132,8 @@ public class ParameterControlManager implements InterfaceParameterControl, Seria
public String[] getControlledParameters() { public String[] getControlledParameters() {
if (singleAdapters != null) { if (singleAdapters != null) {
Vector<String> names = new Vector<String>(singleAdapters.length); Vector<String> names = new Vector<String>(singleAdapters.length);
for (int i = 0; i < singleAdapters.length; i++) { for (ParamAdaption singleAdapter : singleAdapters) {
String prm = singleAdapters[i].getControlledParam(); String prm = singleAdapter.getControlledParam();
if (prm != null) { if (prm != null) {
names.add(prm); names.add(prm);
} }

View File

@ -13,7 +13,6 @@ import eva2.problems.AbstractMultiObjectiveOptimizationProblem;
public class MetricS implements InterfaceParetoFrontMetric, java.io.Serializable { public class MetricS implements InterfaceParetoFrontMetric, java.io.Serializable {
private double[][] objectiveSpaceRange; private double[][] objectiveSpaceRange;
private static boolean TRACE = false;
public MetricS() { public MetricS() {
@ -57,35 +56,17 @@ public class MetricS implements InterfaceParetoFrontMetric, java.io.Serializable
@Override @Override
public double calculateMetricOn(Population pop, AbstractMultiObjectiveOptimizationProblem problem) { public double calculateMetricOn(Population pop, AbstractMultiObjectiveOptimizationProblem problem) {
this.objectiveSpaceRange = problem.getObjectiveSpaceRange(); this.objectiveSpaceRange = problem.getObjectiveSpaceRange();
if (TRACE) {
System.out.println("Border: " + BeanInspector.toString(objectiveSpaceRange));
}
double smetric = this.calculateSMetric(pop, this.objectiveSpaceRange, this.objectiveSpaceRange.length); double smetric = this.calculateSMetric(pop, this.objectiveSpaceRange, this.objectiveSpaceRange.length);
double reference = 1; double reference = 1;
for (int i = 0; i < this.objectiveSpaceRange.length; i++) { for (double[] anObjectiveSpaceRange : this.objectiveSpaceRange) {
reference *= (this.objectiveSpaceRange[i][1] - this.objectiveSpaceRange[i][0]); reference *= (anObjectiveSpaceRange[1] - anObjectiveSpaceRange[0]);
} }
//System.out.println("SMetric: "+smetric +" Reference: " + reference); //System.out.println("SMetric: "+smetric +" Reference: " + reference);
double res = ((Math.abs(smetric) / Math.abs(reference)) * 100); double res = ((Math.abs(smetric) / Math.abs(reference)) * 100);
if (TRACE) {
System.out.println("Res is " + res);
}
return 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 * This method will calculate the s-metric from a double array of
* fitness cases * fitness cases

View File

@ -46,7 +46,6 @@ import java.util.Vector;
*/ */
public class PostProcess { public class PostProcess {
protected static InterfaceDistanceMetric metric = new PhenotypeMetric(); protected static InterfaceDistanceMetric metric = new PhenotypeMetric();
private static final boolean TRACE = false;
// the default mutation step size for HC post processing // the default mutation step size for HC post processing
private static double defaultMutationStepSize = 0.01; private static double defaultMutationStepSize = 0.01;
@ -175,17 +174,7 @@ public class PostProcess {
result.setSameParams(pop); result.setSameParams(pop);
clustering.initClustering(pop); clustering.initClustering(pop);
Population[] clusters = clustering.cluster(pop, null); 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++) { for (int j = 0; j < clusters.length; j++) {
if (j == 0) { // cluster 0 contains non-assigned individuals if (j == 0) { // cluster 0 contains non-assigned individuals
if (lonerMode == DISCARD_LONERS) { if (lonerMode == DISCARD_LONERS) {
@ -580,9 +569,7 @@ public class PostProcess {
case nelderMead: case nelderMead:
double[][] range = ((InterfaceDataTypeDouble) candidates.getEAIndividual(index)).getDoubleRange(); double[][] range = ((InterfaceDataTypeDouble) candidates.getEAIndividual(index)).getDoubleRange();
double perturb = findNMSPerturb(candidates, index, relToAbsPerturb(maxRelativePerturbation, range)); 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); subPop = NelderMeadSimplex.createNMSPopulation(candidates.getEAIndividual(index), absToRelPerturb(perturb, range), range, false);
} }
return subPop; return subPop;
@ -636,9 +623,7 @@ public class PostProcess {
return evalsDone; return evalsDone;
} else { } else {
int stepsPerCand = (steps - (candCnt * (dim - 1))) / candCnt; int stepsPerCand = (steps - (candCnt * (dim - 1))) / candCnt;
if (TRACE) {
System.out.println("employing " + stepsPerCand + " steps per cand.");
}
if (stepsPerCand < dim) { if (stepsPerCand < dim) {
System.err.println("Too few steps allowed in processSingleCandidates!"); System.err.println("Too few steps allowed in processSingleCandidates!");
System.err.println("Method: " + method + ", cands: " + candidates.size() + ", steps: " + steps); System.err.println("Method: " + method + ", cands: " + candidates.size() + ", steps: " + steps);
@ -689,9 +674,7 @@ public class PostProcess {
if (term == null) { if (term == null) {
int stepsPerCand = 10 * (nmPops.get(0).size() - 1); // == 10*dim for NM int stepsPerCand = 10 * (nmPops.get(0).size() - 1); // == 10*dim for NM
if (TRACE) {
System.out.println("employing " + stepsPerCand + " per candidate.");
}
if (stepsPerCand < 1) { if (stepsPerCand < 1) {
System.err.println("Too few steps allowed!"); System.err.println("Too few steps allowed!");
return 0; return 0;
@ -959,18 +942,11 @@ public class PostProcess {
double[] meanFit = clust.getMeanFitness(); 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); int evalsDone = processSingleCandidates(method, clust, funCalls, sigmaCluster / 2., problem, mute);
clust.setFunctionCalls(evalsBefore + evalsDone); clust.setFunctionCalls(evalsBefore + evalsDone);
double improvement = EuclideanMetric.euclideanDistance(meanFit, clust.getMeanFitness()); double improvement = EuclideanMetric.euclideanDistance(meanFit, clust.getMeanFitness());
if (TRACE) {
System.out.println("improvement by " + improvement + " funcalls done: " + evalsDone);
}
return new Pair<Population, Double>(clust, improvement); return new Pair<Population, Double>(clust, improvement);
} }
@ -990,7 +966,6 @@ public class PostProcess {
listener.println("max peak ratio is " + mmkProb.getMaximumPeakRatio(getFoundOptima(solutions, mmkProb.getRealOptima(), mmkProb.getDefaultAccuracy(), true))); listener.println("max peak ratio is " + mmkProb.getMaximumPeakRatio(getFoundOptima(solutions, mmkProb.getRealOptima(), mmkProb.getDefaultAccuracy(), true)));
if (mmkProb.fullListAvailable()) { if (mmkProb.fullListAvailable()) {
for (double epsilon = 0.1; epsilon > 0.00000001; epsilon /= 10.) { 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)); listener.println("found " + getFoundOptima(solutions, mmkProb.getRealOptima(), epsilon, true).size() + " for epsilon = " + epsilon + ", maxPeakRatio: " + mmkProb.getMaximumPeakRatio(solutions));
} }
} }

View File

@ -22,15 +22,13 @@ import java.io.Serializable;
* *
* @author mkron * @author mkron
*/ */
public abstract class PopulationMeasureTerminator implements InterfaceTerminator, public abstract class PopulationMeasureTerminator implements InterfaceTerminator, Serializable {
Serializable {
public enum ChangeTypeEnum {relativeChange, absoluteChange, absoluteValue} public enum ChangeTypeEnum {relativeChange, absoluteChange, absoluteValue}
public enum DirectionTypeEnum {decrease, bidirectional} public enum DirectionTypeEnum {decrease, bidirectional}
public enum StagnationTypeEnum {fitnessCallBased, generationBased} public enum StagnationTypeEnum {fitnessCallBased, generationBased}
protected static boolean TRACE = false;
private double convThresh = 0.01; //, convThreshLower=0.02; private double convThresh = 0.01; //, convThreshLower=0.02;
private double oldMeasure = -1; private double oldMeasure = -1;
private int stagTime = 1000; private int stagTime = 1000;
@ -96,9 +94,7 @@ public abstract class PopulationMeasureTerminator implements InterfaceTerminator
@Override @Override
public boolean isTerminated(PopulationInterface pop) { public boolean isTerminated(PopulationInterface pop) {
if (!firstTime && isStillConverged(pop)) { if (!firstTime && isStillConverged(pop)) {
if (TRACE) {
System.out.println("Converged at " + pop.getGeneration() + "/" + pop.getFunctionCalls() + ", measure " + calcPopulationMeasure(pop));
}
if (stagnationTimeHasPassed(pop)) { if (stagnationTimeHasPassed(pop)) {
// population hasnt changed much for max time, criterion is met // population hasnt changed much for max time, criterion is met
msg = getTerminationMessage(); msg = getTerminationMessage();
@ -226,18 +222,6 @@ public abstract class PopulationMeasureTerminator implements InterfaceTerminator
break; break;
} }
ret = (measure <= allowedUpper) && (measure >= allowedLower); 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; 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."; 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) { public void setStagnationTime(int k) {
stagTime = k; stagTime = k;
} }

View File

@ -1853,24 +1853,8 @@ public class Population extends ArrayList implements PopulationInterface, Clonea
* an array of three * an array of three
*/ */
public double[] getPopulationMeasures(InterfaceDistanceMetric metric) { 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); 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; return res;
} }

View File

@ -19,29 +19,6 @@ public class EvAStatisticalEvaluation {
public static EvAStatisticalEvaluationParams statsParams = new EvAStatisticalEvaluationParams(); 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<OptimizationJob> jobsToWorkWith = new ArrayList<OptimizationJob>();
// for (int i=0; i<jobList.length; i++) {
// // remove jobs which are not finished or not selected
// if (jobList[i]!=null && (Mathematics.contains(selectedIndices, i)) && (jobList[i].isFinishedAndComplete())) jobsToWorkWith.add(jobList[i]);
// }
// List<String> commonFields = getCommonFields(jobsToWorkWith);
// if (commonFields!=null && !commonFields.isEmpty()) for (String field : commonFields) {
// textout.println("Checking field " + field);
//
// for (int i=0; i<jobsToWorkWith.size(); i++) {
// textout.print(jobsToWorkWith.get(i).getParams().getOptimizer().getName() + "\t");
// for (int j=0; j<jobsToWorkWith.size(); j++) {
//// System.out.println("Comparing " + i + " with " + j);
// textout.print("\t" + compare(field, jobsToWorkWith.get(i), jobsToWorkWith.get(j)));
// }
// textout.println("");
// }
// }
// }
public static void evaluate(InterfaceTextListener textout, OptimizationJob[] jobList, int[] selectedIndices, public static void evaluate(InterfaceTextListener textout, OptimizationJob[] jobList, int[] selectedIndices,
StatsOnSingleDataSetEnum[] singleStats, StatsOnSingleDataSetEnum[] singleStats,

View File

@ -523,12 +523,7 @@ public class ANPSO extends NichePSO implements InterfaceOptimizer, InterfaceAddi
Population tmpPop = new Population(), newMainPop = new Population(); Population tmpPop = new Population(), newMainPop = new Population();
Vector<Population> setOfSubswarms = new Vector<Population>(); Vector<Population> setOfSubswarms = new Vector<Population>();
boolean reinitSuperfl = true; boolean reinitSuperfl = true;
boolean TRACEMTHD = false;
// ... and use the corresponding particles to create the subswarms
if (TRACEMTHD) {
System.out.println("---------");
}
for (Set<String> connSet : connectedComps) { for (Set<String> connSet : connectedComps) {
if (connSet.size() > 1) {// create niche if (connSet.size() > 1) {// create niche
Population pop = new Population(connSet.size()); Population pop = new Population(connSet.size());
@ -540,16 +535,9 @@ public class ANPSO extends NichePSO implements InterfaceOptimizer, InterfaceAddi
} }
pop.add(indy); pop.add(indy);
} }
if (TRACEMTHD) {
System.out.print(" subswarm size ssize " + pop.size());
}
if (maxInitialSubSwarmSize > 0 && (pop.size() > maxInitialSubSwarmSize)) { if (maxInitialSubSwarmSize > 0 && (pop.size() > maxInitialSubSwarmSize)) {
if (TRACEMTHD) {
System.out.print(" removing " + (pop.size() - maxInitialSubSwarmSize));
}
tmpPop = pop.getWorstNIndividuals(pop.size() - maxInitialSubSwarmSize, -1); tmpPop = pop.getWorstNIndividuals(pop.size() - maxInitialSubSwarmSize, -1);
tmpPop.synchSize(); tmpPop.synchSize();
// Population testPop=(Population)pop.clone();
pop.removeMembers(tmpPop, true); pop.removeMembers(tmpPop, true);
if (reinitSuperfl) { if (reinitSuperfl) {
for (int i = 0; i < tmpPop.size(); i++) { for (int i = 0; i < tmpPop.size(); i++) {
@ -565,9 +553,6 @@ public class ANPSO extends NichePSO implements InterfaceOptimizer, InterfaceAddi
pop.synchSize(); pop.synchSize();
} }
setOfSubswarms.add(pop); setOfSubswarms.add(pop);
if (TRACEMTHD) {
System.out.print("\nNew subswarm of size: " + pop.size());
}
} else { // move particles corresponding to unconnected vertices to the mainswarm } else { // move particles corresponding to unconnected vertices to the mainswarm
Iterator<String> it = connSet.iterator(); Iterator<String> it = connSet.iterator();
Integer index = Integer.valueOf(it.next()); Integer index = Integer.valueOf(it.next());
@ -575,17 +560,10 @@ public class ANPSO extends NichePSO implements InterfaceOptimizer, InterfaceAddi
newMainPop.add(indy); newMainPop.add(indy);
} }
} }
// for (int i=0; i<setOfSubswarms.size(); i++) {
// if (!getMainSwarm().getPopulation().assertMembers(setOfSubswarms.get(i))) {
// System.err.println("Wrong subswarm " + i);
// }
// }
if (TRACEMTHD) {
System.out.println();
}
newMainPop.synchSize(); newMainPop.synchSize();
for (int i = 0; i < setOfSubswarms.size(); i++) { for (Population setOfSubswarm : setOfSubswarms) {
setOfSubswarms.get(i).synchSize(); setOfSubswarm.synchSize();
} }
useAsSubSwarms(setOfSubswarms); useAsSubSwarms(setOfSubswarms);
useAsMainSwarm(newMainPop); useAsMainSwarm(newMainPop);
@ -599,7 +577,6 @@ public class ANPSO extends NichePSO implements InterfaceOptimizer, InterfaceAddi
*/ */
@Override @Override
public void optimize() { public void optimize() {
// System.out.println(BeanInspector.toString(getMainSwarm()));
// main swarm: // main swarm:
if (getMainSwarm().getPopulation().size() == 0) {// || mainSwarm.getPopulation().size() == 1){ if (getMainSwarm().getPopulation().size() == 0) {// || mainSwarm.getPopulation().size() == 1){
if (isVerbose()) { if (isVerbose()) {
@ -656,27 +633,24 @@ public class ANPSO extends NichePSO implements InterfaceOptimizer, InterfaceAddi
if (isPlot()) { if (isPlot()) {
doPlot(); doPlot();
} }
// System.out.println();
/** end plotting *******************************************************************************/
// reset flags etc for: // reset flags etc for:
// deactivation // deactivation
deactivationOccured = false; deactivationOccured = false;
deactivatedSwarm = new Vector<ParticleSubSwarmOptimization>(); deactivatedSwarm = new Vector<>();
//reinitedSwarm = new Vector<ParticleSubSwarmOptimization>();
// merging // merging
mergingOccurd = false; mergingOccurd = false;
borg = new Vector<ParticleSubSwarmOptimization>(); borg = new Vector<>();
others = new Vector<ParticleSubSwarmOptimization>(); others = new Vector<>();
borgbest = new Vector<AbstractEAIndividual>(); borgbest = new Vector<>();
othersbest = new Vector<AbstractEAIndividual>(); othersbest = new Vector<>();
// absorbtion // absorbtion
absorbtionOccurd = false; absorbtionOccurd = false;
indytoabsorb = new Vector<AbstractEAIndividual>(); indytoabsorb = new Vector<>();
// subswarmcreation // subswarmcreation
creationOccurd = false; creationOccurd = false;
indyconverged = new Vector<AbstractEAIndividual>(); indyconverged = new Vector<>();
convergedneighbor = new Vector<AbstractEAIndividual>(); convergedneighbor = new Vector<>();
//clearing - deprecated //clearing - deprecated
//reinitoccurd = false; //reinitoccurd = false;
@ -751,21 +725,10 @@ public class ANPSO extends NichePSO implements InterfaceOptimizer, InterfaceAddi
currentsubswarm = (Population) getSubSwarms().get(i).getPopulation().clone(); currentsubswarm = (Population) getSubSwarms().get(i).getPopulation().clone();
metapop.addPopulation(currentsubswarm); metapop.addPopulation(currentsubswarm);
} }
for (int i = 0; i < inactiveSubSwarms.size(); ++i) { // in the case of ANPSO for (ParticleSubSwarmOptimization inactiveSubSwarm : inactiveSubSwarms) { // in the case of ANPSO
currentsubswarm = (Population) inactiveSubSwarms.get(i).getPopulation().clone(); currentsubswarm = (Population) inactiveSubSwarm.getPopulation().clone();
metapop.addPopulation(currentsubswarm); 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 // set correct number of generations
metapop.setGeneration(getMainSwarm().getPopulation().getGeneration()); metapop.setGeneration(getMainSwarm().getPopulation().getGeneration());
@ -774,9 +737,7 @@ public class ANPSO extends NichePSO implements InterfaceOptimizer, InterfaceAddi
int calls = getMainSwarm().getPopulation().getFunctionCalls(); int calls = getMainSwarm().getPopulation().getFunctionCalls();
for (int i = 0; i < getSubSwarms().size(); ++i) { for (int i = 0; i < getSubSwarms().size(); ++i) {
ParticleSubSwarmOptimization subswarm = getSubSwarms().get(i); ParticleSubSwarmOptimization subswarm = getSubSwarms().get(i);
// if (subswarm.isActive()){
calls += subswarm.getPopulation().getFunctionCalls(); calls += subswarm.getPopulation().getFunctionCalls();
// }
} }
// calls from inactivated subswarms were transfered to the mainswarm, see useAsSubSwarms method // 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; int mainSize = 0;
//if (includeMainSwarm) mainSize = getMainSwarm().getPopulation().size(); //if (includeMainSwarm) mainSize = getMainSwarm().getPopulation().size();
Population elitePop = new Population(getSubSwarms().size() + inactiveSubSwarms.size() + mainSize); 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) { for (int i = 0; i < getSubSwarms().size(); ++i) {
AbstractEAIndividual bestSS = getSubSwarms().get(i).getBestIndividual(); AbstractEAIndividual bestSS = getSubSwarms().get(i).getBestIndividual();
elitePop.addIndividual((AbstractEAIndividual) getSubSwarms().get(i).bestIndividual.clone()); elitePop.addIndividual((AbstractEAIndividual) getSubSwarms().get(i).bestIndividual.clone());
} }
for (int i = 0; i < inactiveSubSwarms.size(); ++i) { for (ParticleSubSwarmOptimization inactiveSubSwarm : inactiveSubSwarms) {
elitePop.addIndividual((AbstractEAIndividual) inactiveSubSwarms.get(i).bestIndividual.clone()); elitePop.addIndividual((AbstractEAIndividual) inactiveSubSwarm.bestIndividual.clone());
} }
return elitePop; return elitePop;
} }
@ -821,7 +778,6 @@ public class ANPSO extends NichePSO implements InterfaceOptimizer, InterfaceAddi
for (int i = 0; i < getSubSwarms().size() + inactiveSubSwarms.size(); ++i) { for (int i = 0; i < getSubSwarms().size() + inactiveSubSwarms.size(); ++i) {
result += elite.getEAIndividual(i).getStringRepresentation() + "\n"; result += elite.getEAIndividual(i).getStringRepresentation() + "\n";
} }
//result += "\n";
return result; return result;
} }
@ -863,15 +819,8 @@ public class ANPSO extends NichePSO implements InterfaceOptimizer, InterfaceAddi
if (!currentsubswarm.isActive()) { if (!currentsubswarm.isActive()) {
plotCircleForIndy((AbstractEAIndividual) best, "[I]"); plotCircleForIndy((AbstractEAIndividual) best, "[I]");
} else { } else {
if (!getSubswarmOptimizerTemplate().isGcpso()) {
//plotCircleForIndy((AbstractEAIndividual)best,getMaxStdDevFromSwarmAsString(currentsubswarm));
}
if (getSubswarmOptimizerTemplate().isGcpso()) { if (getSubswarmOptimizerTemplate().isGcpso()) {
String rhoAsString = String.format("%6.3f", currentsubswarm.getRho()); 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(); return "ANPSO-" + getMainSwarmSize();
} }
//
// public double getMinimalR() {
// return minimalR;
// }
public void SetMinimalR(double minimalR) { public void SetMinimalR(double minimalR) {
this.minimalR = minimalR; this.minimalR = minimalR;
} }

View File

@ -30,8 +30,6 @@ import java.util.BitSet;
*/ */
@Description("A basic implementation of a Binary ScatterSearch") @Description("A basic implementation of a Binary ScatterSearch")
public class BinaryScatterSearch implements InterfaceOptimizer, java.io.Serializable, InterfacePopulationChangedEventListener { public class BinaryScatterSearch implements InterfaceOptimizer, java.io.Serializable, InterfacePopulationChangedEventListener {
private static boolean TRACE = false;
transient private InterfacePopulationChangedEventListener populationChangedEventListener = null; transient private InterfacePopulationChangedEventListener populationChangedEventListener = null;
private String identifier = "BinaryScatterSearch"; private String identifier = "BinaryScatterSearch";
private int MaxImpIter = 5; private int MaxImpIter = 5;
@ -236,17 +234,9 @@ public class BinaryScatterSearch implements InterfaceOptimizer, java.io.Serializ
int numToInit = this.poolSize - pop.size(); int numToInit = this.poolSize - pop.size();
if (numToInit > 0) { if (numToInit > 0) {
pop.addAll(generateG1((int) (numToInit * this.g1))); pop.addAll(generateG1((int) (numToInit * this.g1)));
if (TRACE) {
System.out.println("s1: " + pop.size());
}
generateG2(pop, (int) (numToInit * this.g2)); generateG2(pop, (int) (numToInit * this.g2));
if (TRACE) {
System.out.println("s2: " + pop.size());
}
generateG3(pop, poolSize - pop.size()); generateG3(pop, poolSize - pop.size());
if (TRACE) {
System.out.println("s3: " + pop.size());
}
} }
return pop; return pop;
} }
@ -272,8 +262,9 @@ public class BinaryScatterSearch implements InterfaceOptimizer, java.io.Serializ
* 000...000, then 010101...01, 101010...10, 001001001...001, * 000...000, then 010101...01, 101010...10, 001001001...001,
* 110110110...110 and so on * 110110110...110 and so on
* *
* @param pop the initial Population * @param targetSize The size of the new Population
* @return the new Population * @param template The template individual to use
* @return a new Population
*/ */
public static Population generateG1Pop(int targetSize, AbstractEAIndividual template) { public static Population generateG1Pop(int targetSize, AbstractEAIndividual template) {
boolean method1 = true; boolean method1 = true;
@ -716,8 +707,7 @@ public class BinaryScatterSearch implements InterfaceOptimizer, java.io.Serializ
// generate a new Pool // generate a new Pool
this.pool = new Population(); this.pool = new Population();
ArrayList<Population> newSubsets = generateSubsets(); ArrayList<Population> newSubsets = generateSubsets();
for (int i = 0; i < newSubsets.size(); i++) { for (Population s : newSubsets) {
Population s = newSubsets.get(i);
AbstractEAIndividual x = combineSolution(s); AbstractEAIndividual x = combineSolution(s);
if (!contains((InterfaceDataTypeBinary) x, this.pool) && this.pool.size() <= this.poolSize) { if (!contains((InterfaceDataTypeBinary) x, this.pool) && this.pool.size() <= this.poolSize) {
this.pool.add(x); this.pool.add(x);

View File

@ -69,7 +69,6 @@ public class ClusterBasedNichingEA implements InterfacePopulationChangedEventLis
private int populationSize = 50; private int populationSize = 50;
private int convergedCnt = 0; private int convergedCnt = 0;
private int collisions = 0; private int collisions = 0;
private static boolean TRACE = false, TRACE_STATE = false, TRACE_EVTS = false;
private int showCycle = 0; private int showCycle = 0;
transient private TopoPlot topologyPlot; transient private TopoPlot topologyPlot;
private int haltingWindow = 15; private int haltingWindow = 15;
@ -450,88 +449,43 @@ public class ClusterBasedNichingEA implements InterfacePopulationChangedEventLis
return ret; return ret;
} else { } else {
return (histComparator.compare(firstIndy, secIndy) > 0); return (histComparator.compare(firstIndy, secIndy) > 0);
// return (secIndy.isDominatingDebConstraints(firstIndy));
} }
} }
private Population optimizeSpecies(Population species, boolean minorPlot) { private Population optimizeSpecies(Population species, boolean minorPlot) {
optimizer.setPopulation(species); optimizer.setPopulation(species);
// optimizer.initializeByPopulation(species, false);
if (optimizer instanceof EvolutionStrategies) { if (optimizer instanceof EvolutionStrategies) {
EvolutionStrategies es = (EvolutionStrategies) optimizer; EvolutionStrategies es = (EvolutionStrategies) optimizer;
int mu = Math.max(1, (int) (muLambdaRatio * species.size())); int mu = Math.max(1, (int) (muLambdaRatio * species.size()));
if (mu >= 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); mu = Math.max(1, species.size() - 1);
} }
es.setMu(mu); es.setMu(mu);
es.setLambda(species.size()); 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) { if (BeanInspector.hasMethod(optimizer, "getLastModelPopulation", null) != null) {
Object pc = BeanInspector.callIfAvailable(optimizer, "getLastTrainingPatterns", null); Object pc = BeanInspector.callIfAvailable(optimizer, "getLastTrainingPatterns", null);
// System.out.println("MAPSO train set bef optSpec: " + BeanInspector.callIfAvailable(pc, "getStringRepresentation", null));
} }
this.optimizer.optimize(); this.optimizer.optimize();
Population retPop = optimizer.getPopulation(); 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 (retPop.size() != retPop.getTargetSize()) {
if (TRACE) {
System.out.println("correcting popsize after opt: " + retPop.getTargetSize() + " to " + retPop.size());
}
retPop.synchSize(); retPop.synchSize();
} }
// if (useDistraction) { // distraction step
// if ((distraction != null) && (!distraction.isEmpty())) {
// System.out.println("Distraction step!!!");
// boolean distrHappened = false;
// for (int i=0; i<retPop.size(); i++) {
// distrHappened |= distraction.applyDistractionTo(retPop.getEAIndividual(i));
// }
// if (distrHappened) {
//// Object distrList = species.getData("distraction");
//// if (distr)
//// species.addData("distr", value)
// }
// }
// }
return retPop; return retPop;
} }
@Override @Override
public void optimize() { public void optimize() {
Population reinitPop = null; Population reinitPop = null;
if (TRACE_STATE) {
printState("---- CBN Optimizing", doomedPopulation);
// System.out.println("-Funcalls: "+undifferentiatedPopulation.getFunctionCalls());
}
if (doomedPopulation.size() > 0) { if (doomedPopulation.size() > 0) {
reinitPop = this.initializeIndividuals(doomedPopulation.size()); // do not add these to undifferentiated yet, that would mess up the evaluation count reinitPop = this.initializeIndividuals(doomedPopulation.size()); // do not add these to undifferentiated yet, that would mess up the evaluation count
doomedPopulation.clear(); doomedPopulation.clear();
// if (TRACE)
// System.out.println("At " + undifferentiatedPopulation.getFunctionCalls() + " reinited " + reinitPop.size() + " indies... ");
} }
int countIndies = (reinitPop != null ? reinitPop.size() : 0) + undifferentiatedPopulation.size(); int countIndies = (reinitPop != null ? reinitPop.size() : 0) + undifferentiatedPopulation.size();
for (int i = 0; i < species.size(); i++) { for (Population specy1 : species) {
countIndies += species.get(i).size(); countIndies += specy1.size();
}
if (TRACE) {
System.out.println("NumIndies: " + countIndies);
} }
if (this.showCycle > 0) { if (this.showCycle > 0) {
if (undifferentiatedPopulation.getGeneration() <= 1) { if (undifferentiatedPopulation.getGeneration() <= 1) {
@ -550,7 +504,6 @@ public class ClusterBasedNichingEA implements InterfacePopulationChangedEventLis
// optimize D_0 // optimize D_0
this.undifferentiatedPopulation.synchSize(); this.undifferentiatedPopulation.synchSize();
if (undifferentiatedPopulation.size() > 0) { 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.putData(InterfaceSpeciesAware.populationTagKey, InterfaceSpeciesAware.explorerPopTag);
undifferentiatedPopulation = optimizeSpecies(undifferentiatedPopulation, false); undifferentiatedPopulation = optimizeSpecies(undifferentiatedPopulation, false);
} else { } else {
@ -560,40 +513,17 @@ public class ClusterBasedNichingEA implements InterfacePopulationChangedEventLis
Population curSpecies; Population curSpecies;
// optimize the clustered species // optimize the clustered species
for (int i = this.species.size() - 1; i >= 0; i--) { 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 = this.species.get(i);
curSpecies.setFunctionCalls(0); curSpecies.setFunctionCalls(0);
curSpecies.synchSize(); curSpecies.synchSize();
// if (isActive(curSpecies)) { // Lets have only active species...
if ((haltingWindow > 0) && (this.testSpeciesForConvergence(curSpecies))) { 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++; 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 AbstractEAIndividual best = curSpecies.getBestHistoric(); // usually we want the best alltogether
if (best == null) { if (best == null) {
best = (AbstractEAIndividual) curSpecies.getBestEAIndividual().getClone(); best = (AbstractEAIndividual) curSpecies.getBestEAIndividual().getClone();
} }
int toReinit = 0; int toReinit = 0;
populationArchive.add(best); populationArchive.add(best);
// System.out.println((""+ population.getFunctionCalls() + " " + (BeanInspector.toString(best.getDoublePosition())).replaceAll(";|\\[|\\]", "")));
species.remove(i); // remove the converged Species species.remove(i); // remove the converged Species
toReinit = curSpecies.size(); toReinit = curSpecies.size();
// those will not be optimized anymore, so we dont need to doom them, but can directly add them to undiff! // 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 // This is necessary to keep track of the function calls needed
undifferentiatedPopulation.incrFunctionCallsBy(curSpecies.getFunctionCalls()); 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. synchronized (population) { // fill the population instance with the current individuals from undiff, spec, etc.
this.population = (Population) this.undifferentiatedPopulation.clone(); this.population = (Population) this.undifferentiatedPopulation.clone();
population.setUseHistory(true); population.setUseHistory(true);
for (int i = 0; i < this.species.size(); i++) { for (Population specy : this.species) {
this.population.addPopulation(this.species.get(i)); this.population.addPopulation(specy);
} }
if (doomedPopulation.size() > 0) { if (doomedPopulation.size() > 0) {
population.addPopulation(reinitPop); population.addPopulation(reinitPop);
@ -627,34 +553,15 @@ public class ClusterBasedNichingEA implements InterfacePopulationChangedEventLis
population.synchSize(); 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 // possible species differentiation and convergence
if (this.undifferentiatedPopulation.getGeneration() % this.speciesCycle == 0) { if (this.undifferentiatedPopulation.getGeneration() % this.speciesCycle == 0) {
if (TRACE) {
System.out.println("Species cycle:");
}
initClustering(); initClustering();
if (this.useSpeciesDifferentiation) { if (this.useSpeciesDifferentiation) {
///////////////////////////// species differentiation phase
if (TRACE) {
printState("---Species Differentation", reinitPop);
}
Population[] clusters; Population[] clusters;
ArrayList<Population> newSpecies = new ArrayList<Population>(); ArrayList<Population> newSpecies = new ArrayList<Population>();
//cluster the undifferentiated population //cluster the undifferentiated population
clusters = this.caForSpeciesDifferentation.cluster(this.undifferentiatedPopulation, 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 for (int j = 1; j < clusters.length; j++) { // loop new clusters
splitFromFirst(undifferentiatedPopulation, clusters[j], false); splitFromFirst(undifferentiatedPopulation, clusters[j], false);
newSpecies.add(clusters[j]); newSpecies.add(clusters[j]);
@ -662,12 +569,8 @@ public class ClusterBasedNichingEA implements InterfacePopulationChangedEventLis
replaceUndifferentiated(clusters[0]); replaceUndifferentiated(clusters[0]);
for (int i = 0; i < this.species.size(); i++) { // loop old species for (int i = 0; i < this.species.size(); i++) { // loop old species
curSpecies = this.species.get(i); curSpecies = this.species.get(i);
// if (curSpecies.size()>minGroupSize) { // only active populations are clustered
// check if a species has differentiated any further // check if a species has differentiated any further
clusters = this.caForSpeciesDifferentation.cluster(curSpecies, population); clusters = this.caForSpeciesDifferentation.cluster(curSpecies, population);
if (TRACE) {
System.out.println("clustered " + i + " to " + clusters.length);
}
if (clusters[0].size() > 0) { if (clusters[0].size() > 0) {
mergeToFirst(undifferentiatedPopulation, clusters[0], false); mergeToFirst(undifferentiatedPopulation, clusters[0], false);
} }
@ -683,17 +586,8 @@ public class ClusterBasedNichingEA implements InterfacePopulationChangedEventLis
newSpecies.add(clusters[j]); newSpecies.add(clusters[j]);
} }
// } else {
// // small populations are kept directly
// newSpecies.add(curSpecies);
// }
} }
this.species = newSpecies; this.species = newSpecies;
if (TRACE) {
printState("---After differentiation", reinitPop);
}
//if (this.show) this.plot();
} // end of species differentiation } // end of species differentiation
// plot the populations // plot the populations
@ -704,17 +598,10 @@ public class ClusterBasedNichingEA implements InterfacePopulationChangedEventLis
} }
if (this.mergeSpecies && (species.size() > 0)) { if (this.mergeSpecies && (species.size() > 0)) {
///////////////////////////// species merging phase
if (TRACE) {
System.out.println("-Species merge:");
}
// first test if loners belong to any species // first test if loners belong to any species
int[] assocSpec = caForSpeciesMerging.associateLoners(undifferentiatedPopulation, species.toArray(new Population[species.size()]), population); int[] assocSpec = caForSpeciesMerging.associateLoners(undifferentiatedPopulation, species.toArray(new Population[species.size()]), population);
for (int i = undifferentiatedPopulation.size() - 1; i >= 0; i--) { // backwards or die! for (int i = undifferentiatedPopulation.size() - 1; i >= 0; i--) { // backwards or die!
if (assocSpec[i] >= 0) { if (assocSpec[i] >= 0) {
if (TRACE_EVTS) {
System.out.println("!!! Loner merge to " + i);
}
// loner i should be merged to species assocSpec[i] // loner i should be merged to species assocSpec[i]
AbstractEAIndividual tmpIndy = (AbstractEAIndividual) this.undifferentiatedPopulation.get(i); AbstractEAIndividual tmpIndy = (AbstractEAIndividual) this.undifferentiatedPopulation.get(i);
if (topologyPlot != null) { if (topologyPlot != null) {
@ -724,9 +611,6 @@ public class ClusterBasedNichingEA implements InterfacePopulationChangedEventLis
species.get(assocSpec[i]).add(tmpIndy); // TODO merge information from loners? species.get(assocSpec[i]).add(tmpIndy); // TODO merge information from loners?
} }
} }
if (TRACE) {
printState("---After loner-merges", reinitPop);
}
Population spec1, spec2; Population spec1, spec2;
// test if species are close to already archived solutions - deactivate them if so // test if species are close to already archived solutions - deactivate them if so
assocSpec = caForSpeciesMerging.associateLoners(populationArchive, species.toArray(new Population[species.size()]), population); 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 // the species has not yet been deactivated
specToRemove.add(assocSpec[i]); specToRemove.add(assocSpec[i]);
collisions++; 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); doomedPopulation.addPopulation(spec1);
} }
} }
@ -760,15 +634,9 @@ public class ClusterBasedNichingEA implements InterfacePopulationChangedEventLis
if (specIndex > lastRemoved) { if (specIndex > lastRemoved) {
System.err.println("Stupid queue!!!"); 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! species.remove(specIndex); // warning, dont try to remove Integer object but index i!
lastRemoved = specIndex; lastRemoved = specIndex;
} }
if (TRACE) {
printState("---After archive-merges", reinitPop);
}
// Now test if species should be merged among each other // Now test if species should be merged among each other
for (int i1 = 0; i1 < this.species.size(); i1++) { for (int i1 = 0; i1 < this.species.size(); i1++) {
spec1 = this.species.get(i1); spec1 = this.species.get(i1);
@ -776,39 +644,24 @@ public class ClusterBasedNichingEA implements InterfacePopulationChangedEventLis
spec2 = this.species.get(i2); spec2 = this.species.get(i2);
if (this.caForSpeciesMerging.mergingSpecies(spec1, spec2, population)) { 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); mergeToFirst(spec1, spec2, true);
this.species.remove(i2); this.species.remove(i2);
i2--; i2--;
} }
} }
} }
if (TRACE) {
printState("---After merging", reinitPop);
}
} /// end of species merging } /// end of species merging
if (maxSpeciesSize >= minGroupSize) { if (maxSpeciesSize >= minGroupSize) {
// reinit worst n individuals from all species which are too large // reinit worst n individuals from all species which are too large
for (int i = 0; i < species.size(); i++) { for (Population curSpec : species) {
Population curSpec = species.get(i);
if (curSpec.size() > maxSpeciesSize) { if (curSpec.size() > maxSpeciesSize) {
if (TRACE_EVTS) {
System.out.println("!!! Reinit indies " + (maxSpeciesSize - curSpec.size()));
}
ArrayList<AbstractEAIndividual> sorted = curSpec.getSorted(reduceSizeComparator); ArrayList<AbstractEAIndividual> sorted = curSpec.getSorted(reduceSizeComparator);
for (int k = maxSpeciesSize; k < sorted.size(); k++) { for (int k = maxSpeciesSize; k < sorted.size(); k++) {
if (curSpec.remove(sorted.get(k))) { if (curSpec.remove(sorted.get(k))) {
doomedPopulation.add(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()); undifferentiatedPopulation.setTargetSize(undifferentiatedPopulation.size());
// output the result // 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. synchronized (population) { // fill the population instance with the current individuals from undiff, spec, etc.
this.population = (Population) this.undifferentiatedPopulation.clone(); this.population = (Population) this.undifferentiatedPopulation.clone();
population.setUseHistory(true); population.setUseHistory(true);
for (int i = 0; i < this.species.size(); i++) { for (Population specy : this.species) {
this.population.addPopulation(this.species.get(i)); this.population.addPopulation(specy);
} }
if (doomedPopulation.size() > 0) { if (doomedPopulation.size() > 0) {
population.addPopulation(doomedPopulation); population.addPopulation(doomedPopulation);
} // this is just so that the numbers match up... } // this is just so that the numbers match up...
population.synchSize(); population.synchSize();
if (TRACE) {
System.out.println("Doomed size: " + doomedPopulation.size());
System.out.println("Population size: " + this.population.size());
}
if (population.size() != populationSize) { if (population.size() != populationSize) {
System.err.println("Warning: Invalid population size in CBNEA! " + population.size()); 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); 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 (getClusterDiffDist() > 0) { // assume that it should be set
if (this.caForSpeciesDifferentation instanceof InterfaceClusteringDistanceParam) { if (this.caForSpeciesDifferentation instanceof InterfaceClusteringDistanceParam) {
((InterfaceClusteringDistanceParam) caForSpeciesDifferentation).setClustDistParam(getClusterDiffDist()); ((InterfaceClusteringDistanceParam) caForSpeciesDifferentation).setClustDistParam(getClusterDiffDist());
if (TRACE) {
System.out.println("### Clustering distance parameter set to " + getClusterDiffDist());
}
} else { } else {
EVAERROR.errorMsgOnce("Warning: cluster distance is defined in CBN but the clustering method " + caForSpeciesDifferentation.getClass() + " cant interpret it!"); 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); 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<species.size(); i++) pop.addPopulation(species.get(i));
// pop.synchSize();
// return pop;
// }
/** /**
* Replace the undifferentiated population with the given one. * Replace the undifferentiated population with the given one.
* *
* @param pop * @param pop
*/ */
private void replaceUndifferentiated(Population pop) { private void replaceUndifferentiated(Population pop) {
// System.out.println("Adding " + pop.size() + " as undiff.");
undifferentiatedPopulation.clear(); undifferentiatedPopulation.clear();
undifferentiatedPopulation.addPopulation(pop); undifferentiatedPopulation.addPopulation(pop);
} }
private void printState(String headline, Population reinit) {
System.out.print(headline + ", Gen. " + this.undifferentiatedPopulation.getGeneration());
System.out.print(" - Undiff.: " + specTag(undifferentiatedPopulation));
System.out.print(", Demes: ");
int sum = undifferentiatedPopulation.size() + (reinit == null ? 0 : reinit.size());
if (species.size() > 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) { private String specTag(Population spec) {
return spec.size() + "(" + spec.getGeneration() + ((spec.hasData("MAPSOModelInformation")) ? "/" + (BeanInspector.callIfAvailable(spec.getData("MAPSOModelInformation"), "getStringRepresentation", null)) : "") + ")"; 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 * Merge two species by adding the second to the first. Keep the longer
* history. The second species should be deactivated after merging. * history. The second species should be deactivated after merging.
* *
* @param pop1 * @param spec1
* @param pop2 * @param spec2
* @param plot
*/ */
protected void mergeToFirst(Population spec1, Population spec2, boolean plot) { protected void mergeToFirst(Population spec1, Population spec2, boolean plot) {
// System.out.println("Merging " + spec2.size() + " to " + spec1.size());
if (plot && (topologyPlot != null)) { if (plot && (topologyPlot != null)) {
plotLine(topologyPlot, spec1.getBestEAIndividual(), spec2.getBestEAIndividual()); plotLine(topologyPlot, spec1.getBestEAIndividual(), spec2.getBestEAIndividual());
} }

View File

@ -40,7 +40,6 @@ public class ClusteringHillClimbing implements InterfacePopulationChangedEventLi
InterfaceOptimizer, Serializable, InterfaceAdditionalPopulationInformer { InterfaceOptimizer, Serializable, InterfaceAdditionalPopulationInformer {
transient private InterfacePopulationChangedEventListener populationChangedEventListener; transient private InterfacePopulationChangedEventListener populationChangedEventListener;
public static final boolean TRACE = false;
transient private String identifier = ""; transient private String identifier = "";
private Population population = new Population(); private Population population = new Population();
private transient Population archive = new Population(); private transient Population archive = new Population();
@ -48,7 +47,6 @@ public class ClusteringHillClimbing implements InterfacePopulationChangedEventLi
private int hcEvalCycle = 1000; private int hcEvalCycle = 1000;
private int initialPopSize = 100; private int initialPopSize = 100;
private int loopCnt = 0; private int loopCnt = 0;
// private int baseEvalCnt = 0;
private int notifyGuiEvery = 50; private int notifyGuiEvery = 50;
private double sigmaClust = 0.01; private double sigmaClust = 0.01;
private double minImprovement = 0.000001; private double minImprovement = 0.000001;
@ -198,9 +196,6 @@ public class ClusteringHillClimbing implements InterfacePopulationChangedEventLi
evalsNow = hcEvalCycle; evalsNow = hcEvalCycle;
} }
do { do {
if (TRACE) {
System.out.println("evalCycle: " + hcEvalCycle + ", evals now: " + evalsNow);
}
popD = PostProcess.clusterLocalSearch(localSearchMethod, population, (AbstractOptimizationProblem) optimizationProblem, sigmaClust, evalsNow, 0.5, mutator); popD = PostProcess.clusterLocalSearch(localSearchMethod, population, (AbstractOptimizationProblem) optimizationProblem, sigmaClust, evalsNow, 0.5, mutator);
// (population, (AbstractOptimizationProblem)problem, sigmaClust, hcEvalCycle - (population.getFunctionCalls() % hcEvalCycle), 0.5); // (population, (AbstractOptimizationProblem)problem, sigmaClust, hcEvalCycle - (population.getFunctionCalls() % hcEvalCycle), 0.5);
if (popD.head().getFunctionCalls() == funCallsBefore) { if (popD.head().getFunctionCalls() == funCallsBefore) {
@ -210,21 +205,12 @@ public class ClusteringHillClimbing implements InterfacePopulationChangedEventLi
} while (popD.head().getFunctionCalls() == funCallsBefore); } while (popD.head().getFunctionCalls() == funCallsBefore);
improvement = popD.tail(); improvement = popD.tail();
population = popD.head(); population = popD.head();
if (TRACE) {
System.out.println("num inds after clusterLS: " + population.size());
}
popD.head().setGeneration(population.getGeneration() + 1); popD.head().setGeneration(population.getGeneration() + 1);
if (doReinitialization && (improvement < minImprovement)) { if (doReinitialization && (improvement < minImprovement)) {
if (TRACE) {
System.out.println("improvement below " + minImprovement);
}
if ((localSearchMethod != PostProcessMethod.hillClimber) || (mutator.getSigma() < stepSizeThreshold)) { // reinit! if ((localSearchMethod != PostProcessMethod.hillClimber) || (mutator.getSigma() < stepSizeThreshold)) { // reinit!
// is performed for nm and cma, and if hc has too low sigma // is performed for nm and cma, and if hc has too low sigma
if (TRACE) {
System.out.println("REINIT!!");
}
if (localSearchMethod == PostProcessMethod.hillClimber) { if (localSearchMethod == PostProcessMethod.hillClimber) {
mutator.setSigma(initialStepSize); mutator.setSigma(initialStepSize);
@ -252,12 +238,8 @@ public class ClusteringHillClimbing implements InterfacePopulationChangedEventLi
System.err.println("Invalid case in ClusteringHillClimbing!"); System.err.println("Invalid case in ClusteringHillClimbing!");
} }
mutator.setSigma(mutator.getSigma() * reduceFactor); mutator.setSigma(mutator.getSigma() * reduceFactor);
if (TRACE) {
System.out.println("mutation stepsize reduced to " + mutator.getSigma());
}
} }
} }
// System.out.println("funcalls: " + evalCnt);
this.firePropertyChangedEvent(Population.NEXT_GENERATION_PERFORMED); this.firePropertyChangedEvent(Population.NEXT_GENERATION_PERFORMED);
} }
@ -266,17 +248,10 @@ public class ClusteringHillClimbing implements InterfacePopulationChangedEventLi
public void registerPopulationStateChanged(Object source, String name) { public void registerPopulationStateChanged(Object source, String name) {
// The events of the interim hill climbing population will be caught here // The events of the interim hill climbing population will be caught here
if (name.compareTo(Population.FUN_CALL_INTERVAL_REACHED) == 0) { if (name.compareTo(Population.FUN_CALL_INTERVAL_REACHED) == 0) {
// if ((((Population)source).size() % 50) > 0) {
// System.out.println("bla");
// }
// set funcalls to real value // set funcalls to real value
population.setFunctionCalls(((Population) source).getFunctionCalls()); population.setFunctionCalls(((Population) source).getFunctionCalls());
// System.out.println("FunCallIntervalReached at " + (((Population)source).getFunctionCalls()));
this.firePropertyChangedEvent(Population.NEXT_GENERATION_PERFORMED); this.firePropertyChangedEvent(Population.NEXT_GENERATION_PERFORMED);
} }
// do not react to NextGenerationPerformed
//else System.err.println("ERROR, event was " + name);
} }
/** /**

View File

@ -91,7 +91,6 @@ import java.util.Formatter;
+ "in parallel, which are reclustered in each iteration based on the dynamic peak set.") + "in parallel, which are reclustered in each iteration based on the dynamic peak set.")
public class EsDpiNiching implements InterfaceOptimizer, Serializable, InterfaceAdditionalPopulationInformer, InterfacePopulationChangedEventListener { public class EsDpiNiching implements InterfaceOptimizer, Serializable, InterfaceAdditionalPopulationInformer, InterfacePopulationChangedEventListener {
private static final boolean TRACE = false, TRACE_DEMES = false;
private double nicheRadius = 0.3; private double nicheRadius = 0.3;
private int expectedPeaks = 5; private int expectedPeaks = 5;
private int explorerPeaks = 0; private int explorerPeaks = 0;
@ -250,7 +249,6 @@ public class EsDpiNiching implements InterfaceOptimizer, Serializable, Interface
population.incrFunctionCallsBy(peakOpts[i].getPopulation().getFunctionCalls()); 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) // 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) { if (getNumRndImmigrants() > 0) {
generateEvalImmigrants(getNumRndImmigrants()); generateEvalImmigrants(getNumRndImmigrants());
} }
@ -319,7 +317,6 @@ public class EsDpiNiching implements InterfaceOptimizer, Serializable, Interface
} }
r = 0.5 * Math.sqrt(dim); r = 0.5 * Math.sqrt(dim);
} }
// setNicheRadius(r*Math.pow(numExpectedPeaks, -1./(double)dim));
return r * Math.pow(numExpectedOptima, -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() { private int increaseExpectedPeaksCriterion() {
// if ((getPopulation().getGeneration() % 5) == 0) return 1;
// else return 0;
if (isDoNumPeakAdaption() && (archive.size() >= getExpectedPeaks())) { if (isDoNumPeakAdaption() && (archive.size() >= getExpectedPeaks())) {
return (int) Math.max(((double) getExpectedPeaks()) * 1.2, 2.); return (int) Math.max(((double) getExpectedPeaks()) * 1.2, 2.);
} else { } else {
@ -374,9 +369,6 @@ public class EsDpiNiching implements InterfaceOptimizer, Serializable, Interface
if (increaseExpectedPeaksCriterion() > 0) { if (increaseExpectedPeaksCriterion() > 0) {
addExpectedPeaks(increaseExpectedPeaksCriterion()); 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); ClusteringDynPeakIdent dpiClustering = new ClusteringDynPeakIdent(getExpectedPeaks(), getLambdaPerPeak(), nicheRadius, true, metric);
// perform dynamic peak identification resulting in the dynamic peak set dps // perform dynamic peak identification resulting in the dynamic peak set dps
dpiClustering.initClustering(population); dpiClustering.initClustering(population);
@ -386,20 +378,12 @@ public class EsDpiNiching implements InterfaceOptimizer, Serializable, Interface
peakPopSet[i].removePopulationChangedEventListener(this); peakPopSet[i].removePopulationChangedEventListener(this);
} }
setGeneration(population.getGeneration(), peakPopSet); setGeneration(population.getGeneration(), peakPopSet);
if (TRACE_DEMES) {
printDemes("After clustering: ", peakPopSet);
}
int curNumPeaks = peakPopSet.length - 1; int curNumPeaks = peakPopSet.length - 1;
// boolean copyHashFromParents=true;
// transfer population hash data along the peaks -> for each peak chose the original last population // transfer population hash data along the peaks -> for each peak chose the original last population
// and transfer the data to the new cluster // and transfer the data to the new cluster
// if (copyHashFromParents) {
copyDataFromParents(peakPopSet); copyDataFromParents(peakPopSet);
// } else {
// copyDataFromClosest(clusteredPeakPops);
// }
int reqNewPeaks = 0; int reqNewPeaks = 0;
if (curNumPeaks < getExpectedPeaks()) { 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) // add missing and explorer peaks as new random individuals (or old unclustered ones)
peakPopSet = generateMissingSpecies(peakPopSet, getMuPerPeak(), reqNewPeaks, false); peakPopSet = generateMissingSpecies(peakPopSet, getMuPerPeak(), reqNewPeaks, false);
if (TRACE_DEMES) {
printDemes("After expansion: ", peakPopSet);
}
if (archive != null && (archive.size() > 0) && isReinitOnCollision()) { if (archive != null && (archive.size() > 0) && isReinitOnCollision()) {
double origNicheRad = dpiClustering.getNicheRadius(); double origNicheRad = dpiClustering.getNicheRadius();
dpiClustering.setNicheRadius(collisionDetNicheRadius); 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 // the new found species is actually better than the archived solution
archive.set(i, peakPopSet[assoc[i]].getBestEAIndividual().clone()); // replace archived indy 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()); peakPopSet[assoc[i]] = initRandomPeakPop(getMuPerPeak());
} }
} }
dpiClustering.setNicheRadius(origNicheRad); 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; plot = null;
// now generate the lambda offsprings // now generate the lambda offsprings
// nextGeneration = this.generateEvalChildren(dps); // create lambda new ones from mu parents // 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())) { 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." // 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(); AbstractEAIndividual bestOther = (AbstractEAIndividual) selectBestFromOtherSpecies(clustIndex, peakPopSet).clone();
if (TRACE) {
System.out.println("Adding best from other species: " + bestOther);
}
curSpecies.add(bestOther); curSpecies.add(bestOther);
} else if (curSpecies.size() == 0) { } else if (curSpecies.size() == 0) {
System.err.println("Warning, empty niche population in EsDpiNiching!"); System.err.println("Warning, empty niche population in EsDpiNiching!");
@ -497,19 +458,10 @@ public class EsDpiNiching implements InterfaceOptimizer, Serializable, Interface
if (doDraw(population.getGeneration())) { if (doDraw(population.getGeneration())) {
drawPeakPop("" + clustIndex, curSpecies); drawPeakPop("" + clustIndex, curSpecies);
} }
if (TRACE) {
System.out.println("Optimizing cluster index " + (clustIndex) + ", size " + curSpecies.size());
}
peakOpts[clustIndex - 1].optimize(); // !!!!!!!! Actual optimization step peakOpts[clustIndex - 1].optimize(); // !!!!!!!! Actual optimization step
optimizedSpecies = peakOpts[clustIndex - 1].getPopulation(); optimizedSpecies = peakOpts[clustIndex - 1].getPopulation();
optimizedSpecies.putData(origPeakIndyKey, curPeak); optimizedSpecies.putData(origPeakIndyKey, curPeak);
population.incrFunctionCallsBy(optimizedSpecies.size()); 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 ! // 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())); 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 if (doEtaPreselection) { // this basically replaces ES-environment selection
// select the eta best from the offspring per peak population // select the eta best from the offspring per peak population
// fill up to muPerPeak by adding from the old 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!"); System.err.println("Warning: fewer clusters than expected peaks in EsDpiNiching!");
offspring.clear(); // empty set to avoid duplicates! offspring.clear(); // empty set to avoid duplicates!
} else { } else {
if (TRACE) {
System.out.println("EtaPresel: from " + offspring.size() + " offspring selecting " + eta);
}
Population selected = selBest.selectFrom(offspring, eta); Population selected = selBest.selectFrom(offspring, eta);
if (!selected.isSubSet(offspring)) { if (!selected.isSubSet(offspring)) {
System.err.println("fatal problem in EsDpiNiching!!!"); System.err.println("fatal problem in EsDpiNiching!!!");
@ -558,33 +492,16 @@ public class EsDpiNiching implements InterfaceOptimizer, Serializable, Interface
int delta = muPerPeak - eta; int delta = muPerPeak - eta;
if (delta > 0) { if (delta > 0) {
Population filterPeakPop = peakPopSet[i + 1].filter(selected); 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 // (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. // 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); selected.addPopulation(selBest.selectFrom(filterPeakPop, Math.min(delta, filterPeakPop.size())), false);
if (selected.size() < muPerPeak && (addLonersToPeaks)) { if (selected.size() < muPerPeak && (addLonersToPeaks)) {
delta = Math.min(muPerPeak - selected.size(), loners.size()); delta = Math.min(muPerPeak - selected.size(), loners.size());
if (TRACE) {
System.out.println("filling up with lucky loners: " + delta);
}
// fill up with loner indies // fill up with loner indies
SelectRandom selRnd = new SelectRandom(false); // no duplicates wanted! SelectRandom selRnd = new SelectRandom(false); // no duplicates wanted!
Population luckyLosers = selRnd.selectFrom(loners, delta); Population luckyLosers = selRnd.selectFrom(loners, delta);
selected.addPopulation(luckyLosers, true); selected.addPopulation(luckyLosers, true);
loners.removeMembers(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(); 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) { if (doDraw(population.getGeneration()) && archive != null) {
for (int i = 0; i < this.archive.size(); i++) { for (int i = 0; i < this.archive.size(); i++) {
ClusterBasedNichingEA.plotIndy(plot, 'x', (InterfaceDataTypeDouble) archive.get(i)); ClusterBasedNichingEA.plotIndy(plot, 'x', (InterfaceDataTypeDouble) archive.get(i));
@ -605,7 +522,6 @@ public class EsDpiNiching implements InterfaceOptimizer, Serializable, Interface
generateEvalImmigrants(getNumRndImmigrants()); generateEvalImmigrants(getNumRndImmigrants());
} }
collectPopulationIncGen(population, peakOpts, randomNewIndies); 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) { private Population deactivateSpecies(int clustIndex, boolean resetRandomly) {
@ -634,7 +550,6 @@ public class EsDpiNiching implements InterfaceOptimizer, Serializable, Interface
Population origPop = peakOpts[origEsPop].getPopulation(); Population origPop = peakOpts[origEsPop].getPopulation();
clusteredPeakPops[i].copyHashData(origPop); clusteredPeakPops[i].copyHashData(origPop);
clusteredPeakPops[i].SetHistory(origPop.getHistory()); // copy the history for deactivation! 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 } else { // ok in the first iteration of if the indy was a random immigrant
if (population.getGeneration() > 1 && (getNumRndImmigrants() == 0)) { if (population.getGeneration() > 1 && (getNumRndImmigrants() == 0)) {
System.err.println("Error, empty original es pop ID!"); 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<peakOpts.length; i++) {
// Population peakPop = peakOpts[i].getPopulation();
// indy = (AbstractEAIndividual) peakPop.getData(origPeakIndyKey);
// if (indy!=null) centers.add(indy);
// else centers.add(peakOpts[i].getPopulation().getCenterIndy());
// }
// for (int i=1; i<clusteredPeakPops.length; i++) {
// indy = clusteredPeakPops[i].getBestEAIndividual();
// Pair<Integer,Double> 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) { private void printDemes(String prefix, Population[] peakPops) {
System.out.print(prefix + " demes: "); System.out.print(prefix + " demes: ");
for (int i = 0; i < peakPops.length; i++) { 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++) { for (int i = 0; i < origClusters.length; i++) {
newClusters[i] = origClusters[i]; newClusters[i] = origClusters[i];
} }
if (TRACE) {
System.out.println("Generated missing peak species...");
}
return newClusters; return newClusters;
} }
} }
@ -776,9 +664,6 @@ public class EsDpiNiching implements InterfaceOptimizer, Serializable, Interface
problem.initializePopulation(randomNewIndies); problem.initializePopulation(randomNewIndies);
problem.evaluate(randomNewIndies); problem.evaluate(randomNewIndies);
population.incrFunctionCallsBy(cnt); population.incrFunctionCallsBy(cnt);
if (TRACE) {
System.out.println("evaluated immigrants: " + randomNewIndies.size());
}
} else { } else {
randomNewIndies = null; randomNewIndies = null;
} }
@ -802,9 +687,6 @@ public class EsDpiNiching implements InterfaceOptimizer, Serializable, Interface
if (rndIndex == i) { if (rndIndex == i) {
rndIndex++; rndIndex++;
} }
if (TRACE) {
System.out.println("selected spec index " + rndIndex);
}
return clusteredSpecies[rndIndex].getBestEAIndividual(); return clusteredSpecies[rndIndex].getBestEAIndividual();
} }
@ -828,7 +710,6 @@ public class EsDpiNiching implements InterfaceOptimizer, Serializable, Interface
} }
ClusterBasedNichingEA.plotPopConnected(plot, npop); ClusterBasedNichingEA.plotPopConnected(plot, npop);
plot.drawIndividual(1, 0, "", npop.getBestEAIndividual()); plot.drawIndividual(1, 0, "", npop.getBestEAIndividual());
// plot.drawPopulation(prefix, npop);
} catch (Exception e) { } catch (Exception e) {
plot = null; 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 // (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. // if a cluster had a size of 1 AND parents may survive due to elitism.
pop.addPopulation(pi, false); 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) { if (immigrants != null) {
immigrants.putDataAllIndies(originalPeakPop, new Integer(-2)); immigrants.putDataAllIndies(originalPeakPop, -2);
pop.addPopulation(immigrants, true); pop.addPopulation(immigrants, true);
} }
pop.incrGeneration(); pop.incrGeneration();
pop.synchSize(); pop.synchSize();
if (TRACE) {
System.out.println("Collected " + pop.size() + " indies in pop.");
}
} }
/** /**

View File

@ -1,6 +1,5 @@
package eva2.optimization.strategies; package eva2.optimization.strategies;
import eva2.gui.BeanInspector;
import eva2.optimization.go.InterfacePopulationChangedEventListener; import eva2.optimization.go.InterfacePopulationChangedEventListener;
import eva2.optimization.individuals.AbstractEAIndividual; import eva2.optimization.individuals.AbstractEAIndividual;
import eva2.optimization.individuals.InterfaceDataTypeDouble; 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 // These variables are necessary for the more complex LectureGUI enviroment
transient private String identifier = ""; transient private String identifier = "";
private Population population; private Population population;
private static boolean TRACE = false;
private static final String lockKey = "gdaLockDataKey"; private static final String lockKey = "gdaLockDataKey";
private static final String lastFitnessKey = "gdaLastFitDataKey"; private static final String lastFitnessKey = "gdaLastFitDataKey";
private static final String stepSizeKey = "gdaStepSizeDataKey"; private static final String stepSizeKey = "gdaStepSizeDataKey";
@ -155,10 +153,8 @@ public class GradientDescentAlgorithm implements InterfaceOptimizer, java.io.Ser
int[] lock = (int[]) indy.getData(lockKey); int[] lock = (int[]) indy.getData(lockKey);
double indystepsize = ((Double) indy.getData(stepSizeKey)).doubleValue(); double indystepsize = ((Double) indy.getData(stepSizeKey)).doubleValue();
// System.out.println("indystepsize" + indystepsize);
if ((this.optimizationProblem instanceof InterfaceFirstOrderDerivableProblem) && (indy instanceof InterfaceDataTypeDouble)) { if ((this.optimizationProblem instanceof InterfaceFirstOrderDerivableProblem) && (indy instanceof InterfaceDataTypeDouble)) {
// Hashtable history = (Hashtable) indyhash.get(indy);
for (int iterations = 0; iterations < this.iterations; iterations++) { for (int iterations = 0; iterations < this.iterations; iterations++) {
double[] oldgradient = indy.hasData(gradientKey) ? (double[]) indy.getData(gradientKey) : null; 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[] oldchange = null;
double[] gradient = ((InterfaceFirstOrderDerivableProblem) optimizationProblem).getFirstOrderGradients(params); 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 if ((oldgradient != null) && (wstepsize != null)) { // LOCAL adaption
for (int li = 0; li < wstepsize.length; li++) { for (int li = 0; li < wstepsize.length; li++) {
double prod = gradient[li] * oldgradient[li]; double prod = gradient[li] * oldgradient[li];
@ -180,7 +173,6 @@ public class GradientDescentAlgorithm implements InterfaceOptimizer, java.io.Ser
wstepsize[li] = (wstepsize[li] < localminstepsize) ? localminstepsize : wstepsize[li]; wstepsize[li] = (wstepsize[li] < localminstepsize) ? localminstepsize : wstepsize[li];
wstepsize[li] = (wstepsize[li] > localmaxstepsize) ? localmaxstepsize : wstepsize[li]; wstepsize[li] = (wstepsize[li] > localmaxstepsize) ? localmaxstepsize : wstepsize[li];
// System.out.println("wstepsize "+ li + " " + wstepsize[li]);
} }
} }
@ -251,11 +243,8 @@ public class GradientDescentAlgorithm implements InterfaceOptimizer, java.io.Ser
if (this.recovery) { if (this.recovery) {
for (int i = 0; i < this.population.size(); i++) { for (int i = 0; i < this.population.size(); i++) {
indy = ((AbstractEAIndividual) this.population.get(i)); indy = ((AbstractEAIndividual) this.population.get(i));
// Hashtable history = (Hashtable) indyhash.get(indy);
if (indy.getFitness()[0] > recoverythreshold) { if (indy.getFitness()[0] > recoverythreshold) {
if (TRACE) {
System.out.println("Gradient Descent: Fitness critical:" + indy.getFitness()[0]);
}
((InterfaceDataTypeDouble) indy).setDoublePhenotype((double[]) indy.getData(oldParamsKey)); ((InterfaceDataTypeDouble) indy).setDoublePhenotype((double[]) indy.getData(oldParamsKey));
double[] changes = (double[]) indy.getData(changesKey); double[] changes = (double[]) indy.getData(changesKey);
int[] lock = (int[]) indy.getData(lockKey); int[] lock = (int[]) indy.getData(lockKey);
@ -282,8 +271,7 @@ public class GradientDescentAlgorithm implements InterfaceOptimizer, java.io.Ser
//System.out.println("gsa main"); //System.out.println("gsa main");
for (int i = 0; i < this.population.size(); i++) { for (int i = 0; i < this.population.size(); i++) {
indy = ((AbstractEAIndividual) this.population.get(i)); indy = ((AbstractEAIndividual) this.population.get(i));
// Hashtable history = (Hashtable) indyhash.get(indy);
// if (history == null) break;
if (indy.getData(lastFitnessKey) != null) { if (indy.getData(lastFitnessKey) != null) {
double lastfit = ((Double) indy.getData(lastFitnessKey)).doubleValue(); double lastfit = ((Double) indy.getData(lastFitnessKey)).doubleValue();
double indystepsize = ((Double) indy.getData(stepSizeKey)).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); //System.out.println("newstepsize" + indystepsize);
indystepsize = (indystepsize > globalmaxstepsize) ? globalmaxstepsize : indystepsize; indystepsize = (indystepsize > globalmaxstepsize) ? globalmaxstepsize : indystepsize;
indystepsize = (indystepsize < globalminstepsize) ? globalminstepsize : indystepsize; indystepsize = (indystepsize < globalminstepsize) ? globalminstepsize : indystepsize;
indy.putData(stepSizeKey, new Double(indystepsize)); indy.putData(stepSizeKey, indystepsize);
} }
//System.out.println("newstepsize in bounds" + indystepsize); //System.out.println("newstepsize in bounds" + indystepsize);

View File

@ -50,7 +50,6 @@ public class IslandModelEA implements InterfacePopulationChangedEventListener, I
transient private Plot plot = null; transient private Plot plot = null;
transient private String identifier = ""; transient private String identifier = "";
transient private InterfacePopulationChangedEventListener populationChangedEventListener; transient private InterfacePopulationChangedEventListener populationChangedEventListener;
transient private final boolean TRACE = false;
public IslandModelEA() { public IslandModelEA() {
} }
@ -203,15 +202,9 @@ public class IslandModelEA implements InterfacePopulationChangedEventListener, I
for (int i = 0; i < this.islands.length; i++) { for (int i = 0; i < this.islands.length; i++) {
if (this.islands[i].getPopulation().size() > 0) { if (this.islands[i].getPopulation().size() > 0) {
this.islands[i].optimize(); this.islands[i].optimize();
if (TRACE) {
System.out.println(BeanInspector.toString(islands[i].getPopulation()));
}
} else { } else {
this.islands[i].getPopulation().incrGeneration(); this.islands[i].getPopulation().incrGeneration();
} }
if (TRACE) {
System.out.println("----");
}
} }
this.population.incrGeneration(); this.population.incrGeneration();
if ((this.population.getGeneration() % this.migrationRate) == 0) { if ((this.population.getGeneration() % this.migrationRate) == 0) {

View File

@ -34,9 +34,6 @@ public class MemeticAlgorithm implements InterfaceOptimizer,
private int subsetsize = 5; private int subsetsize = 5;
private int globalSearchIterations = 1; private int globalSearchIterations = 1;
private boolean lamarckism = true; private boolean lamarckism = true;
// int counter = 0; !?
// int maxfunctioncalls = 1000; !?
private boolean TRACE = false;
private String identifier = ""; private String identifier = "";
private InterfaceOptimizationProblem optimizationProblem = new F1Problem(); private InterfaceOptimizationProblem optimizationProblem = new F1Problem();
private InterfaceOptimizer globalOptimizer = new GeneticAlgorithm(); private InterfaceOptimizer globalOptimizer = new GeneticAlgorithm();
@ -94,20 +91,13 @@ public class MemeticAlgorithm implements InterfaceOptimizer,
@Override @Override
public void optimize() { public void optimize() {
if (TRACE) {
System.out.println("global search");
}
this.globalOptimizer.optimize(); this.globalOptimizer.optimize();
if ((globalSearchIterations > 0) && (((this.globalOptimizer.getPopulation().getGeneration() % this.globalSearchIterations) == 0)) if ((globalSearchIterations > 0) && (((this.globalOptimizer.getPopulation().getGeneration() % this.globalSearchIterations) == 0))
&& (this.localSearchSteps > 0) && (this.localSearchSteps > 0)
&& (this.optimizationProblem instanceof InterfaceLocalSearchable)) { && (this.optimizationProblem instanceof InterfaceLocalSearchable)) {
// here the local search is performed // here the local search is performed
if (TRACE) {
System.out.println("Performing local search on " + subsetsize
+ " individuals.");
}
Population gop = this.globalOptimizer.getPopulation(); Population gop = this.globalOptimizer.getPopulation();
Population subset = selectorPlug.selectFrom(gop, subsetsize); Population subset = selectorPlug.selectFrom(gop, subsetsize);
Population subsetclone = new Population(); Population subsetclone = new Population();
@ -164,17 +154,9 @@ public class MemeticAlgorithm implements InterfaceOptimizer,
gop.setFunctionCalls(gop.getFunctionCalls() gop.setFunctionCalls(gop.getFunctionCalls()
+ (int) Math.round(localSearchSteps * cost * subset.size())); + (int) Math.round(localSearchSteps * cost * subset.size()));
if (TRACE) {
System.out.println("Population size after local search:" + gop.size());
}
this.setPopulation(gop); this.setPopulation(gop);
} }
if (TRACE) {
System.out.println("function calls"
+ this.globalOptimizer.getPopulation().getFunctionCalls());
}
this.firePropertyChangedEvent(Population.NEXT_GENERATION_PERFORMED); this.firePropertyChangedEvent(Population.NEXT_GENERATION_PERFORMED);
} }
@ -205,9 +187,6 @@ public class MemeticAlgorithm implements InterfaceOptimizer,
*/ */
protected void firePropertyChangedEvent(String name) { protected void firePropertyChangedEvent(String name) {
if (this.populationChangedEventListener != null) { if (this.populationChangedEventListener != null) {
if (TRACE) {
System.out.println("firePropertyChangedEvent MA");
}
this.populationChangedEventListener.registerPopulationStateChanged(this, name); this.populationChangedEventListener.registerPopulationStateChanged(this, name);
} }
} }

View File

@ -47,7 +47,6 @@ public class ParticleFilterOptimization implements InterfaceOptimizer, java.io.S
transient private int indCount = 0; transient private int indCount = 0;
transient private InterfacePopulationChangedEventListener populationChangedEventListener; transient private InterfacePopulationChangedEventListener populationChangedEventListener;
transient Plot myPlot = null; transient Plot myPlot = null;
public static final boolean TRACE = false;
public ParticleFilterOptimization() { public ParticleFilterOptimization() {
if (withShow) { if (withShow) {
@ -167,9 +166,6 @@ public class ParticleFilterOptimization implements InterfaceOptimizer, java.io.S
parents.add(immi); parents.add(immi);
} }
parents.synchSize(); parents.synchSize();
if (TRACE) {
System.out.println("Added " + i + " random individuals");
}
} }
parents.setFunctionCalls(pop.getFunctionCalls()); parents.setFunctionCalls(pop.getFunctionCalls());
@ -249,14 +245,9 @@ public class ParticleFilterOptimization implements InterfaceOptimizer, java.io.S
// predict step // predict step
predict(nextGeneration); 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); population = evaluatePopulation(nextGeneration);
// collectStatistics(population);
this.firePropertyChangedEvent(Population.NEXT_GENERATION_PERFORMED); this.firePropertyChangedEvent(Population.NEXT_GENERATION_PERFORMED);
} }

View File

@ -103,7 +103,6 @@ public class ParticleSwarmOptimization implements InterfaceOptimizer, java.io.Se
// parameter for exponential moving average // parameter for exponential moving average
private int emaPeriods = 0; private int emaPeriods = 0;
// for debugging only // for debugging only
transient private static boolean TRACE = false;
transient protected boolean show = false; transient protected boolean show = false;
transient protected Plot plot; transient protected Plot plot;
private boolean externalInitialPop = false; 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++) { for (int i = 0; i < this.population.size(); i++) {
double[] succVel = (double[]) population.getEAIndividual(i).getData(lastSuccessKey); double[] succVel = (double[]) population.getEAIndividual(i).getData(lastSuccessKey);
if (succVel != null) { if (succVel != null) {
successes.add(new Integer(i)); successes.add(i);
} }
} }
if (successes.size() > 0) { 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. * Do some preparations in the beginning of the loop.
*/ */
protected void startOptimize() { 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) { if (this.show) {
this.show(); this.show();
} }
@ -1580,9 +1570,6 @@ public class ParticleSwarmOptimization implements InterfaceOptimizer, java.io.Se
initIndividualMemory(indy); initIndividualMemory(indy);
indy.putData(indexKey, i); indy.putData(indexKey, i);
indy.setIndividualIndex(i); indy.setIndividualIndex(i);
if (TRACE) {
System.err.println("initialize indy " + i + " " + AbstractEAIndividual.getDefaultDataString(indy));
}
} }
} }
} }

View File

@ -70,7 +70,6 @@ public class ScatterSearch implements InterfaceOptimizer, java.io.Serializable,
private double nelderMeadInitPerturbation = 0.01; private double nelderMeadInitPerturbation = 0.01;
private double improvementEpsilon = 0.1; // minimal relative fitness improvement for a candidate to be taken over into the refset private double improvementEpsilon = 0.1; // minimal relative fitness improvement for a candidate to be taken over into the refset
private double minDiversityEpsilon = 0.0001; // minimal phenotypic distance for a candidate to be taken over into the refset private double minDiversityEpsilon = 0.0001; // minimal phenotypic distance for a candidate to be taken over into the refset
private static boolean TRACE = false;
public ScatterSearch() { public ScatterSearch() {
GenericObjectEditor.setHideProperty(this.getClass(), "population", true); GenericObjectEditor.setHideProperty(this.getClass(), "population", true);
@ -137,14 +136,9 @@ public class ScatterSearch implements InterfaceOptimizer, java.io.Serializable,
*/ */
private void initRefSet(Population pop) { private void initRefSet(Population pop) {
optimizationProblem.evaluate(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 = getRefSetFitBased(new Population(refSetSize), pop);
refSet.incrFunctionCallsBy(pop.size()); refSet.incrFunctionCallsBy(pop.size());
if (TRACE) {
System.out.println("ref set size " + refSet.size() + " avg dist " + refSet.getPopulationMeasures()[0]);
}
refSet.addPopulationChangedEventListener(this); refSet.addPopulationChangedEventListener(this);
refSet.setNotifyEvalInterval(generationCycle); refSet.setNotifyEvalInterval(generationCycle);
} }
@ -166,9 +160,6 @@ public class ScatterSearch implements InterfaceOptimizer, java.io.Serializable,
} }
probDim = (Integer) dim; probDim = (Integer) dim;
range = ((InterfaceDataTypeDouble) template).getDoubleRange(); 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(); int funCallsStart = refSet.getFunctionCalls();
do { do {
if (combinations == null || combinations.size() == 0) { if (combinations == null || combinations.size() == 0) {
if (TRACE) {
System.out.println("Improvements: " + lastImprovementCount);
System.out.println("---------- best: " + refSet.getBestEAIndividual().getFitness(0));
}
combinations = generateCombinations(refSet); combinations = generateCombinations(refSet);
oldRefSet = (Population) refSet.clone(); oldRefSet = (Population) refSet.clone();
lastImprovementCount = 0; lastImprovementCount = 0;
} }
if (TRACE) {
System.out.println("No combinations: " + combinations.size());
}
if (combinations.size() > 0) { if (combinations.size() > 0) {
updateRefSet(refSet, combinations, oldRefSet); updateRefSet(refSet, combinations, oldRefSet);
} }
} while (refSet.getFunctionCalls() - funCallsStart < generationCycle); } while (refSet.getFunctionCalls() - funCallsStart < generationCycle);
optimizationProblem.evaluatePopulationEnd(refSet); optimizationProblem.evaluatePopulationEnd(refSet);
if (TRACE) {
System.out.println("Improvements: " + lastImprovementCount);
}
} }
private boolean isDoLocalSolver(AbstractEAIndividual cand, Population refSet) { private boolean isDoLocalSolver(AbstractEAIndividual cand, Population refSet) {
@ -271,15 +250,9 @@ public class ScatterSearch implements InterfaceOptimizer, java.io.Serializable,
Population diversifiedPop = diversify(); Population diversifiedPop = diversify();
int keep = refSetSize / 2; int keep = refSetSize / 2;
Population newRefSet = refSet.cloneWithoutInds(); 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)); 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(); int h = newRefSet.size();
ArrayList<double[]> distVects = new ArrayList<double[]>(); ArrayList<double[]> distVects = new ArrayList<double[]>();
@ -364,10 +337,6 @@ public class ScatterSearch implements InterfaceOptimizer, java.io.Serializable,
AbstractEAIndividual bestCand = candidates.getEAIndividual(bestIndex); AbstractEAIndividual bestCand = candidates.getEAIndividual(bestIndex);
AbstractEAIndividual worstRef = refSet.getWorstEAIndividual(); AbstractEAIndividual worstRef = refSet.getWorstEAIndividual();
if (TRACE) {
System.out.println("best cand: " + bestCand.getFitness(0));
}
if (isDoLocalSolver(bestCand, refSet)) { if (isDoLocalSolver(bestCand, refSet)) {
Pair<AbstractEAIndividual, Integer> lsRet = localSolver(bestCand, localSearchSteps); Pair<AbstractEAIndividual, Integer> lsRet = localSolver(bestCand, localSearchSteps);
if ((Math.abs(lsRet.tail() - localSearchSteps) / localSearchSteps) > 0.05) { if ((Math.abs(lsRet.tail() - localSearchSteps) / localSearchSteps) > 0.05) {
@ -375,33 +344,21 @@ public class ScatterSearch implements InterfaceOptimizer, java.io.Serializable,
} }
bestCand = lsRet.head(); bestCand = lsRet.head();
refSet.incrFunctionCallsBy(lsRet.tail()); refSet.incrFunctionCallsBy(lsRet.tail());
if (TRACE) {
System.out.println("best cand after: " + bestCand.getFitness(0));
}
} }
if (bestCand.isDominatingEqual(worstRef)) { if (bestCand.isDominatingEqual(worstRef)) {
if (TRACE) {
System.out.println("cand is dominating worst ref!");
}
if (diversityCriterionFulfilled(bestCand, refSet, oldRefSet)) { if (diversityCriterionFulfilled(bestCand, refSet, oldRefSet)) {
// System.out.println("diversity criterion is fulfilled! replacing fit " + worstRef.getFitness(0));
int replIndex = refSet.indexOf(worstRef); int replIndex = refSet.indexOf(worstRef);
refSet.set(replIndex, bestCand); refSet.set(replIndex, bestCand);
lastImprovementCount++; lastImprovementCount++;
} else if (bestCand.isDominating(refSet.getBestEAIndividual())) { } else if (bestCand.isDominating(refSet.getBestEAIndividual())) {
// exception: always accept best solution found so far // exception: always accept best solution found so far
int closestIndex = getClosestIndy(bestCand, refSet); int closestIndex = getClosestIndy(bestCand, refSet);
// if (TRACE) System.out.println("replacing due to best fit");
refSet.set(closestIndex, bestCand); refSet.set(closestIndex, bestCand);
lastImprovementCount++; lastImprovementCount++;
} }
// System.out.println("Improvements: " + lastImprovementCount);
candidates.remove(bestIndex); candidates.remove(bestIndex);
} else { } 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 // 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 // so we can just clear the rest of the candidates
if (!doLocalSearch && (bestCand.getFitness().length == 1)) { if (!doLocalSearch && (bestCand.getFitness().length == 1)) {
@ -422,7 +379,6 @@ public class ScatterSearch implements InterfaceOptimizer, java.io.Serializable,
private Pair<AbstractEAIndividual, Integer> localSolverHC(AbstractEAIndividual cand, int hcSteps) { private Pair<AbstractEAIndividual, Integer> localSolverHC(AbstractEAIndividual cand, int hcSteps) {
// use HC for a start... // use HC for a start...
// double[] fitBefore = cand.getFitness();
Population hcPop = new Population(1); Population hcPop = new Population(1);
hcPop.add(cand); hcPop.add(cand);
int stepsDone = PostProcess.processWithHC(hcPop, optimizationProblem, hcSteps); 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 for (int i = 0; i < half - 1; i++) { // better-better
AbstractEAIndividual indy1 = refSorted.getEAIndividual(i); AbstractEAIndividual indy1 = refSorted.getEAIndividual(i);
for (int j = i + 1; j < half; j++) { for (int j = i + 1; j < half; j++) {
// if (TRACE) System.out.println("combi T bb, " + i+ "/" + j);
AbstractEAIndividual indy2 = refSorted.getEAIndividual(j); AbstractEAIndividual indy2 = refSorted.getEAIndividual(j);
combs.add(combineTypeOne(indy1, indy2)); combs.add(combineTypeOne(indy1, indy2));
combs.add(combineTypeTwo(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 for (int i = 0; i < half; i++) { // better-worse
AbstractEAIndividual indy1 = refSorted.getEAIndividual(i); AbstractEAIndividual indy1 = refSorted.getEAIndividual(i);
for (int j = half; j < refSet.size(); j++) { for (int j = half; j < refSet.size(); j++) {
// if (TRACE) System.out.println("combi T bw, " + i+ "/" + j);
AbstractEAIndividual indy2 = refSorted.getEAIndividual(j); AbstractEAIndividual indy2 = refSorted.getEAIndividual(j);
combs.add(combineTypeOne(indy1, indy2)); combs.add(combineTypeOne(indy1, indy2));
combs.add(combineTypeTwo(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 for (int i = half; i < refSet.size() - 1; i++) { // worse-worse
AbstractEAIndividual indy1 = refSorted.getEAIndividual(i); AbstractEAIndividual indy1 = refSorted.getEAIndividual(i);
for (int j = i + 1; j < refSet.size(); j++) { for (int j = i + 1; j < refSet.size(); j++) {
// if (TRACE) System.out.println("combi T ww, " + i+ "/" + j);
AbstractEAIndividual indy2 = refSorted.getEAIndividual(j); AbstractEAIndividual indy2 = refSorted.getEAIndividual(j);
combs.add(combineTypeTwo(indy1, indy2)); combs.add(combineTypeTwo(indy1, indy2));
if (RNG.flipCoin(0.5)) { if (RNG.flipCoin(0.5)) {
@ -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; return combs;
} }
@ -649,9 +598,7 @@ public class ScatterSearch implements InterfaceOptimizer, java.io.Serializable,
pop.add(createDiverseIndy(freq)); pop.add(createDiverseIndy(freq));
} }
pop.setTargetSize(poolSize); pop.setTargetSize(poolSize);
if (TRACE) {
System.out.println("created diverse pop size " + pop.size());
}
return pop; return pop;
} }

View File

@ -134,7 +134,6 @@ import java.util.List;
@Description("TRIBES: a parameter free PSO implementation by Maurice Clerc.") @Description("TRIBES: a parameter free PSO implementation by Maurice Clerc.")
public class Tribes implements InterfaceOptimizer, java.io.Serializable { public class Tribes implements InterfaceOptimizer, java.io.Serializable {
public static final boolean TRACE = false;
protected String identifier = "TRIBES"; protected String identifier = "TRIBES";
transient private InterfacePopulationChangedEventListener listener = null; transient private InterfacePopulationChangedEventListener listener = null;
protected AbstractOptimizationProblem optimizationProblem; protected AbstractOptimizationProblem optimizationProblem;
@ -322,16 +321,7 @@ public class Tribes implements InterfaceOptimizer, java.io.Serializable {
} }
optimizationProblem.evaluatePopulationEnd(population); optimizationProblem.evaluatePopulationEnd(population);
// this.population.incrFunctionCallsby(evals);
this.population.incrGeneration(); 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<population.size(); i++) System.out.println(" * "+((TribesExplorer)population.get(i)).getStringRepresentation());
System.out.println(" best: " + population.getBestEAIndividual().getStringRepresentation() + " - " + population.getBestEAIndividual().getFitness(0));
System.out.println("swarm contains " + swarm.numParticles() + " particles in iteration " + iter);
}
} }
private void plotAll(Population pop) { private void plotAll(Population pop) {

View File

@ -11,7 +11,6 @@ public class TribesPosition implements java.io.Serializable {
* *
*/ */
private static final long serialVersionUID = 1L; private static final long serialVersionUID = 1L;
private boolean TRACE = false;
double x[]; double x[];
int[][] maxIsoLink = null; int[][] maxIsoLink = null;
double[] fitness; double[] fitness;
@ -23,22 +22,6 @@ public class TribesPosition implements java.io.Serializable {
fitness = new double[1];// new double[maxFunctionNb]; // TODO fitness = new double[1];// new double[maxFunctionNb]; // TODO
} }
// public TribesPosition clone(TribesPosition position, int fitnessSize) {
// // TODO this method might better vanish
// int n;
// // Pour remplacer "implements Cloneable"
// TribesPosition Clone = new TribesPosition(x.length, fitness.length);
// Clone.Dimension = position.Dimension;
// System.arraycopy(position.x, 0, Clone.x, 0, position.Dimension);
// for (n = 0; n < fitnessSize; n++) {
// Clone.fitness[n] = position.fitness[n];
// }
//
// Clone.totalError = position.totalError;
// Clone.isolation=position.isolation;
// return Clone;
// }
@Override @Override
public TribesPosition clone() { public TribesPosition clone() {
// Pour remplacer "implements Cloneable" // Pour remplacer "implements Cloneable"
@ -695,9 +678,6 @@ public class TribesPosition implements java.io.Serializable {
No need of a very precise solution No need of a very precise solution
*/ */
if (TRACE) {
System.out.println("sunny start");
}
// INITIALISATION // INITIALISATION
for (n = 0; n < swarm.size; n++) { for (n = 0; n < swarm.size; n++) {
@ -835,9 +815,7 @@ public class TribesPosition implements java.io.Serializable {
System.out.print(swarm.Best.position.x[d]+" "); System.out.print(swarm.Best.position.x[d]+" ");
*/ */
swarm.bestMem.getPos().isolation = swarm.bestMem.getPos().fitness[0]; swarm.bestMem.getPos().isolation = swarm.bestMem.getPos().fitness[0];
if (TRACE) {
System.out.println("sunny end, ret " + swarm.bestMem.getPos().toString());
}
return swarm.bestMem.getPos(); return swarm.bestMem.getPos();
} }

View File

@ -612,14 +612,8 @@ public class TribesSwarm implements java.io.Serializable {
TribesPosition posTemp = new TribesPosition(range.length); TribesPosition posTemp = new TribesPosition(range.length);
double[] rand_i; double[] rand_i;
if (Tribes.TRACE) {
System.out.println("+ generateExplorer option " + option);
}
switch (option) { switch (option) {
case 3: // around a "center" case 3: // around a "center"
if (Tribes.TRACE) {
System.out.println("+ around center ");
}
if (radius < 0) { if (radius < 0) {
// Choose at random a memory // Choose at random a memory
m = RNG.randomInt(this.tribes[fromTribe].memoryNb); m = RNG.randomInt(this.tribes[fromTribe].memoryNb);
@ -648,9 +642,6 @@ public class TribesSwarm implements java.io.Serializable {
In order to do that all memorizez positions are used, including de "dead" ones In order to do that all memorizez positions are used, including de "dead" ones
See SunnySpell See SunnySpell
*/ */
if (Tribes.TRACE) {
System.out.println("+ sunny spell ");
}
// if only initRange should be used for initialization, give that one to the sspell // if only initRange should be used for initialization, give that one to the sspell
expl.position = expl.position.maxIsolated((initRange == null) ? range : initRange, this); expl.position = expl.position.maxIsolated((initRange == null) ? range : initRange, this);
@ -666,9 +657,7 @@ public class TribesSwarm implements java.io.Serializable {
default: default:
// For pure random (0) method, or option 1 (on the bounds) // For pure random (0) method, or option 1 (on the bounds)
if (initType == 1) { // use initRange if (initType == 1) { // use initRange
if (Tribes.TRACE) {
System.out.println("+ in initRange ");
}
if (initRange == null) { if (initRange == null) {
System.err.println("unexpected null initRange!"); System.err.println("unexpected null initRange!");
} }
@ -677,9 +666,6 @@ public class TribesSwarm implements java.io.Serializable {
posTemp = expl.position.clone(); posTemp = expl.position.clone();
expl.initExplorerSpace(initRange); expl.initExplorerSpace(initRange);
} else { // use default range } else { // use default range
if (Tribes.TRACE) {
System.out.println("+ in whole range ");
}
//default: // In the whole search space //default: // In the whole search space
expl.initExplorerSpace(range); expl.initExplorerSpace(range);
posTemp = expl.position.clone(); posTemp = expl.position.clone();

View File

@ -26,7 +26,6 @@ import java.util.concurrent.Semaphore;
*/ */
public class MatlabEvalMediator { public class MatlabEvalMediator {
volatile Boolean requesting = false; volatile Boolean requesting = false;
// final static boolean TRACE = false;
volatile private Boolean fin = false; volatile private Boolean fin = false;
volatile Object question = null; volatile Object question = null;
volatile double[] answer = null; volatile double[] answer = null;

View File

@ -33,7 +33,6 @@ import java.util.BitSet;
@Description("Interface problem class for optimization in Matlab, only usable from within Matlab") @Description("Interface problem class for optimization in Matlab, only usable from within Matlab")
public class MatlabProblem extends AbstractOptimizationProblem implements InterfaceHasInitRange, InterfaceTextListener, Serializable { public class MatlabProblem extends AbstractOptimizationProblem implements InterfaceHasInitRange, InterfaceTextListener, Serializable {
private static final long serialVersionUID = 4913310869887420815L; private static final long serialVersionUID = 4913310869887420815L;
public static boolean TRACE = false;
transient OptimizerRunnable runnable = null; transient OptimizerRunnable runnable = null;
protected boolean allowSingleRunnable = true; protected boolean allowSingleRunnable = true;
private transient Population seedPopulation = null; private transient Population seedPopulation = null;
@ -219,8 +218,6 @@ public class MatlabProblem extends AbstractOptimizationProblem implements Interf
log("### Data type is " + dataType); log("### Data type is " + dataType);
initTemplate(); initTemplate();
setDebugOut(TRACE, defTestOut);
log("Initial range is " + BeanInspector.toString(initialRange) + "\n"); log("Initial range is " + BeanInspector.toString(initialRange) + "\n");
} }
@ -233,8 +230,6 @@ public class MatlabProblem extends AbstractOptimizationProblem implements Interf
* @param fname * @param fname
*/ */
public void setDebugOut(boolean swtch, String fname) { public void setDebugOut(boolean swtch, String fname) {
TRACE = swtch;
// System.err.println("setDebugOut: " + swtch +" " + fname);
if (!swtch && (dos != null)) { if (!swtch && (dos != null)) {
dos.close(); dos.close();
dos = null; dos = null;
@ -243,7 +238,6 @@ public class MatlabProblem extends AbstractOptimizationProblem implements Interf
if (fname == null || (fname.length() == 0)) { if (fname == null || (fname.length() == 0)) {
fname = defTestOut; fname = defTestOut;
} }
// System.err.println("Opening "+fname);
dos = new PrintStream(new FileOutputStream(fname)); dos = new PrintStream(new FileOutputStream(fname));
} catch (FileNotFoundException e) { } catch (FileNotFoundException e) {
e.printStackTrace(); e.printStackTrace();

View File

@ -8,7 +8,6 @@ import java.util.Comparator;
* *
*/ */
public class KMEANSJAVA { public class KMEANSJAVA {
static public boolean TRACE = false;
protected double[][] c; protected double[][] c;
protected int[] indices; protected int[] indices;
@ -41,10 +40,6 @@ public class KMEANSJAVA {
* *
*/ */
public KMEANSJAVA(double[][] samples, int K, int iterations) { public KMEANSJAVA(double[][] samples, int K, int iterations) {
//System.out.print("in");
if (TRACE) {
System.out.println("K" + K);
}
if (K > samples.length) { if (K > samples.length) {
K = samples.length; K = samples.length;
} }
@ -72,11 +67,11 @@ public class KMEANSJAVA {
for (int indexofc = 0; indexofc < c.length; indexofc++) { for (int indexofc = 0; indexofc < c.length; indexofc++) {
double[] newcenter = new double[samples[0].length]; double[] newcenter = new double[samples[0].length];
int treffer = 0; int treffer = 0;
for (int j = 0; j < indices.length; j++) { //System.out.println("j="+j); for (int indice : indices) { //System.out.println("j="+j);
if (indices[j] == indexofc) { if (indice == indexofc) {
treffer++; treffer++;
for (int d = 0; d < newcenter.length; d++) { 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]; //newcenter[d] = newcenter[d] + samples[j][d];
} }
} }
@ -88,7 +83,6 @@ public class KMEANSJAVA {
} }
// determine the new centers // determine the new centers
} }
//System.out.println("out");
} }
/** /**
@ -115,9 +109,9 @@ public class KMEANSJAVA {
System.out.println(""); System.out.println("");
} }
System.out.println("test"); System.out.println("test");
for (int i = 0; i < test.length; i++) { for (double[] aTest : test) {
for (int j = 0; j < test[i].length; j++) { for (int j = 0; j < aTest.length; j++) {
System.out.print(test[i][j] + " "); System.out.print(aTest[j] + " ");
} }
System.out.println(""); System.out.println("");
} }

View File

@ -25,13 +25,9 @@ import java.util.jar.JarInputStream;
* @author mkron * @author mkron
*/ */
public class ReflectPackage { public class ReflectPackage {
final static boolean TRACE = false;
static int missedJarsOnClassPath = 0; static int missedJarsOnClassPath = 0;
static boolean useFilteredClassPath = true; static boolean useFilteredClassPath = true;
// static boolean usePathMap = true;
static String[] dynCP = null; static String[] dynCP = null;
// static HashMap<String, ArrayList<String>> pathMap = new HashMap<String, ArrayList<String>>();
static class ClassComparator<T> implements Comparator<T> { static class ClassComparator<T> implements Comparator<T> {
@Override @Override
@ -59,26 +55,15 @@ public class ReflectPackage {
} }
dir = path + "/" + pckgname.replace(".", "/"); dir = path + "/" + pckgname.replace(".", "/");
if (TRACE) {
System.out.println(".. opening " + path);
}
directory = new File(dir); directory = new File(dir);
} catch (NullPointerException x) { } 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; return 0;
} }
if (directory.exists()) { if (directory.exists()) {
// Get the list of the files contained in the package // Get the list of the files contained in the package
return getClassesFromDirFltr(set, directory, pckgname, includeSubs, reqSuperCls); return getClassesFromDirFltr(set, directory, pckgname, includeSubs, reqSuperCls);
} else { } else {
if (TRACE) {
System.err.println(directory.getPath() + " doesnt exist in " + path + ", dir was " + dir);
}
return 0; return 0;
} }
} catch (ClassNotFoundException e) { } catch (ClassNotFoundException e) {
@ -88,21 +73,17 @@ public class ReflectPackage {
} }
} }
// public static ArrayList<Class> getClassesFromDir(File directory, String pckgname, boolean includeSubs) {
// return getClassesFromDirFltr(directory, pckgname, includeSubs, null);
// }
public static int getClassesFromDirFltr(HashSet<Class> set, File directory, String pckgname, boolean includeSubs, Class<?> reqSuperCls) { public static int getClassesFromDirFltr(HashSet<Class> set, File directory, String pckgname, boolean includeSubs, Class<?> reqSuperCls) {
int cntAdded = 0; int cntAdded = 0;
if (directory.exists()) { if (directory.exists()) {
// Get the list of the files contained in the package // Get the list of the files contained in the package
String[] files = directory.list(); String[] files = directory.list();
for (int i = 0; i < files.length; i++) { for (String file : files) {
// we are only interested in .class files // we are only interested in .class files
if (files[i].endsWith(".class")) { if (file.endsWith(".class")) {
// removes the .class extension // removes the .class extension
try { 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 != null) {
if (reqSuperCls.isAssignableFrom(cls)) { if (reqSuperCls.isAssignableFrom(cls)) {
cntAdded += addClass(set, cls); cntAdded += addClass(set, cls);
@ -111,15 +92,15 @@ public class ReflectPackage {
cntAdded += addClass(set, cls); cntAdded += addClass(set, cls);
} }
} catch (Exception e) { } 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) { } 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) { } else if (includeSubs) {
// do a recursive search over subdirs // 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()) { 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<Class> set, Class cls) { private static int addClass(HashSet<Class> set, Class cls) {
if (TRACE) {
System.out.println("adding class " + cls.getName());
}
if (set.contains(cls)) { if (set.contains(cls)) {
System.err.println("warning, Class " + cls.getName() + " not added twice!"); System.err.println("warning, Class " + cls.getName() + " not added twice!");
return 0; return 0;
@ -150,12 +128,9 @@ public class ReflectPackage {
public static ArrayList<Class> filterAssignableClasses(ArrayList<Class> classes, Class<?> reqSuperCls) { public static ArrayList<Class> filterAssignableClasses(ArrayList<Class> classes, Class<?> reqSuperCls) {
ArrayList<Class> assClasses = new ArrayList<Class>(); ArrayList<Class> assClasses = new ArrayList<Class>();
for (int i = 0; i < classes.size(); i++) { for (Class aClass : classes) {
if (reqSuperCls.isAssignableFrom(classes.get(i))) { if (reqSuperCls.isAssignableFrom(aClass)) {
if (TRACE) { assClasses.add(aClass);
System.out.println(" taking over " + classes.get(i));
}
assClasses.add(classes.get(i));
} }
} }
return assClasses; return assClasses;
@ -173,9 +148,6 @@ public class ReflectPackage {
int cntAdded = 0; int cntAdded = 0;
packageName = packageName.replaceAll("\\.", "/"); packageName = packageName.replaceAll("\\.", "/");
if (TRACE) {
System.out.println("Jar " + jarName + " looking for " + packageName);
}
try { try {
JarInputStream jarFile = new JarInputStream JarInputStream jarFile = new JarInputStream
(new FileInputStream(jarName)); (new FileInputStream(jarName));
@ -183,7 +155,6 @@ public class ReflectPackage {
while ((jarEntry = jarFile.getNextJarEntry()) != null) { while ((jarEntry = jarFile.getNextJarEntry()) != null) {
String jarEntryName = jarEntry.getName(); String jarEntryName = jarEntry.getName();
// if (TRACE) System.out.println("- " + jarEntry.getName());
if ((jarEntryName.startsWith(packageName)) && if ((jarEntryName.startsWith(packageName)) &&
(jarEntryName.endsWith(".class"))) { (jarEntryName.endsWith(".class"))) {
// subpackages are hit here as well! // subpackages are hit here as well!
@ -203,25 +174,20 @@ public class ReflectPackage {
} else { } else {
cntAdded += addClass(set, cls); cntAdded += addClass(set, cls);
} }
} catch (Exception e) { } catch (Exception | Error e) {
System.err.println("ReflectPackage: Couldnt get Class from jar for " + clsName + ": " + e.getMessage()); System.err.println("ReflectPackage: Couldn't get Class from jar for " + clsName + ": " + e.getMessage());
} catch (Error e) {
System.err.println("ReflectPackage: Couldnt get Class from jar for " + clsName + ": " + e.getMessage());
} }
} }
// classes.add (jarEntry.getName().replaceAll("/", "\\."));
} }
} }
} catch (IOException e) { } catch (IOException e) {
missedJarsOnClassPath++; missedJarsOnClassPath++;
if (missedJarsOnClassPath == 0) { 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?"); System.err.println("Dirty class path?");
} else if (missedJarsOnClassPath == 2) { } 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; return cntAdded;
} }
@ -230,13 +196,13 @@ public class ReflectPackage {
* Collect all classes from a given package on the classpath. If includeSubs is true, * Collect all classes from a given package on the classpath. If includeSubs is true,
* the sub-packages are listed as well. * the sub-packages are listed as well.
* *
* @param pckg * @param pkg Package name
* @param includeSubs * @param includeSubs Whether to include sub packages
* @param bSort sort alphanumerically by class name * @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. * @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) { public static Class[] getAllClassesInPackage(String pkg, boolean includeSubs, boolean bSort) {
return getClassesInPackageFltr(new HashSet<Class>(), pckg, includeSubs, bSort, null); return getClassesInPackageFltr(new HashSet<Class>(), pkg, includeSubs, bSort, null);
} }
/** /**
@ -244,14 +210,11 @@ public class ReflectPackage {
* as superclass or superinterface. If includeSubs is true, * as superclass or superinterface. If includeSubs is true,
* the sub-packages are listed as well. * the sub-packages are listed as well.
* *
* @param pckg * @param pkg
* @return * @return
* @see Class.assignableFromClass(Class cls)
*/ */
public static Class[] getClassesInPackageFltr(HashSet<Class> set, String pckg, boolean includeSubs, boolean bSort, Class reqSuperCls) { public static Class[] getClassesInPackageFltr(HashSet<Class> set, String pkg, boolean includeSubs, boolean bSort, Class reqSuperCls) {
String classPath = null;
if (!useFilteredClassPath || (dynCP == null)) { if (!useFilteredClassPath || (dynCP == null)) {
classPath = System.getProperty("java.class.path", ".");
if (useFilteredClassPath) { if (useFilteredClassPath) {
try { try {
dynCP = getValidCPArray(); dynCP = getValidCPArray();
@ -263,20 +226,11 @@ public class ReflectPackage {
} }
} }
if (TRACE) { for (String aDynCP : dynCP) {
System.out.println("classpath is " + classPath); if (aDynCP.endsWith(".jar")) {
} getClassesFromJarFltr(set, aDynCP, pkg, includeSubs, reqSuperCls);
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);
} else { } else {
if (TRACE) { getClassesFromFilesFltr(set, aDynCP, pkg, includeSubs, reqSuperCls);
System.out.println("reading from files: " + dynCP[i] + " " + pckg);
}
getClassesFromFilesFltr(set, dynCP[i], pckg, includeSubs, reqSuperCls);
} }
} }
Object[] clsArr = set.toArray(); Object[] clsArr = set.toArray();
@ -298,9 +252,6 @@ public class ReflectPackage {
public static String getResourcePathFromCP(String res) { public static String getResourcePathFromCP(String res) {
String[] cpEntries = getClassPathElements(); String[] cpEntries = getClassPathElements();
URL url = ClassLoader.getSystemResource(res); URL url = ClassLoader.getSystemResource(res);
if (TRACE) {
System.out.println(res + ((url == null) ? " not" : " was") + " found by classloader.");
}
if (url != null) { if (url != null) {
File f; File f;
try { try {
@ -319,15 +270,9 @@ public class ReflectPackage {
fNameSep = System.getProperty("file.separator") + res; fNameSep = System.getProperty("file.separator") + res;
} }
for (int i = 0; i < cpEntries.length; i++) { for (String cpEntry : cpEntries) {
if (!cpEntries[i].endsWith(".jar")) { // its a fs directory (hopefully) if (!cpEntry.endsWith(".jar")) { // its a fs directory (hopefully)
if (TRACE) { f = new File(cpEntry + fNameSep);
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]);
}
if (f.exists()) { if (f.exists()) {
return f.getAbsolutePath(); return f.getAbsolutePath();
} }
@ -345,9 +290,6 @@ public class ReflectPackage {
public static InputStream getResourceStreamFromCP(String res) { public static InputStream getResourceStreamFromCP(String res) {
InputStream in = BasicResourceLoader.instance().getStreamFromResourceLocation(res); InputStream in = BasicResourceLoader.instance().getStreamFromResourceLocation(res);
if (TRACE) {
System.out.println(res + ((in == null) ? " not" : " was") + " found by classloader.");
}
if (in != null) { if (in != null) {
return in; return in;
} }
@ -362,15 +304,9 @@ public class ReflectPackage {
fNameSep = System.getProperty("file.separator") + res; fNameSep = System.getProperty("file.separator") + res;
} }
for (int i = 0; i < cpEntries.length; i++) { for (String cpEntry : cpEntries) {
if (!cpEntries[i].endsWith(".jar")) { // its a fs directory (hopefully) if (!cpEntry.endsWith(".jar")) { // its a fs directory (hopefully)
if (TRACE) { f = new File(cpEntry + fNameSep);
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]);
}
if (f.exists()) { if (f.exists()) {
try { try {
return new FileInputStream(f); return new FileInputStream(f);
@ -387,12 +323,10 @@ public class ReflectPackage {
String[] pathElements = getClassPathElements(); String[] pathElements = getClassPathElements();
File f; File f;
ArrayList<String> valids = new ArrayList<String>(pathElements.length); ArrayList<String> valids = new ArrayList<String>(pathElements.length);
for (int i = 0; i < pathElements.length; i++) { for (String pathElement : pathElements) {
// System.err.println(pathElements[i]); f = new File(pathElement);
f = new File(pathElements[i]);
// if (f.canRead()) {valids.add(pathElements[i]);}
if (f.exists() && f.canRead()) { if (f.exists() && f.canRead()) {
valids.add(pathElements[i]); valids.add(pathElement);
} }
} }
return valids; return valids;
@ -400,7 +334,6 @@ public class ReflectPackage {
public static String[] getValidCPArray() { public static String[] getValidCPArray() {
ArrayList<String> valids = getValidCPEntries(); ArrayList<String> valids = getValidCPEntries();
// vp = valids.toArray(dynCP); // this causes Matlab to crash meanly.
String[] vp = new String[valids.size()]; String[] vp = new String[valids.size()];
for (int i = 0; i < valids.size(); i++) { for (int i = 0; i < valids.size(); i++) {
vp[i] = valids.get(i); vp[i] = valids.get(i);
@ -416,9 +349,6 @@ public class ReflectPackage {
* @return * @return
*/ */
public static Class<?>[] getAssignableClassesInPackage(String pckg, Class reqSuperCls, boolean includeSubs, boolean bSort) { 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<Class>(), pckg, includeSubs, bSort, reqSuperCls); return getClassesInPackageFltr(new HashSet<Class>(), 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, * Retrieve assignable classes of the given package from classpath given by full class and package String,
* such as eva2.problems.AbstractOptimizationProblem. * such as eva2.problems.AbstractOptimizationProblem.
* *
* @param pckg String denoting the package * @param pckgClassName String denoting the package
* @param reqSuperCls * @param includeSubs
* @param bSort
* @return * @return
*/ */
public static Class<?>[] getAssignableClasses(String pckgClassName, boolean includeSubs, boolean bSort) { public static Class<?>[] getAssignableClasses(String pckgClassName, boolean includeSubs, boolean bSort) {
@ -450,13 +381,8 @@ public class ReflectPackage {
public static void main(String[] args) { public static void main(String[] args) {
ClassLoader cld = Thread.currentThread().getContextClassLoader(); ClassLoader cld = Thread.currentThread().getContextClassLoader();
System.out.println("1: " + cld.getResource("/eva2/server")); System.out.println("1: " + cld.getResource("/eva2/optimization"));
System.out.println("2: " + cld.getResource("eva2/server")); System.out.println("2: " + cld.getResource("eva2/optimization"));
// 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());
HashSet<String> h = new HashSet<String>(20); HashSet<String> h = new HashSet<String>(20);
@ -466,27 +392,10 @@ public class ReflectPackage {
for (String string : h) { for (String string : h) {
System.out.println("+ " + string); System.out.println("+ " + string);
} }
// String[] pathElements = getClassPathElements();
// for (int i=0; i<pathElements.length; i++) {
// System.out.print(i+" " + pathElements[i]);
// System.out.println(pathElements[i].endsWith(".jar") ? " is a jar" : " is a path");
// if (pathElements[i].endsWith(".jar")) {
// ArrayList al = getClassesFromJarFltr(pathElements[i], "eva2.server.model", false, null);
// for (int k=0; k<al.size(); k++) {
// //if (Class.forName("eva2.server.modules.ModuleAdapter").isAssignableFrom((Class)al.get(i)))
// System.out.println((Class)al.get(k));
// }
// } else {
//
// }
// }
} }
public static String[] getClassPathElements() { public static String[] getClassPathElements() {
String classPath = System.getProperty("java.class.path", "."); String classPath = System.getProperty("java.class.path", ".");
// System.out.println("classpath: " + classPath);
return classPath.split(File.pathSeparator); return classPath.split(File.pathSeparator);
} }
@ -495,7 +404,6 @@ public class ReflectPackage {
Object bean = null; Object bean = null;
try { try {
bean = server.getObjectInstance(new ObjectName("com.sun.management:type=HotSpotDiagnostic")); bean = server.getObjectInstance(new ObjectName("com.sun.management:type=HotSpotDiagnostic"));
//bean = server.queryMBeans(null, null);
} catch (Exception e) { } catch (Exception e) {
// TODO Auto-generated catch block // TODO Auto-generated catch block
e.printStackTrace(); e.printStackTrace();
@ -507,12 +415,6 @@ public class ReflectPackage {
MBeanServer server = ManagementFactory.getPlatformMBeanServer(); MBeanServer server = ManagementFactory.getPlatformMBeanServer();
Object ret = null; Object ret = null;
try { try {
// void setVMOption(String name, String value)
//-Xrunhprof:heap=dump,format=b
// ret = server.invoke(new ObjectName("com.sun.management:type=HotSpotDiagnostic"),
// "setVMOption", new Object[]{"agentlib", "hprof=heap=dump,format=a"},
// new String[] {"java.lang.String","java.lang.String"});
// ret = server.invoke(new ObjectName("com.sun.management:type=HotSpotDiagnostic"), "getDiagnosticOptions", new Object[] {}, new String[] {});
server.invoke(new ObjectName("com.sun.management:type=HotSpotDiagnostic"), "dumpHeap", new Object[]{file, live}, new String[]{"java.lang.String", "boolean"}); server.invoke(new ObjectName("com.sun.management:type=HotSpotDiagnostic"), "dumpHeap", new Object[]{file, live}, new String[]{"java.lang.String", "boolean"});
//bean = server.queryMBeans(null, null); //bean = server.queryMBeans(null, null);
} catch (Exception e) { } catch (Exception e) {
@ -544,7 +446,6 @@ public class ReflectPackage {
* @param args constructor arguments * @param args constructor arguments
* @param paramValuePairs pairs of values to set using generic setter methods * @param paramValuePairs pairs of values to set using generic setter methods
* @return * @return
* @see BeanInspector.setMem(Object,String,Object)
*/ */
public static Object instantiateWithParams(String clsName, Object[] args, List<Pair<String, Object>> paramValuePairs) { public static Object instantiateWithParams(String clsName, Object[] args, List<Pair<String, Object>> paramValuePairs) {
Object o = getInstance(clsName, args); Object o = getInstance(clsName, args);
@ -555,8 +456,6 @@ public class ReflectPackage {
if (!succ) { if (!succ) {
System.err.println("Error, unable to set " + nameVal.head + " to " + nameVal.tail + " in object " + o); System.err.println("Error, unable to set " + nameVal.head + " to " + nameVal.tail + " in object " + o);
return null; return null;
} else if (TRACE) {
System.out.println("Successfully set " + nameVal.head + " to " + nameVal.tail + " in object " + o);
} }
} }
} }

View File

@ -29,16 +29,13 @@ public class DArea extends JComponent implements DParent, Printable {
/** /**
* the default minimal rectangle which is shown * the default minimal rectangle which is shown
*/ */
public static final DRectangle DEFAULT_MIN_RECT = new DRectangle(-1, -1, 2, public static final DRectangle DEFAULT_MIN_RECT = new DRectangle(-1, -1, 2, 2);
2);
/** /**
* *
*/ */
private static final long serialVersionUID = 1461387400381365146L; private static final long serialVersionUID = 1461387400381365146L;
private static final boolean TRACE = false;
private boolean auto_focus = false, auto_grid = false, private boolean auto_focus = false, auto_grid = false,
grid_to_front = false; grid_to_front = false;
@ -358,9 +355,6 @@ public class DArea extends JComponent implements DParent, Printable {
*/ */
@Override @Override
public void paint(Graphics g) { public void paint(Graphics g) {
if (TRACE) {
System.out.println("DArea.paint(Graphics)");
}
if (auto_focus) { if (auto_focus) {
container.restore(); container.restore();
visible_rect = (DRectangle) container.getRectangle().clone(); visible_rect = (DRectangle) container.getRectangle().clone();
@ -388,9 +382,6 @@ public class DArea extends JComponent implements DParent, Printable {
* auto_grid option * auto_grid option
*/ */
private void paintGrid(DMeasures m) { private void paintGrid(DMeasures m) {
if (TRACE) {
System.out.println("DArea.paintGrid(DMeasures)");
}
grid.rectangle = getDRectangle(); grid.rectangle = getDRectangle();
if (auto_grid) { if (auto_grid) {
Border b = getBorder(); Border b = getBorder();
@ -417,9 +408,6 @@ public class DArea extends JComponent implements DParent, Printable {
* @param m the measures of the area * @param m the measures of the area
*/ */
private void paintGrid(ScaledBorder sb, DMeasures m) { private void paintGrid(ScaledBorder sb, DMeasures m) {
if (TRACE) {
System.out.println("DArea.paintGrid(ScaledBorder, DMeasures)");
}
Dimension d = getSize(); Dimension d = getSize();
FontMetrics fm = m.getGraphics().getFontMetrics(); FontMetrics fm = m.getGraphics().getFontMetrics();
grid.setDistances(sb.getSrcdX(fm, d), sb.getSrcdY(fm, d)); grid.setDistances(sb.getSrcdX(fm, d), sb.getSrcdY(fm, d));
@ -479,9 +467,6 @@ public class DArea extends JComponent implements DParent, Printable {
*/ */
@Override @Override
public int print(Graphics g, PageFormat pf, int pi) { public int print(Graphics g, PageFormat pf, int pi) {
if (TRACE) {
System.out.println("DArea.print(...)");
}
if (pi > 0) { if (pi > 0) {
return Printable.NO_SUCH_PAGE; return Printable.NO_SUCH_PAGE;
} }
@ -553,9 +538,6 @@ public class DArea extends JComponent implements DParent, Printable {
*/ */
@Override @Override
public void repaint(DRectangle r) { public void repaint(DRectangle r) {
if (TRACE) {
System.out.println("DArea.repaint(DRectangle)" + r);
}
if (r == null) { if (r == null) {
throw new IllegalArgumentException( throw new IllegalArgumentException(
"Cannot repaint a null DRectangle"); "Cannot repaint a null DRectangle");
@ -580,9 +562,6 @@ public class DArea extends JComponent implements DParent, Printable {
@Override @Override
public void restoreBorder() { public void restoreBorder() {
dborder = container.getDBorder(); 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 * @param aFlag visible or not
*/ */
public void setGridVisible(boolean aFlag) { public void setGridVisible(boolean aFlag) {
if (TRACE) {
System.out.println("DArea.setGridVisisble: " + aFlag);
}
grid.rectangle = getDRectangle(); grid.rectangle = getDRectangle();
grid.setVisible(aFlag); grid.setVisible(aFlag);
} }
@ -784,9 +761,6 @@ public class DArea extends JComponent implements DParent, Printable {
* @param rect the visible <code>DRectangle</code> in DArea coordinates * @param rect the visible <code>DRectangle</code> in DArea coordinates
*/ */
public void setVisibleRectangle(DRectangle rect) { public void setVisibleRectangle(DRectangle rect) {
if (TRACE) {
System.out.println("DArea.setVisibleRectangle(DRectangle)");
}
if (rect.isEmpty()) { if (rect.isEmpty()) {
throw new IllegalArgumentException( throw new IllegalArgumentException(
"You should never try to set an empty rectangle\n" "You should never try to set an empty rectangle\n"