Code cleanup.

This commit is contained in:
Fabian Becker 2012-06-29 13:08:52 +00:00
parent 00b6af14ff
commit 5814162876
10 changed files with 761 additions and 742 deletions

View File

@ -47,6 +47,7 @@ import eva2.tools.chart2d.DPoint;
import eva2.tools.chart2d.DPointIcon; import eva2.tools.chart2d.DPointIcon;
import eva2.tools.chart2d.DPointSet; import eva2.tools.chart2d.DPointSet;
import eva2.tools.chart2d.ScaledBorder; import eva2.tools.chart2d.ScaledBorder;
import java.util.logging.Level;
import java.util.logging.Logger; import java.util.logging.Logger;
/* /*
@ -740,8 +741,8 @@ public class FunctionArea extends DArea implements Serializable {
out.flush(); out.flush();
out.close(); out.close();
return true; return true;
} catch (Exception e) { } catch (Exception ex) {
System.err.println("Error on data export:" + e.getMessage()); LOGGER.log(Level.WARNING, "Error while writing to file.", ex);
return false; return false;
} }
} }

View File

@ -356,6 +356,9 @@ public class GenericArrayEditor extends JPanel implements PropertyEditor {
view = new PropertyValueSelector(editor); view = new PropertyValueSelector(editor);
} else if (editor.getAsText() != null) { } else if (editor.getAsText() != null) {
view = new PropertyText(editor); view = new PropertyText(editor);
} else if (view == null) {
/* Dirty hack to view PropertyDoubleArray component */
view = new PropertyText(editor);
} }
} }
if (view == null) { if (view == null) {

View File

@ -9,57 +9,59 @@ import javax.swing.BorderFactory;
import javax.swing.JTextField; import javax.swing.JTextField;
/** /**
* A text property editor view. Updates the editor on key release and lost focus events. * A text property editor view. Updates the editor on key release and lost focus
* * events.
*
*/ */
public class PropertyText extends JTextField { public class PropertyText extends JTextField {
private PropertyEditor propertyEditor;
/**
*
*/
public PropertyText(PropertyEditor pe) {
super(pe.getAsText());
this.setBorder(BorderFactory.createEmptyBorder());
propertyEditor = pe;
// m_Editor.addPropertyChangeListener(new PropertyChangeListener() {
// public void propertyChange(PropertyChangeEvent evt) {
// updateUs();
// }
// });
addKeyListener(new KeyAdapter() {
public void keyReleased(KeyEvent e) {
//if (e.getKeyCode() == KeyEvent.VK_ENTER)
updateEditor();
}
});
addFocusListener(new FocusAdapter() {
public void focusLost(FocusEvent e) {
updateEditor();
}
});
}
/** private PropertyEditor propertyEditor;
*
*/ /**
protected void updateEditor() { *
try { */
String x = getText(); public PropertyText(PropertyEditor pe) {
if (!propertyEditor.getAsText().equals(x)) { super(pe.getAsText());
propertyEditor.setAsText(x); this.setBorder(BorderFactory.createEmptyBorder());
propertyEditor = pe;
addKeyListener(new KeyAdapter() {
@Override
public void keyReleased(KeyEvent e) {
//if (e.getKeyCode() == KeyEvent.VK_ENTER)
updateEditor();
}
});
addFocusListener(new FocusAdapter() {
@Override
public void focusLost(FocusEvent e) {
updateEditor();
}
});
}
/**
*
*/
protected void updateEditor() {
try {
String x = getText();
if (!propertyEditor.getAsText().equals(x)) {
propertyEditor.setAsText(x);
// setText(m_Editor.getAsText()); // setText(m_Editor.getAsText());
} }
} catch (IllegalArgumentException ex) { } catch (IllegalArgumentException ex) {
// System.err.println("Warning: Couldnt set value (PropertyText)"); // System.err.println("Warning: Couldnt set value (PropertyText)");
} }
} }
public boolean checkConsistency() { public boolean checkConsistency() {
String x = getText(); String x = getText();
return x.equals(propertyEditor.getAsText()); return x.equals(propertyEditor.getAsText());
} }
public void updateFromEditor() { public void updateFromEditor() {
setText(propertyEditor.getAsText()); setText(propertyEditor.getAsText());
} }
} }

View File

@ -13,12 +13,14 @@ import java.util.BitSet;
*/ */
public interface InterfaceGAIndividual { public interface InterfaceGAIndividual {
/** This method will allow the user to read the GA genotype /**
* This method will allow the user to read the GA genotype.
* @return BitSet * @return BitSet
*/ */
public BitSet getBGenotype(); public BitSet getBGenotype();
/** This method will allow the user to set the current GA genotype. /**
* This method will allow the user to set the current GA genotype.
* Use this method with care, since the object is returned when using * Use this method with care, since the object is returned when using
* getBinaryData() you can directly alter the genotype without using * getBinaryData() you can directly alter the genotype without using
* this method. * this method.

View File

@ -1,147 +1,181 @@
package eva2.server.go.operators.mutation; package eva2.server.go.operators.mutation;
import java.util.BitSet;
import eva2.server.go.individuals.AbstractEAIndividual; import eva2.server.go.individuals.AbstractEAIndividual;
import eva2.server.go.individuals.InterfaceGAIndividual; import eva2.server.go.individuals.InterfaceGAIndividual;
import eva2.server.go.populations.Population; import eva2.server.go.populations.Population;
import eva2.server.go.problems.InterfaceOptimizationProblem; import eva2.server.go.problems.InterfaceOptimizationProblem;
import eva2.tools.math.RNG; import eva2.tools.math.RNG;
import java.util.BitSet;
/** /**
* Created by IntelliJ IDEA. *
* User: streiche
* Date: 05.08.2004
* Time: 17:47:03
* To change this template use File | Settings | File Templates.
*/ */
public class MutateGAInvertBits implements InterfaceMutation, java.io.Serializable { public class MutateGAInvertBits implements InterfaceMutation, java.io.Serializable {
private int m_NumberOfMutations = 1; private int m_NumberOfMutations = 1;
private int m_MaxInveredBits = 5; private int m_MaxInveredBits = 5;
public MutateGAInvertBits() { public MutateGAInvertBits() {
}
public MutateGAInvertBits(MutateGAInvertBits mutator) {
this.m_NumberOfMutations = mutator.m_NumberOfMutations;
this.m_MaxInveredBits = mutator.m_MaxInveredBits;
}
/** This method will enable you to clone a given mutation operator
* @return The clone
*/
public Object clone() {
return new MutateGAInvertBits(this);
}
/** This method allows you to evaluate wether two mutation operators
* are actually the same.
* @param mutator The other mutation operator
*/
public boolean equals(Object mutator) {
if (mutator instanceof MutateGAInvertBits) {
MutateGAInvertBits mut = (MutateGAInvertBits)mutator;
if (this.m_NumberOfMutations != mut.m_NumberOfMutations) return false;
if (this.m_MaxInveredBits != mut.m_MaxInveredBits) return false;
return true;
} else return false;
} }
/** This method allows you to init the mutation operator public MutateGAInvertBits(MutateGAInvertBits mutator) {
* @param individual The individual that will be mutated. this.m_NumberOfMutations = mutator.m_NumberOfMutations;
* @param opt The optimization problem. this.m_MaxInveredBits = mutator.m_MaxInveredBits;
}
/**
* This method will enable you to clone a given mutation operator
*
* @return The clone
*/ */
@Override
public Object clone() {
return new MutateGAInvertBits(this);
}
/**
* This method allows you to evaluate wether two mutation operators are
* actually the same.
*
* @param mutator The other mutation operator
*/
@Override
public boolean equals(Object mutator) {
if (mutator instanceof MutateGAInvertBits) {
MutateGAInvertBits mut = (MutateGAInvertBits) mutator;
if (this.m_NumberOfMutations != mut.m_NumberOfMutations) {
return false;
}
if (this.m_MaxInveredBits != mut.m_MaxInveredBits) {
return false;
}
return true;
} else {
return false;
}
}
/**
* This method allows you to init the mutation operator
*
* @param individual The individual that will be mutated.
* @param opt The optimization problem.
*/
@Override
public void init(AbstractEAIndividual individual, InterfaceOptimizationProblem opt) { public void init(AbstractEAIndividual individual, InterfaceOptimizationProblem opt) {
}
} /**
* This method will mutate a given AbstractEAIndividual. If the individual
/** This method will mutate a given AbstractEAIndividual. If the individual * doesn't implement InterfaceGAIndividual nothing happens.
* doesn't implement InterfaceGAIndividual nothing happens. *
* @param individual The individual that is to be mutated * @param individual The individual that is to be mutated
*/ */
public void mutate(AbstractEAIndividual individual) { @Override
//System.out.println("Before Mutate: " +((GAIndividual)individual).getSolutionRepresentationFor()); public void mutate(AbstractEAIndividual individual) {
if (individual instanceof InterfaceGAIndividual) { if (individual instanceof InterfaceGAIndividual) {
BitSet tmpBitSet = ((InterfaceGAIndividual)individual).getBGenotype(); BitSet tmpBitSet = ((InterfaceGAIndividual) individual).getBGenotype();
int[][] mutationIndices = new int[this.m_NumberOfMutations][2]; int[][] mutationIndices = new int[this.m_NumberOfMutations][2];
for (int i = 0; i < mutationIndices.length; i++) { for (int i = 0; i < mutationIndices.length; i++) {
mutationIndices[i][0] = RNG.randomInt(0, ((InterfaceGAIndividual)individual).getGenotypeLength());; mutationIndices[i][0] = RNG.randomInt(0, ((InterfaceGAIndividual) individual).getGenotypeLength());;
mutationIndices[i][1] = RNG.randomInt(0, this.m_MaxInveredBits);; mutationIndices[i][1] = RNG.randomInt(0, this.m_MaxInveredBits);;
} }
// double instances of mutationIndices could be checked here... *sigh* // ToDo: double instances of mutationIndices could be checked here... *sigh*
for (int i = 0; i < mutationIndices.length; i++) { for (int i = 0; i < mutationIndices.length; i++) {
tmpBitSet.flip(mutationIndices[i][0], Math.min(((InterfaceGAIndividual)individual).getGenotypeLength(), mutationIndices[i][0]+ mutationIndices[i][1])); tmpBitSet.flip(mutationIndices[i][0], Math.min(((InterfaceGAIndividual) individual).getGenotypeLength(), mutationIndices[i][0] + mutationIndices[i][1]));
if ((mutationIndices[i][0]+ mutationIndices[i][1]) > ((InterfaceGAIndividual)individual).getGenotypeLength()) { if ((mutationIndices[i][0] + mutationIndices[i][1]) > ((InterfaceGAIndividual) individual).getGenotypeLength()) {
tmpBitSet.flip(0, (mutationIndices[i][0]+ mutationIndices[i][1])-((InterfaceGAIndividual)individual).getGenotypeLength()); tmpBitSet.flip(0, (mutationIndices[i][0] + mutationIndices[i][1]) - ((InterfaceGAIndividual) individual).getGenotypeLength());
} }
} }
((InterfaceGAIndividual)individual).SetBGenotype(tmpBitSet); ((InterfaceGAIndividual) individual).SetBGenotype(tmpBitSet);
} }
//System.out.println("After Mutate: " +((GAIndividual)individual).getSolutionRepresentationFor()); }
}
/** This method allows you to perform either crossover on the strategy parameters /**
* or to deal in some other way with the crossover event. * This method allows you to perform either crossover on the strategy
* @param indy1 The original mother * parameters or to deal in some other way with the crossover event.
* @param partners The original partners *
* @param indy1 The original mother
* @param partners The original partners
*/ */
@Override
public void crossoverOnStrategyParameters(AbstractEAIndividual indy1, Population partners) { public void crossoverOnStrategyParameters(AbstractEAIndividual indy1, Population partners) {
// nothing to do here // nothing to do here
} }
/** This method allows you to get a string representation of the mutation /**
* operator * This method allows you to get a string representation of the mutation
* @return A descriptive string. * operator
*/ *
public String getStringRepresentation() { * @return A descriptive string.
return "GA inversion mutation"; */
} @Override
public String getStringRepresentation() {
return "GA inversion mutation";
}
/********************************************************************************************************************** /**
* These are for GUI * These are for GUI
*/ */
/** This method allows the CommonJavaObjectEditorPanel to read the
* name to the current object. /**
* @return The name. * This method allows the CommonJavaObjectEditorPanel to read the name to
*/ * the current object.
public String getName() { *
return "GA invert n bits mutation"; * @return The name.
} */
/** This method returns a global info string public String getName() {
* @return description return "GA invert n bits mutation";
*/ }
public static String globalInfo() {
return "This mutation operator inverts n successive bits.";
}
/** This method allows you to set the number of mutations that occur in the /**
* genotype. * This method returns a global info string
* @param mutations The number of mutations. *
*/ * @return description
public void setNumberOfMutations(int mutations) { */
if (mutations < 0) mutations = 0; public static String globalInfo() {
this.m_NumberOfMutations = mutations; return "This mutation operator inverts n successive bits.";
} }
public int getNumberOfMutations() {
return this.m_NumberOfMutations; /**
} * This method allows you to set the number of mutations that occur in the
public String numberOfMutationsTipText() { * genotype.
return "The number of inversion events."; *
} * @param mutations The number of mutations.
/** This method allows you to set the macimun number if succesively */
* inverted bits public void setNumberOfMutations(int mutations) {
* @param mutations The number of successively inverted bits. if (mutations < 0) {
*/ mutations = 0;
public void setMaxInveredBits(int mutations) { }
if (mutations < 0) mutations = 0; this.m_NumberOfMutations = mutations;
this.m_MaxInveredBits = mutations; }
}
public int getMaxInveredBits() { public int getNumberOfMutations() {
return this.m_MaxInveredBits; return this.m_NumberOfMutations;
} }
public String maxInveredBitsTipText() {
return "The number of successive bits to be inverted."; public String numberOfMutationsTipText() {
} return "The number of inversion events.";
}
/**
* This method allows you to set the macimun number if succesively inverted
* bits
*
* @param mutations The number of successively inverted bits.
*/
public void setMaxInveredBits(int mutations) {
if (mutations < 0) {
mutations = 0;
}
this.m_MaxInveredBits = mutations;
}
public int getMaxInveredBits() {
return this.m_MaxInveredBits;
}
public String maxInveredBitsTipText() {
return "The number of successive bits to be inverted.";
}
} }

View File

@ -1,122 +1,151 @@
package eva2.server.go.operators.mutation; package eva2.server.go.operators.mutation;
import java.util.BitSet;
import eva2.server.go.individuals.AbstractEAIndividual; import eva2.server.go.individuals.AbstractEAIndividual;
import eva2.server.go.individuals.InterfaceGAIndividual; import eva2.server.go.individuals.InterfaceGAIndividual;
import eva2.server.go.populations.Population; import eva2.server.go.populations.Population;
import eva2.server.go.problems.InterfaceOptimizationProblem; import eva2.server.go.problems.InterfaceOptimizationProblem;
import eva2.tools.math.RNG; import eva2.tools.math.RNG;
import java.util.BitSet;
/** /**
* Created by IntelliJ IDEA. *
* User: streiche
* Date: 03.04.2003
* Time: 10:03:37
* To change this template use Options | File Templates.
*/ */
public class MutateGANBit implements InterfaceMutation, java.io.Serializable { public class MutateGANBit implements InterfaceMutation, java.io.Serializable {
private int m_NumberOfMutations = 1;
private int numberOfMutations = 1;
public MutateGANBit() { public MutateGANBit() {
} }
public MutateGANBit(MutateGANBit mutator) { public MutateGANBit(MutateGANBit mutator) {
this.m_NumberOfMutations = mutator.m_NumberOfMutations; this.numberOfMutations = mutator.numberOfMutations;
} }
/** This method will enable you to clone a given mutation operator /**
* This method will enable you to clone a given mutation operator
*
* @return The clone * @return The clone
*/ */
@Override
public Object clone() { public Object clone() {
return new MutateGANBit(this); return new MutateGANBit(this);
} }
/** This method allows you to evaluate wether two mutation operators /**
* are actually the same. * This method allows you to evaluate wether two mutation operators are
* @param mutator The other mutation operator * actually the same.
*
* @param mutator The other mutation operator
*/ */
@Override
public boolean equals(Object mutator) { public boolean equals(Object mutator) {
if (mutator instanceof MutateGANBit) { if (mutator instanceof MutateGANBit) {
MutateGANBit mut = (MutateGANBit)mutator; MutateGANBit mut = (MutateGANBit) mutator;
if (this.m_NumberOfMutations != mut.m_NumberOfMutations) return false; if (this.numberOfMutations != mut.numberOfMutations) {
return false;
}
return true; return true;
} else return false; } else {
return false;
}
} }
/** This method allows you to init the mutation operator /**
* @param individual The individual that will be mutated. * This method allows you to init the mutation operator
* @param opt The optimization problem. *
* @param individual The individual that will be mutated.
* @param opt The optimization problem.
*/ */
@Override
public void init(AbstractEAIndividual individual, InterfaceOptimizationProblem opt) { public void init(AbstractEAIndividual individual, InterfaceOptimizationProblem opt) {
} }
/** This method will mutate a given AbstractEAIndividual. If the individual /**
* This method will mutate a given AbstractEAIndividual. If the individual
* doesn't implement InterfaceGAIndividual nothing happens. * doesn't implement InterfaceGAIndividual nothing happens.
* @param individual The individual that is to be mutated *
* @param individual The individual that is to be mutated
*/ */
@Override
public void mutate(AbstractEAIndividual individual) { public void mutate(AbstractEAIndividual individual) {
//System.out.println("Before Mutate: " +((GAIndividual)individual).getSolutionRepresentationFor()); //System.out.println("Before Mutate: " +((GAIndividual)individual).getSolutionRepresentationFor());
if (individual instanceof InterfaceGAIndividual) { if (individual instanceof InterfaceGAIndividual) {
BitSet tmpBitSet = ((InterfaceGAIndividual)individual).getBGenotype(); BitSet tmpBitSet = ((InterfaceGAIndividual) individual).getBGenotype();
int[] mutationIndices = new int[this.m_NumberOfMutations]; int[] mutationIndices = new int[this.numberOfMutations];
for (int i = 0; i < mutationIndices.length; i++) mutationIndices[i] = RNG.randomInt(0, ((InterfaceGAIndividual)individual).getGenotypeLength());; for (int i = 0; i < mutationIndices.length; i++) {
mutationIndices[i] = RNG.randomInt(0, ((InterfaceGAIndividual) individual).getGenotypeLength());
};
// double instances of mutationIndices could be checked here... *sigh* // double instances of mutationIndices could be checked here... *sigh*
for (int i = 0; i < mutationIndices.length; i++) { for (int i = 0; i < mutationIndices.length; i++) {
tmpBitSet.flip(mutationIndices[i]); tmpBitSet.flip(mutationIndices[i]);
} }
((InterfaceGAIndividual)individual).SetBGenotype(tmpBitSet); ((InterfaceGAIndividual) individual).SetBGenotype(tmpBitSet);
} }
//System.out.println("After Mutate: " +((GAIndividual)individual).getSolutionRepresentationFor());
} }
/** This method allows you to perform either crossover on the strategy parameters /**
* or to deal in some other way with the crossover event. * This method allows you to perform either crossover on the strategy
* @param indy1 The original mother * parameters or to deal in some other way with the crossover event.
* @param partners The original partners *
* @param indy1 The original mother
* @param partners The original partners
*/ */
@Override
public void crossoverOnStrategyParameters(AbstractEAIndividual indy1, Population partners) { public void crossoverOnStrategyParameters(AbstractEAIndividual indy1, Population partners) {
// nothing to do here // nothing to do here
} }
/** This method allows you to get a string representation of the mutation /**
* This method allows you to get a string representation of the mutation
* operator * operator
*
* @return A descriptive string. * @return A descriptive string.
*/ */
@Override
public String getStringRepresentation() { public String getStringRepresentation() {
return "GA n-Bit mutation"; return "GA n-Bit mutation";
} }
/********************************************************************************************************************** /**
* These are for GUI * ********************************************************************************************************************
*/ * These are for GUI
/** This method allows the CommonJavaObjectEditorPanel to read the */
* name to the current object. /**
* This method allows the CommonJavaObjectEditorPanel to read the name to
* the current object.
*
* @return The name. * @return The name.
*/ */
public String getName() { public String getName() {
return "GA n-Bit mutation"; return "GA n-Bit mutation";
} }
/** This method returns a global info string
/**
* This method returns a global info string
*
* @return description * @return description
*/ */
public static String globalInfo() { public static String globalInfo() {
return "Switch n bits of the GA genotype."; return "Switch n bits of the GA genotype.";
} }
/** This method allows you to set the number of mutations that occur in the /**
* This method allows you to set the number of mutations that occur in the
* genotype. * genotype.
* @param mutations The number of mutations. *
* @param mutations The number of mutations.
*/ */
public void setNumberOfMutations(int mutations) { public void setNumberOfMutations(int mutations) {
if (mutations < 0) mutations = 0; if (mutations < 0) {
this.m_NumberOfMutations = mutations; mutations = 0;
}
this.numberOfMutations = mutations;
} }
public int getNumberOfMutations() { public int getNumberOfMutations() {
return this.m_NumberOfMutations; return this.numberOfMutations;
} }
public String numberOfMutationsTipText() { public String numberOfMutationsTipText() {
return "The number of bits to be mutated."; return "The number of bits to be mutated.";
} }

View File

@ -9,80 +9,78 @@ package eva2.server.go.operators.terminators;
* $Date: 2007-12-05 11:29:32 +0100 (Wed, 05 Dec 2007) $ * $Date: 2007-12-05 11:29:32 +0100 (Wed, 05 Dec 2007) $
* $Author: mkron $ * $Author: mkron $
*/ */
/*==========================================================================*
* IMPORTS
*==========================================================================*/
import java.io.Serializable;
import eva2.gui.BeanInspector;
import eva2.server.go.InterfaceTerminator; import eva2.server.go.InterfaceTerminator;
import eva2.server.go.PopulationInterface; import eva2.server.go.PopulationInterface;
import eva2.server.go.populations.InterfaceSolutionSet; import eva2.server.go.populations.InterfaceSolutionSet;
import eva2.server.go.problems.InterfaceOptimizationProblem; import eva2.server.go.problems.InterfaceOptimizationProblem;
import java.io.Serializable;
/*==========================================================================*
* CLASS DECLARATION
*==========================================================================*/
/** /**
* *
*/ */
public class GenerationTerminator implements InterfaceTerminator, public class GenerationTerminator implements InterfaceTerminator, Serializable {
Serializable {
/**
* Number of fitness calls on the problem which is optimized
*/
protected int m_Generations = 100;
private String msg = "";
public void init(InterfaceOptimizationProblem prob){
msg = "Not terminated.";
}
public static String globalInfo() {
return "Terminate after the given number of generations";
}
public GenerationTerminator() { /**
} * Number of fitness calls on the problem which is optimized
*/
protected int m_Generations = 100;
private String msg = "";
public GenerationTerminator(int gens) { @Override
m_Generations = gens; public void init(InterfaceOptimizationProblem prob) {
} msg = "Not terminated.";
}
public boolean isTerminated(InterfaceSolutionSet solSet) {
return isTerminated(solSet.getCurrentPopulation());
}
public boolean isTerminated(PopulationInterface Pop) { public static String globalInfo() {
if (m_Generations<Pop.getGeneration()) { return "Terminate after the given number of generations";
msg = m_Generations + " generations reached."; }
return true;
}
return false;
}
public String lastTerminationMessage() { public GenerationTerminator() {
return msg; }
}
public String toString() { public GenerationTerminator(int gens) {
String ret = "Generations calls="+m_Generations; m_Generations = gens;
return ret; }
}
public void setGenerations(int x) { @Override
m_Generations = x; public boolean isTerminated(InterfaceSolutionSet solSet) {
} return isTerminated(solSet.getCurrentPopulation());
}
public int getGenerations() { @Override
return m_Generations; public boolean isTerminated(PopulationInterface Pop) {
} if (m_Generations < Pop.getGeneration()) {
msg = m_Generations + " generations reached.";
/** return true;
* Returns the tip text for this property }
* @return tip text for this property return false;
*/ }
public String generationsTipText() {
return "number of generations to evaluate."; @Override
} public String lastTerminationMessage() {
return msg;
}
@Override
public String toString() {
String ret = "Generations calls=" + m_Generations;
return ret;
}
public void setGenerations(int x) {
m_Generations = x;
}
public int getGenerations() {
return m_Generations;
}
/**
* Returns the tip text for this property
*
* @return tip text for this property
*/
public String generationsTipText() {
return "number of generations to evaluate.";
}
} }

View File

@ -215,6 +215,7 @@ public class Population extends ArrayList implements PopulationInterface, Clonea
* considered functional are omitted, such as archive, history and the * considered functional are omitted, such as archive, history and the
* listeners. * listeners.
*/ */
@Override
public boolean equals(Object o) { public boolean equals(Object o) {
if (!super.equals(o)) { if (!super.equals(o)) {
return false; return false;

View File

@ -159,13 +159,8 @@ public class StatisticsWithGUI extends AbstractStatistics implements Serializabl
} }
protected void initPlots(PopulationInterface pop, List<InterfaceAdditionalPopulationInformer> informerList) { protected void initPlots(PopulationInterface pop, List<InterfaceAdditionalPopulationInformer> informerList) {
if (TRACE) {
System.out.println("initPlots");
}
if (m_StatsParams instanceof StatisticsParameter) { if (m_StatsParams instanceof StatisticsParameter) {
// StringSelection ss = ((StatsParameter)m_StatsParams).getGraphSelection();
graphDesc = lastFieldSelection.getSelectedWithIndex(); graphDesc = lastFieldSelection.getSelectedWithIndex();
// for (int i=0; i<description.get(0).length; i++) graphDesc.add(description.get(0)[i]);
} else { } else {
graphDesc = null; graphDesc = null;
System.err.println("Error in StatisticsWithGUI.initPlots()!"); System.err.println("Error in StatisticsWithGUI.initPlots()!");

View File

@ -1,510 +1,464 @@
package eva2.tools.math; package eva2.tools.math;
import eva2.tools.EVAERROR;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.BitSet; import java.util.BitSet;
import java.util.Random; import java.util.Random;
import eva2.tools.EVAERROR;
public class RNG { public class RNG {
private static Random random;
private static long randomSeed;
/**
*
*/
static {
randomSeed=System.currentTimeMillis();
random=new Random(randomSeed);
}
/**
*
*/
public static void setRandomSeed(long new_seed) {
// counter++;
randomSeed = new_seed;
if (randomSeed == 0)
setRandomSeed();
else
random = new Random(randomSeed);
}
/** private static Random random;
* Set the random seed without replacing zero with current system time. private static long randomSeed;
*/
public static void setRandomSeedStrict(long new_seed) {
randomSeed = new_seed;
random.setSeed(randomSeed);
}
/** /**
* *
*/ */
public static void setRandomSeed() { static {
randomSeed = System.currentTimeMillis(); randomSeed = System.currentTimeMillis();
random = new Random(randomSeed); random = new Random(randomSeed);
} }
/** /**
* *
*/ */
public static void setRandom(Random base_random) { public static void setRandomSeed(long new_seed) {
random = base_random; // counter++;
} randomSeed = new_seed;
if (randomSeed == 0) {
setRandomSeed();
} else {
random = new Random(randomSeed);
}
}
/** /**
* * Set the random seed without replacing zero with current system time.
*/ */
public static long getRandomSeed() { public static void setRandomSeedStrict(long new_seed) {
return randomSeed; randomSeed = new_seed;
} random.setSeed(randomSeed);
}
/** /**
* Returns 0 or 1 evenly distributed. *
*/ */
public static int randomInt() { public static void setRandomSeed() {
return randomInt(0, 1); randomSeed = System.currentTimeMillis();
} random = new Random(randomSeed);
}
/** /**
* Returns an evenly distributes int value between zero and upperLim-1. *
* */
* @param upperLim public static void setRandom(Random base_random) {
* upper exclusive limit of the random int random = base_random;
*/ }
public static int randomInt(int upperLim) {
return randomInt(0, upperLim - 1);
}
/** /**
* This method returns a evenly distributed int value. The boundarys are *
* included. */
* public static long getRandomSeed() {
* @param lo return randomSeed;
* Lower bound. }
* @param hi
* Upper bound.
* @return int
*/
public static int randomInt(int lo, int hi) {
if (hi < lo) {
System.err.println("Invalid boundary values! Returning zero.");
return -1;
}
int result = (Math.abs(random.nextInt()) % (hi - lo + 1)) + lo;
if ((result < lo) || (result > hi)) {
System.err.println("Error, invalid value " + result
+ " in RNG.randomInt! boundaries were lo/hi: " + lo + " / "
+ hi);
result = Math.abs(random.nextInt() % (hi - lo + 1)) + lo;
}
return result;
}
/** /**
* This method returns a random permutation of n int values * Returns 0 or 1 evenly distributed.
* */
* @param length public static int randomInt() {
* The number of int values return randomInt(0, 1);
* @return The permutation [0-length-1] }
*/
public static int[] randomPerm(int length) {
ArrayList<Integer> intList = new ArrayList<Integer>(length);
int[] result = new int[length];
for (int i = 0; i < length; i++) {
intList.add(new Integer(i));
}
for (int i = 0; i < length - 1; i++) {
int index = randomInt(intList.size());
result[i] = intList.get(index);
intList.remove(index);
} /**
if (intList.size() > 1) * Returns an evenly distributes int value between zero and upperLim-1.
System.err.println("Error in randomPerm!"); *
result[length - 1] = intList.get(0); * @param upperLim upper exclusive limit of the random int
return result; */
} public static int randomInt(int upperLim) {
return randomInt(0, upperLim - 1);
}
/** This method returns a evenly distributed int value. /**
* The boundarys are included. * This method returns a evenly distributed int value. The boundarys are
* @param lo Lower bound. * included.
* @param hi Upper bound. *
* @return int * @param lo Lower bound.
*/ * @param hi Upper bound.
public static int randomInt(Random rand, int lo,int hi) { * @return int
if (hi<lo) { */
System.err.println("Invalid boundary values! Returning zero."); public static int randomInt(int lo, int hi) {
return -1; if (hi < lo) {
} System.err.println("Invalid boundary values! Returning zero.");
int result = (Math.abs(rand.nextInt())%(hi-lo+1))+lo; return -1;
if ((result < lo) || (result > hi)) { }
System.err.println("Error, invalid value " + result + " in RNG.randomInt! boundaries were lo/hi: " + lo + " / " + hi); int result = (Math.abs(random.nextInt()) % (hi - lo + 1)) + lo;
result = Math.abs(rand.nextInt()%(hi-lo+1))+lo; if ((result < lo) || (result > hi)) {
} System.err.println("Error, invalid value " + result
return result; + " in RNG.randomInt! boundaries were lo/hi: " + lo + " / "
} + hi);
result = Math.abs(random.nextInt() % (hi - lo + 1)) + lo;
}
return result;
}
/** /**
* Returns a random long between 0 and Long.MAX_VALUE-1 (inclusively). * This method returns a random permutation of n int values
*/ *
public static long randomLong() { * @param length The number of int values
return randomLong(0, Long.MAX_VALUE - 1); * @return The permutation [0-length-1]
} */
public static int[] randomPerm(int length) {
ArrayList<Integer> intList = new ArrayList<Integer>(length);
int[] result = new int[length];
for (int i = 0; i < length; i++) {
intList.add(new Integer(i));
}
for (int i = 0; i < length - 1; i++) {
int index = randomInt(intList.size());
result[i] = intList.get(index);
intList.remove(index);
/** }
* Returns a random long between the given values (inclusively). if (intList.size() > 1) {
*/ System.err.println("Error in randomPerm!");
public static long randomLong(long lo, long hi) { }
return (Math.abs(random.nextLong()) % (hi - lo + 1)) + lo; result[length - 1] = intList.get(0);
} return result;
}
/** /**
* * This method returns a evenly distributed int value. The boundarys are
*/ * included.
public static float randomFloat() { *
return random.nextFloat(); * @param lo Lower bound.
} * @param hi Upper bound.
* @return int
*/
public static int randomInt(Random rand, int lo, int hi) {
if (hi < lo) {
System.err.println("Invalid boundary values! Returning zero.");
return -1;
}
int result = (Math.abs(rand.nextInt()) % (hi - lo + 1)) + lo;
if ((result < lo) || (result > hi)) {
System.err.println("Error, invalid value " + result + " in RNG.randomInt! boundaries were lo/hi: " + lo + " / " + hi);
result = Math.abs(rand.nextInt() % (hi - lo + 1)) + lo;
}
return result;
}
/** /**
* * Returns a random long between 0 and Long.MAX_VALUE-1 (inclusively).
*/ */
public static float randomFloat(float lo, float hi) { public static long randomLong() {
return (hi - lo) * random.nextFloat() + lo; return randomLong(0, Long.MAX_VALUE - 1);
} }
/** /**
* A random double value between 0 and 1. * Returns a random long between the given values (inclusively).
*/ */
public static double randomDouble() { public static long randomLong(long lo, long hi) {
return random.nextDouble(); return (Math.abs(random.nextLong()) % (hi - lo + 1)) + lo;
} }
/** /**
* *
*/ */
public static double randomDouble(double lo,double hi) { public static float randomFloat() {
return (hi-lo)*random.nextDouble()+lo; return random.nextFloat();
} }
public static double randomDouble(Random rand, double lo,double hi) { /**
return (hi-lo)*rand.nextDouble()+lo; *
} */
public static float randomFloat(float lo, float hi) {
return (hi - lo) * random.nextFloat() + lo;
}
/** /**
* Create a uniform random vector within the given bounds. * A random double value between 0 and 1.
*/ */
public static double[] randomDoubleArray(double[] lo,double[] hi) { public static double randomDouble() {
double[] xin = new double[lo.length]; return random.nextDouble();
for (int i=0;i<lo.length;i++) }
xin[i] = (hi[i]-lo[i])*random.nextDouble()+lo[i];
return xin;
}
/** /**
* Create a uniform random vector within the given bounds. *
*/ */
public static double[] randomDoubleArray(double[][] range) { public static double randomDouble(double lo, double hi) {
double[] xin = new double[range.length]; return (hi - lo) * random.nextDouble() + lo;
for (int i=0;i<xin.length;i++) }
xin[i] = (range[i][1]-range[i][0])*random.nextDouble()+range[i][0];
return xin;
}
/** public static double randomDouble(Random rand, double lo, double hi) {
* Create a uniform random double vector within the given bounds (inclusive) in every dimension. return (hi - lo) * rand.nextDouble() + lo;
* }
* @param lower
* @param upper
* @param size
* @return
*/
public static double[] randomDoubleArray(double lower, double upper, int size) {
double[] result = new double[size];
for (int i = 0; i < result.length; i++) {
result[i] = RNG.randomDouble(lower, upper);
}
return result;
// double[] xin = new double[size];
// for (int i=0;i<size;i++)
// xin[i] = (hi-lo)*random.nextDouble()+lo;
// return xin;
}
public static double[] randomDoubleArray(Random rand, double lower, double upper, int size) { /**
double[] result = new double[size]; * Create a uniform random vector within the given bounds.
for (int i = 0; i < result.length; i++) { */
result[i] = RNG.randomDouble(rand, lower, upper); public static double[] randomDoubleArray(double[] lo, double[] hi) {
} double[] xin = new double[lo.length];
return result; for (int i = 0; i < lo.length; i++) {
} xin[i] = (hi[i] - lo[i]) * random.nextDouble() + lo[i];
/** }
* return xin;
*/ }
public static double[] randomDoubleArray(double[] lo,double[] hi,double[] xin) {
//counter++;
for (int i=0;i<lo.length;i++)
xin[i] = (hi[i]-lo[i])*random.nextDouble()+lo[i];
return xin;
}
/** /**
* Create a uniform random integer vector within the given bounds (inclusive) in every dimension. * Create a uniform random vector within the given bounds.
* */
* @param n public static double[] randomDoubleArray(double[][] range) {
* @param lower double[] xin = new double[range.length];
* @param upper for (int i = 0; i < xin.length; i++) {
* @return xin[i] = (range[i][1] - range[i][0]) * random.nextDouble() + range[i][0];
*/ }
public static int[] randomIntArray(int lower, int upper, int size) { return xin;
int[] result = new int[size]; }
for (int i = 0; i < result.length; i++) {
result[i] = RNG.randomInt(lower, upper);
}
return result;
}
public static int[] randomIntArray(Random rand, int lower, int upper, int size) { /**
int[] result = new int[size]; * Create a uniform random double vector within the given bounds (inclusive)
for (int i = 0; i < result.length; i++) { * in every dimension.
result[i] = RNG.randomInt(rand, lower, upper); *
} * @param lower
return result; * @param upper
} * @param size
/** * @return
* */
*/ public static double[] randomDoubleArray(double lower, double upper, int size) {
public static boolean randomBoolean() { double[] result = new double[size];
// counter++; for (int i = 0; i < result.length; i++) {
return (randomInt() == 1); result[i] = RNG.randomDouble(lower, upper);
} }
return result;
// double[] xin = new double[size];
// for (int i=0;i<size;i++)
// xin[i] = (hi-lo)*random.nextDouble()+lo;
// return xin;
}
/** public static double[] randomDoubleArray(Random rand, double lower, double upper, int size) {
* double[] result = new double[size];
*/ for (int i = 0; i < result.length; i++) {
public static int randomBit() { result[i] = RNG.randomDouble(rand, lower, upper);
// counter++; }
return randomInt(); return result;
} }
/** /**
* Create a random bitset with given cardinality and lengths, *
*/ */
public static BitSet randomBitSet(int cardinality, int length) { public static double[] randomDoubleArray(double[] lo, double[] hi, double[] xin) {
if (cardinality>length) { //counter++;
EVAERROR.errorMsgOnce("Error, invalid cardinality " + cardinality + " requested for bit length "+ length +", cardinality will be reduced."); for (int i = 0; i < lo.length; i++) {
cardinality=length; xin[i] = (hi[i] - lo[i]) * random.nextDouble() + lo[i];
} }
BitSet bs = new BitSet(length); return xin;
int[] perm = randomPerm(length); }
for (int i=0; i<cardinality; i++) {
bs.set(perm[i]);
}
return bs;
}
/**
* Create a random bitset with a given probability of 1 per bit.
*/
public static BitSet randomBitSet(double pSet, int length) {
BitSet bs = new BitSet(length);
for (int i=0; i<length; i++) {
if (flipCoin(pSet)) bs.set(i);
}
return bs;
}
/**
* Returns true with probability p.
*
* @param p
* @return true with probability p, else false
*/
public static boolean flipCoin(double p) {
// counter++;
return (randomDouble() < p ? true : false);
}
/** /**
* * Create a uniform random integer vector within the given bounds
*/ * (inclusive) in every dimension.
public static float gaussianFloat(float dev) { *
// counter++; * @param n
return (float) random.nextGaussian() * dev; * @param lower
} * @param upper
* @return
*/
public static int[] randomIntArray(int lower, int upper, int size) {
int[] result = new int[size];
for (int i = 0; i < result.length; i++) {
result[i] = RNG.randomInt(lower, upper);
}
return result;
}
/** public static int[] randomIntArray(Random rand, int lower, int upper, int size) {
* Return a Gaussian double with mean 0 and deviation dev. int[] result = new int[size];
* for (int i = 0; i < result.length; i++) {
* @param dev result[i] = RNG.randomInt(rand, lower, upper);
* the deviation of the distribution. }
* @return a Gaussian double with mean 0 and given deviation. return result;
*/ }
public static double gaussianDouble(double dev) {
// counter++;
return random.nextGaussian() * dev;
}
/** /**
* *
*/ */
public static float exponentialFloat(float mean) { public static boolean randomBoolean() {
// counter++; // counter++;
return (float) (-mean * Math.log(randomDouble())); return (randomInt() == 1);
} }
/** /**
* *
*/ */
public static double exponentialDouble(double mean) { public static int randomBit() {
// counter++; // counter++;
return -mean * Math.log(randomDouble()); return randomInt();
} }
/** /**
* Returns a vector denoting a random point around the center - inside a * Create a random bitset with given cardinality and lengths,
* hypersphere of uniform distribution if nonUnif=0, - inside a hypersphere */
* of non-uniform distribution if nonUnif > 0, - inside a D-Gaussian if public static BitSet randomBitSet(int cardinality, int length) {
* nonUnif < 0. For case 2, the nonUnif parameter is used as standard if (cardinality > length) {
* deviation (instead of 1/D), the parameter is not further used in the EVAERROR.errorMsgOnce("Error, invalid cardinality " + cardinality + " requested for bit length " + length + ", cardinality will be reduced.");
* other two cases. Original code by Maurice Clerc, from the TRIBES package cardinality = length;
* }
* @param center BitSet bs = new BitSet(length);
* center point of the distribution int[] perm = randomPerm(length);
* @param radius for (int i = 0; i < cardinality; i++) {
* radius of the distribution bs.set(perm[i]);
* @param nonUnif }
* kind of distribution return bs;
* }
**/
public static double[] randHypersphere(double[] center, double radius,
double nonUnif) {
double[] x = new double[center.length];
int j;
double xLen, r;
int D = center.length;
// ----------------------------------- Step 1. Direction /**
xLen = 0; * Create a random bitset with a given probability of 1 per bit.
for (j = 0; j < D; j++) { */
r = gaussianDouble(1); public static BitSet randomBitSet(double pSet, int length) {
x[j] = r; BitSet bs = new BitSet(length);
xLen += x[j] * x[j]; for (int i = 0; i < length; i++) {
} if (flipCoin(pSet)) {
bs.set(i);
}
}
return bs;
}
xLen = Math.sqrt(xLen); /**
* Returns true with probability p.
*
* @param p
* @return true with probability p, else false
*/
public static boolean flipCoin(double p) {
// counter++;
return (randomDouble() < p ? true : false);
}
// ----------------------------------- Step 2. Random radius /**
*
*/
public static float gaussianFloat(float dev) {
// counter++;
return (float) random.nextGaussian() * dev;
}
r = randomDouble(); /**
if (nonUnif < 0) * Return a Gaussian double with mean 0 and deviation dev.
r = gaussianDouble(r / 2); // D-Gaussian *
else if (nonUnif > 0) * @param dev the deviation of the distribution.
r = Math.pow(r, nonUnif); // non-uniform hypersphere * @return a Gaussian double with mean 0 and given deviation.
else */
r = Math.pow(r, 1. / D); // Real hypersphere public static double gaussianDouble(double dev) {
// counter++;
return random.nextGaussian() * dev;
}
for (j = 0; j < D; j++) { /**
x[j] = center[j] + radius * r * x[j] / xLen; *
} */
return x; public static float exponentialFloat(float mean) {
} // counter++;
return (float) (-mean * Math.log(randomDouble()));
}
/** /**
* Adds Gaussian noise to a double vector *
* */
* @param v public static double exponentialDouble(double mean) {
* the double vector // counter++;
* @param dev return -mean * Math.log(randomDouble());
* the Gaussian deviation }
*/
public static void addNoise(double[] v, double dev) {
for (int i = 0; i < v.length; i++) {
// add noise to the value
v[i] += gaussianDouble(dev);
}
}
/** /**
* Create a normalized random vector with gaussian random double entries. * Returns a vector denoting a random point around the center - inside a
* * hypersphere of uniform distribution if nonUnif=0, - inside a hypersphere
* @param n * of non-uniform distribution if nonUnif > 0, - inside a D-Gaussian if
* @param dev * nonUnif < 0. For case 2, the nonUnif parameter is used as standard
* @return * deviation (instead of 1/D), the parameter is not further used in the
*/ * other two cases. Original code by Maurice Clerc, from the TRIBES package
public static double[] gaussianVector(int n, double dev, boolean normalize) { *
double[] result = new double[n];
gaussianVector(dev, result, normalize);
return result;
}
/** *
* Create a normalized random vector with gaussian random double entries. * @param center center point of the distribution
* * @param radius radius of the distribution
* @param n * @param nonUnif kind of distribution
* @return *
*/ *
public static double[] gaussianVector(double dev, double[] result, */
boolean normalize) { public static double[] randHypersphere(double[] center, double radius,
for (int i = 0; i < result.length; i++) { double nonUnif) {
result[i] = RNG.gaussianDouble(dev); double[] x = new double[center.length];
} int j;
if (normalize) double xLen, r;
Mathematics.normVect(result, result); int D = center.length;
return result;
}
// public static int testRndInt(long seed, int bits) { // ----------------------------------- Step 1. Direction
// return (int)(seed >>> (48 - bits)); xLen = 0;
// } for (j = 0; j < D; j++) {
// r = gaussianDouble(1);
// public static int testRandomInt(int lo, int hi, long seed) { x[j] = r;
// if (hi<lo) { xLen += x[j] * x[j];
// System.err.println("Invalid boundary values! Returning zero."); }
// return -1;
// }
// int result = (Math.abs(testRndInt(seed,32))%(hi-lo+1))+lo;
// if ((result < lo) || (result > hi)) {
// System.err.println("Error, invalid value " + result +
// " in RNG.randomInt! boundaries were lo/hi: " + lo + " / " + hi);
// System.out.println("Error, invalid value " + result +
// " in RNG.randomInt! boundaries were lo/hi: " + lo + " / " + hi);
// }
// return result;
// }
//
// public static void testRand(long initSeed) {
// for (long seed=initSeed; seed<=Long.MAX_VALUE; seed++) {
// int rnd = testRandomInt(0,8,seed);
// if (seed % 100000000 == 0) System.out.println("Seed at " + seed);
// }
// }
// public static void main(String[] args) { xLen = Math.sqrt(xLen);
// testRand(24000000000l);
// System.out.println("RNG Done");
// double[] v = new double[2];
// for (int i=0; i<1000; i++) {
// gaussianVector(1., v, false);
// EVAHELP.logString(Arrays.toString(v)+"\n", "randtest.dat");
// // System.out.println(Arrays.toString(v));
// }
// }
/** // ----------------------------------- Step 2. Random radius
* Create a uniform random double vector within the given bounds (inclusive)
* in every dimension. r = randomDouble();
* if (nonUnif < 0) {
* @param n r = gaussianDouble(r / 2); // D-Gaussian
* @param lower } else if (nonUnif > 0) {
* @param upper r = Math.pow(r, nonUnif); // non-uniform hypersphere
* @return } else {
*/ r = Math.pow(r, 1. / D); // Real hypersphere
// public static double[] randomVector(int n, double lower, double upper) { }
// double[] result = new double[n]; for (j = 0; j < D; j++) {
// for (int i = 0; i < result.length; i++) { x[j] = center[j] + radius * r * x[j] / xLen;
// result[i] = RNG.randomDouble(lower, upper); }
// } return x;
// return result; }
// }
/**
* Adds Gaussian noise to a double vector
*
* @param v the double vector
* @param dev the Gaussian deviation
*/
public static void addNoise(double[] v, double dev) {
for (int i = 0; i < v.length; i++) {
// add noise to the value
v[i] += gaussianDouble(dev);
}
}
/**
* Create a normalized random vector with gaussian random double entries.
*
* @param n
* @param dev
* @return
*/
public static double[] gaussianVector(int n, double dev, boolean normalize) {
double[] result = new double[n];
gaussianVector(dev, result, normalize);
return result;
}
/**
* Create a normalized random vector with gaussian random double entries.
*
* @param n
* @return
*/
public static double[] gaussianVector(double dev, double[] result,
boolean normalize) {
for (int i = 0; i < result.length; i++) {
result[i] = RNG.gaussianDouble(dev);
}
if (normalize) {
Mathematics.normVect(result, result);
}
return result;
}
} }