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,11 +9,14 @@ 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; private PropertyEditor propertyEditor;
/** /**
* *
*/ */
@ -21,18 +24,17 @@ public class PropertyText extends JTextField {
super(pe.getAsText()); super(pe.getAsText());
this.setBorder(BorderFactory.createEmptyBorder()); this.setBorder(BorderFactory.createEmptyBorder());
propertyEditor = pe; propertyEditor = pe;
// m_Editor.addPropertyChangeListener(new PropertyChangeListener() {
// public void propertyChange(PropertyChangeEvent evt) {
// updateUs();
// }
// });
addKeyListener(new KeyAdapter() { addKeyListener(new KeyAdapter() {
@Override
public void keyReleased(KeyEvent e) { public void keyReleased(KeyEvent e) {
//if (e.getKeyCode() == KeyEvent.VK_ENTER) //if (e.getKeyCode() == KeyEvent.VK_ENTER)
updateEditor(); updateEditor();
} }
}); });
addFocusListener(new FocusAdapter() { addFocusListener(new FocusAdapter() {
@Override
public void focusLost(FocusEvent e) { public void focusLost(FocusEvent e) {
updateEditor(); updateEditor();
} }

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,20 +1,14 @@
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 {
@ -22,125 +16,165 @@ public class MutateGAInvertBits implements InterfaceMutation, java.io.Serializab
private int m_MaxInveredBits = 5; private int m_MaxInveredBits = 5;
public MutateGAInvertBits() { public MutateGAInvertBits() {
} }
public MutateGAInvertBits(MutateGAInvertBits mutator) { public MutateGAInvertBits(MutateGAInvertBits mutator) {
this.m_NumberOfMutations = mutator.m_NumberOfMutations; this.m_NumberOfMutations = mutator.m_NumberOfMutations;
this.m_MaxInveredBits = mutator.m_MaxInveredBits; this.m_MaxInveredBits = mutator.m_MaxInveredBits;
} }
/** 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 MutateGAInvertBits(this); return new MutateGAInvertBits(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
* actually the same.
*
* @param mutator The other mutation operator * @param mutator The other mutation operator
*/ */
@Override
public boolean equals(Object mutator) { public boolean equals(Object mutator) {
if (mutator instanceof MutateGAInvertBits) { if (mutator instanceof MutateGAInvertBits) {
MutateGAInvertBits mut = (MutateGAInvertBits)mutator; MutateGAInvertBits mut = (MutateGAInvertBits) mutator;
if (this.m_NumberOfMutations != mut.m_NumberOfMutations) return false; if (this.m_NumberOfMutations != mut.m_NumberOfMutations) {
if (this.m_MaxInveredBits != mut.m_MaxInveredBits) return false; return false;
}
if (this.m_MaxInveredBits != mut.m_MaxInveredBits) {
return false;
}
return true; return true;
} else return false; } else {
return false;
}
} }
/** This method allows you to init the mutation operator /**
* This method allows you to init the mutation operator
*
* @param individual The individual that will be mutated. * @param individual The individual that will be mutated.
* @param opt The optimization problem. * @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());
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
* parameters or to deal in some other way with the crossover event.
*
* @param indy1 The original mother * @param indy1 The original mother
* @param partners The original partners * @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 inversion mutation"; 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. /**
* 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 invert n bits mutation"; return "GA invert n bits 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 "This mutation operator inverts n successive bits."; return "This mutation operator inverts n successive bits.";
} }
/** 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) {
mutations = 0;
}
this.m_NumberOfMutations = mutations; this.m_NumberOfMutations = mutations;
} }
public int getNumberOfMutations() { public int getNumberOfMutations() {
return this.m_NumberOfMutations; return this.m_NumberOfMutations;
} }
public String numberOfMutationsTipText() { public String numberOfMutationsTipText() {
return "The number of inversion events."; return "The number of inversion events.";
} }
/** This method allows you to set the macimun number if succesively
* inverted bits /**
* This method allows you to set the macimun number if succesively inverted
* bits
*
* @param mutations The number of successively inverted bits. * @param mutations The number of successively inverted bits.
*/ */
public void setMaxInveredBits(int mutations) { public void setMaxInveredBits(int mutations) {
if (mutations < 0) mutations = 0; if (mutations < 0) {
mutations = 0;
}
this.m_MaxInveredBits = mutations; this.m_MaxInveredBits = mutations;
} }
public int getMaxInveredBits() { public int getMaxInveredBits() {
return this.m_MaxInveredBits; return this.m_MaxInveredBits;
} }
public String maxInveredBitsTipText() { public String maxInveredBitsTipText() {
return "The number of successive bits to be inverted."; 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
* actually the same.
*
* @param mutator The other mutation operator * @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 /**
* This method allows you to init the mutation operator
*
* @param individual The individual that will be mutated. * @param individual The individual that will be mutated.
* @param opt The optimization problem. * @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
* parameters or to deal in some other way with the crossover event.
*
* @param indy1 The original mother * @param indy1 The original mother
* @param partners The original partners * @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,32 +9,25 @@ 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 * Number of fitness calls on the problem which is optimized
*/ */
protected int m_Generations = 100; protected int m_Generations = 100;
private String msg = ""; private String msg = "";
public void init(InterfaceOptimizationProblem prob){ @Override
public void init(InterfaceOptimizationProblem prob) {
msg = "Not terminated."; msg = "Not terminated.";
} }
@ -49,24 +42,28 @@ Serializable {
m_Generations = gens; m_Generations = gens;
} }
@Override
public boolean isTerminated(InterfaceSolutionSet solSet) { public boolean isTerminated(InterfaceSolutionSet solSet) {
return isTerminated(solSet.getCurrentPopulation()); return isTerminated(solSet.getCurrentPopulation());
} }
@Override
public boolean isTerminated(PopulationInterface Pop) { public boolean isTerminated(PopulationInterface Pop) {
if (m_Generations<Pop.getGeneration()) { if (m_Generations < Pop.getGeneration()) {
msg = m_Generations + " generations reached."; msg = m_Generations + " generations reached.";
return true; return true;
} }
return false; return false;
} }
@Override
public String lastTerminationMessage() { public String lastTerminationMessage() {
return msg; return msg;
} }
@Override
public String toString() { public String toString() {
String ret = "Generations calls="+m_Generations; String ret = "Generations calls=" + m_Generations;
return ret; return ret;
} }
@ -80,6 +77,7 @@ Serializable {
/** /**
* Returns the tip text for this property * Returns the tip text for this property
*
* @return tip text for this property * @return tip text for this property
*/ */
public String generationsTipText() { public String generationsTipText() {

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,33 +1,35 @@
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 Random random;
private static long randomSeed; private static long randomSeed;
/** /**
* *
*/ */
static { static {
randomSeed=System.currentTimeMillis(); randomSeed = System.currentTimeMillis();
random=new Random(randomSeed); random = new Random(randomSeed);
} }
/** /**
* *
*/ */
public static void setRandomSeed(long new_seed) { public static void setRandomSeed(long new_seed) {
// counter++; // counter++;
randomSeed = new_seed; randomSeed = new_seed;
if (randomSeed == 0) if (randomSeed == 0) {
setRandomSeed(); setRandomSeed();
else } else {
random = new Random(randomSeed); random = new Random(randomSeed);
} }
}
/** /**
* Set the random seed without replacing zero with current system time. * Set the random seed without replacing zero with current system time.
@ -69,8 +71,7 @@ public class RNG {
/** /**
* Returns an evenly distributes int value between zero and upperLim-1. * Returns an evenly distributes int value between zero and upperLim-1.
* *
* @param upperLim * @param upperLim upper exclusive limit of the random int
* upper exclusive limit of the random int
*/ */
public static int randomInt(int upperLim) { public static int randomInt(int upperLim) {
return randomInt(0, upperLim - 1); return randomInt(0, upperLim - 1);
@ -80,10 +81,8 @@ public class RNG {
* This method returns a evenly distributed int value. The boundarys are * This method returns a evenly distributed int value. The boundarys are
* included. * included.
* *
* @param lo * @param lo Lower bound.
* Lower bound. * @param hi Upper bound.
* @param hi
* Upper bound.
* @return int * @return int
*/ */
public static int randomInt(int lo, int hi) { public static int randomInt(int lo, int hi) {
@ -104,8 +103,7 @@ public class RNG {
/** /**
* This method returns a random permutation of n int values * This method returns a random permutation of n int values
* *
* @param length * @param length The number of int values
* The number of int values
* @return The permutation [0-length-1] * @return The permutation [0-length-1]
*/ */
public static int[] randomPerm(int length) { public static int[] randomPerm(int length) {
@ -120,27 +118,30 @@ public class RNG {
intList.remove(index); intList.remove(index);
} }
if (intList.size() > 1) if (intList.size() > 1) {
System.err.println("Error in randomPerm!"); System.err.println("Error in randomPerm!");
}
result[length - 1] = intList.get(0); result[length - 1] = intList.get(0);
return result; return result;
} }
/** This method returns a evenly distributed int value. /**
* The boundarys are included. * This method returns a evenly distributed int value. The boundarys are
* included.
*
* @param lo Lower bound. * @param lo Lower bound.
* @param hi Upper bound. * @param hi Upper bound.
* @return int * @return int
*/ */
public static int randomInt(Random rand, int lo,int hi) { public static int randomInt(Random rand, int lo, int hi) {
if (hi<lo) { if (hi < lo) {
System.err.println("Invalid boundary values! Returning zero."); System.err.println("Invalid boundary values! Returning zero.");
return -1; return -1;
} }
int result = (Math.abs(rand.nextInt())%(hi-lo+1))+lo; int result = (Math.abs(rand.nextInt()) % (hi - lo + 1)) + lo;
if ((result < lo) || (result > hi)) { if ((result < lo) || (result > hi)) {
System.err.println("Error, invalid value " + result + " in RNG.randomInt! boundaries were lo/hi: " + lo + " / " + 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; result = Math.abs(rand.nextInt() % (hi - lo + 1)) + lo;
} }
return result; return result;
} }
@ -183,21 +184,22 @@ public class RNG {
/** /**
* *
*/ */
public static double randomDouble(double lo,double hi) { public static double randomDouble(double lo, double hi) {
return (hi-lo)*random.nextDouble()+lo; return (hi - lo) * random.nextDouble() + lo;
} }
public static double randomDouble(Random rand, double lo,double hi) { public static double randomDouble(Random rand, double lo, double hi) {
return (hi-lo)*rand.nextDouble()+lo; return (hi - lo) * rand.nextDouble() + lo;
} }
/** /**
* Create a uniform random vector within the given bounds. * Create a uniform random vector within the given bounds.
*/ */
public static double[] randomDoubleArray(double[] lo,double[] hi) { public static double[] randomDoubleArray(double[] lo, double[] hi) {
double[] xin = new double[lo.length]; double[] xin = new double[lo.length];
for (int i=0;i<lo.length;i++) for (int i = 0; i < lo.length; i++) {
xin[i] = (hi[i]-lo[i])*random.nextDouble()+lo[i]; xin[i] = (hi[i] - lo[i]) * random.nextDouble() + lo[i];
}
return xin; return xin;
} }
@ -206,13 +208,15 @@ public class RNG {
*/ */
public static double[] randomDoubleArray(double[][] range) { public static double[] randomDoubleArray(double[][] range) {
double[] xin = new double[range.length]; double[] xin = new double[range.length];
for (int i=0;i<xin.length;i++) for (int i = 0; i < xin.length; i++) {
xin[i] = (range[i][1]-range[i][0])*random.nextDouble()+range[i][0]; xin[i] = (range[i][1] - range[i][0]) * random.nextDouble() + range[i][0];
}
return xin; return xin;
} }
/** /**
* Create a uniform random double vector within the given bounds (inclusive) in every dimension. * Create a uniform random double vector within the given bounds (inclusive)
* in every dimension.
* *
* @param lower * @param lower
* @param upper * @param upper
@ -238,18 +242,21 @@ public class RNG {
} }
return result; return result;
} }
/** /**
* *
*/ */
public static double[] randomDoubleArray(double[] lo,double[] hi,double[] xin) { public static double[] randomDoubleArray(double[] lo, double[] hi, double[] xin) {
//counter++; //counter++;
for (int i=0;i<lo.length;i++) for (int i = 0; i < lo.length; i++) {
xin[i] = (hi[i]-lo[i])*random.nextDouble()+lo[i]; xin[i] = (hi[i] - lo[i]) * random.nextDouble() + lo[i];
}
return xin; return xin;
} }
/** /**
* Create a uniform random integer vector within the given bounds (inclusive) in every dimension. * Create a uniform random integer vector within the given bounds
* (inclusive) in every dimension.
* *
* @param n * @param n
* @param lower * @param lower
@ -271,6 +278,7 @@ public class RNG {
} }
return result; return result;
} }
/** /**
* *
*/ */
@ -291,13 +299,13 @@ public class RNG {
* Create a random bitset with given cardinality and lengths, * Create a random bitset with given cardinality and lengths,
*/ */
public static BitSet randomBitSet(int cardinality, int length) { public static BitSet randomBitSet(int cardinality, int length) {
if (cardinality>length) { if (cardinality > length) {
EVAERROR.errorMsgOnce("Error, invalid cardinality " + cardinality + " requested for bit length "+ length +", cardinality will be reduced."); EVAERROR.errorMsgOnce("Error, invalid cardinality " + cardinality + " requested for bit length " + length + ", cardinality will be reduced.");
cardinality=length; cardinality = length;
} }
BitSet bs = new BitSet(length); BitSet bs = new BitSet(length);
int[] perm = randomPerm(length); int[] perm = randomPerm(length);
for (int i=0; i<cardinality; i++) { for (int i = 0; i < cardinality; i++) {
bs.set(perm[i]); bs.set(perm[i]);
} }
return bs; return bs;
@ -308,8 +316,10 @@ public class RNG {
*/ */
public static BitSet randomBitSet(double pSet, int length) { public static BitSet randomBitSet(double pSet, int length) {
BitSet bs = new BitSet(length); BitSet bs = new BitSet(length);
for (int i=0; i<length; i++) { for (int i = 0; i < length; i++) {
if (flipCoin(pSet)) bs.set(i); if (flipCoin(pSet)) {
bs.set(i);
}
} }
return bs; return bs;
} }
@ -336,8 +346,7 @@ public class RNG {
/** /**
* Return a Gaussian double with mean 0 and deviation dev. * Return a Gaussian double with mean 0 and deviation dev.
* *
* @param dev * @param dev the deviation of the distribution.
* the deviation of the distribution.
* @return a Gaussian double with mean 0 and given deviation. * @return a Gaussian double with mean 0 and given deviation.
*/ */
public static double gaussianDouble(double dev) { public static double gaussianDouble(double dev) {
@ -369,14 +378,14 @@ public class RNG {
* deviation (instead of 1/D), the parameter is not further used in the * 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 * other two cases. Original code by Maurice Clerc, from the TRIBES package
* *
* @param center
* center point of the distribution
* @param radius
* radius of the distribution
* @param nonUnif
* kind of distribution
* *
**/ * @param center center point of the distribution
* @param radius radius of the distribution
* @param nonUnif kind of distribution
*
*
*/
public static double[] randHypersphere(double[] center, double radius, public static double[] randHypersphere(double[] center, double radius,
double nonUnif) { double nonUnif) {
double[] x = new double[center.length]; double[] x = new double[center.length];
@ -397,13 +406,13 @@ public class RNG {
// ----------------------------------- Step 2. Random radius // ----------------------------------- Step 2. Random radius
r = randomDouble(); r = randomDouble();
if (nonUnif < 0) if (nonUnif < 0) {
r = gaussianDouble(r / 2); // D-Gaussian r = gaussianDouble(r / 2); // D-Gaussian
else if (nonUnif > 0) } else if (nonUnif > 0) {
r = Math.pow(r, nonUnif); // non-uniform hypersphere r = Math.pow(r, nonUnif); // non-uniform hypersphere
else } else {
r = Math.pow(r, 1. / D); // Real hypersphere r = Math.pow(r, 1. / D); // Real hypersphere
}
for (j = 0; j < D; j++) { for (j = 0; j < D; j++) {
x[j] = center[j] + radius * r * x[j] / xLen; x[j] = center[j] + radius * r * x[j] / xLen;
} }
@ -413,10 +422,8 @@ public class RNG {
/** /**
* Adds Gaussian noise to a double vector * Adds Gaussian noise to a double vector
* *
* @param v * @param v the double vector
* the double vector * @param dev the Gaussian deviation
* @param dev
* the Gaussian deviation
*/ */
public static void addNoise(double[] v, double dev) { public static void addNoise(double[] v, double dev) {
for (int i = 0; i < v.length; i++) { for (int i = 0; i < v.length; i++) {
@ -449,62 +456,9 @@ public class RNG {
for (int i = 0; i < result.length; i++) { for (int i = 0; i < result.length; i++) {
result[i] = RNG.gaussianDouble(dev); result[i] = RNG.gaussianDouble(dev);
} }
if (normalize) if (normalize) {
Mathematics.normVect(result, result); Mathematics.normVect(result, result);
}
return result; return result;
} }
// public static int testRndInt(long seed, int bits) {
// return (int)(seed >>> (48 - bits));
// }
//
// public static int testRandomInt(int lo, int hi, long seed) {
// if (hi<lo) {
// 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) {
// 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));
// }
// }
/**
* Create a uniform random double vector within the given bounds (inclusive)
* in every dimension.
*
* @param n
* @param lower
* @param upper
* @return
*/
// public static double[] randomVector(int n, double lower, double upper) {
// double[] result = new double[n];
// for (int i = 0; i < result.length; i++) {
// result[i] = RNG.randomDouble(lower, upper);
// }
// return result;
// }
} }