From 58141628766e7050508bba783c8256859e723a07 Mon Sep 17 00:00:00 2001 From: Fabian Becker Date: Fri, 29 Jun 2012 13:08:52 +0000 Subject: [PATCH] Code cleanup. --- src/eva2/gui/FunctionArea.java | 5 +- src/eva2/gui/GenericArrayEditor.java | 3 + src/eva2/gui/PropertyText.java | 98 +- .../go/individuals/InterfaceGAIndividual.java | 6 +- .../mutation/MutateGAInvertBits.java | 268 +++--- .../go/operators/mutation/MutateGANBit.java | 121 ++- .../terminators/GenerationTerminator.java | 120 ++- .../server/go/populations/Population.java | 1 + src/eva2/server/stat/StatisticsWithGUI.java | 5 - src/eva2/tools/math/RNG.java | 876 +++++++++--------- 10 files changed, 761 insertions(+), 742 deletions(-) diff --git a/src/eva2/gui/FunctionArea.java b/src/eva2/gui/FunctionArea.java index 29c3b1ae..1fa86123 100644 --- a/src/eva2/gui/FunctionArea.java +++ b/src/eva2/gui/FunctionArea.java @@ -47,6 +47,7 @@ import eva2.tools.chart2d.DPoint; import eva2.tools.chart2d.DPointIcon; import eva2.tools.chart2d.DPointSet; import eva2.tools.chart2d.ScaledBorder; +import java.util.logging.Level; import java.util.logging.Logger; /* @@ -740,8 +741,8 @@ public class FunctionArea extends DArea implements Serializable { out.flush(); out.close(); return true; - } catch (Exception e) { - System.err.println("Error on data export:" + e.getMessage()); + } catch (Exception ex) { + LOGGER.log(Level.WARNING, "Error while writing to file.", ex); return false; } } diff --git a/src/eva2/gui/GenericArrayEditor.java b/src/eva2/gui/GenericArrayEditor.java index 876287cc..efa0c727 100644 --- a/src/eva2/gui/GenericArrayEditor.java +++ b/src/eva2/gui/GenericArrayEditor.java @@ -356,6 +356,9 @@ public class GenericArrayEditor extends JPanel implements PropertyEditor { view = new PropertyValueSelector(editor); } else if (editor.getAsText() != null) { view = new PropertyText(editor); + } else if (view == null) { + /* Dirty hack to view PropertyDoubleArray component */ + view = new PropertyText(editor); } } if (view == null) { diff --git a/src/eva2/gui/PropertyText.java b/src/eva2/gui/PropertyText.java index b4fb8597..0fdf53db 100644 --- a/src/eva2/gui/PropertyText.java +++ b/src/eva2/gui/PropertyText.java @@ -9,57 +9,59 @@ import javax.swing.BorderFactory; 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 { - 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(); - } - }); - } - /** - * - */ - protected void updateEditor() { - try { - String x = getText(); - if (!propertyEditor.getAsText().equals(x)) { - propertyEditor.setAsText(x); + private PropertyEditor propertyEditor; + + /** + * + */ + public PropertyText(PropertyEditor pe) { + super(pe.getAsText()); + 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()); - } - } catch (IllegalArgumentException ex) { + } + } catch (IllegalArgumentException ex) { // System.err.println("Warning: Couldnt set value (PropertyText)"); - } - } - - public boolean checkConsistency() { - String x = getText(); - return x.equals(propertyEditor.getAsText()); - } - - public void updateFromEditor() { - setText(propertyEditor.getAsText()); - } + } + } + + public boolean checkConsistency() { + String x = getText(); + return x.equals(propertyEditor.getAsText()); + } + + public void updateFromEditor() { + setText(propertyEditor.getAsText()); + } } diff --git a/src/eva2/server/go/individuals/InterfaceGAIndividual.java b/src/eva2/server/go/individuals/InterfaceGAIndividual.java index c5a2e527..d09b95cc 100644 --- a/src/eva2/server/go/individuals/InterfaceGAIndividual.java +++ b/src/eva2/server/go/individuals/InterfaceGAIndividual.java @@ -13,12 +13,14 @@ import java.util.BitSet; */ 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 */ 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 * getBinaryData() you can directly alter the genotype without using * this method. diff --git a/src/eva2/server/go/operators/mutation/MutateGAInvertBits.java b/src/eva2/server/go/operators/mutation/MutateGAInvertBits.java index 8ae31302..3acb4f76 100644 --- a/src/eva2/server/go/operators/mutation/MutateGAInvertBits.java +++ b/src/eva2/server/go/operators/mutation/MutateGAInvertBits.java @@ -1,147 +1,181 @@ package eva2.server.go.operators.mutation; - -import java.util.BitSet; - import eva2.server.go.individuals.AbstractEAIndividual; import eva2.server.go.individuals.InterfaceGAIndividual; import eva2.server.go.populations.Population; import eva2.server.go.problems.InterfaceOptimizationProblem; 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 { - private int m_NumberOfMutations = 1; - private int m_MaxInveredBits = 5; + private int m_NumberOfMutations = 1; + private int m_MaxInveredBits = 5; - 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; + public MutateGAInvertBits() { } - /** This method allows you to init the mutation operator - * @param individual The individual that will be mutated. - * @param opt The optimization problem. + 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 */ + @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) { + } - } - - /** This method will mutate a given AbstractEAIndividual. If the individual - * doesn't implement InterfaceGAIndividual nothing happens. - * @param individual The individual that is to be mutated - */ - public void mutate(AbstractEAIndividual individual) { - //System.out.println("Before Mutate: " +((GAIndividual)individual).getSolutionRepresentationFor()); - if (individual instanceof InterfaceGAIndividual) { - BitSet tmpBitSet = ((InterfaceGAIndividual)individual).getBGenotype(); - int[][] mutationIndices = new int[this.m_NumberOfMutations][2]; - for (int i = 0; i < mutationIndices.length; i++) { - mutationIndices[i][0] = RNG.randomInt(0, ((InterfaceGAIndividual)individual).getGenotypeLength());; + /** + * This method will mutate a given AbstractEAIndividual. If the individual + * doesn't implement InterfaceGAIndividual nothing happens. + * + * @param individual The individual that is to be mutated + */ + @Override + public void mutate(AbstractEAIndividual individual) { + if (individual instanceof InterfaceGAIndividual) { + BitSet tmpBitSet = ((InterfaceGAIndividual) individual).getBGenotype(); + int[][] mutationIndices = new int[this.m_NumberOfMutations][2]; + for (int i = 0; i < mutationIndices.length; i++) { + mutationIndices[i][0] = RNG.randomInt(0, ((InterfaceGAIndividual) individual).getGenotypeLength());; mutationIndices[i][1] = RNG.randomInt(0, this.m_MaxInveredBits);; } - // double instances of mutationIndices could be checked here... *sigh* - for (int i = 0; i < mutationIndices.length; i++) { - 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()) { - tmpBitSet.flip(0, (mutationIndices[i][0]+ mutationIndices[i][1])-((InterfaceGAIndividual)individual).getGenotypeLength()); + // ToDo: double instances of mutationIndices could be checked here... *sigh* + for (int i = 0; i < mutationIndices.length; i++) { + 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()) { + tmpBitSet.flip(0, (mutationIndices[i][0] + mutationIndices[i][1]) - ((InterfaceGAIndividual) individual).getGenotypeLength()); } - } - ((InterfaceGAIndividual)individual).SetBGenotype(tmpBitSet); - } - //System.out.println("After Mutate: " +((GAIndividual)individual).getSolutionRepresentationFor()); - } + } + ((InterfaceGAIndividual) individual).SetBGenotype(tmpBitSet); + } + } - /** 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 partners The original partners + /** + * 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 partners The original partners */ + @Override public void crossoverOnStrategyParameters(AbstractEAIndividual indy1, Population partners) { // nothing to do here } - /** This method allows you to get a string representation of the mutation - * operator - * @return A descriptive string. - */ - public String getStringRepresentation() { - return "GA inversion mutation"; - } + /** + * This method allows you to get a string representation of the mutation + * operator + * + * @return A descriptive string. + */ + @Override + public String getStringRepresentation() { + return "GA inversion mutation"; + } -/********************************************************************************************************************** - * These are for GUI - */ - /** This method allows the CommonJavaObjectEditorPanel to read the - * name to the current object. - * @return The name. - */ - public String getName() { - return "GA invert n bits mutation"; - } - /** This method returns a global info string - * @return description - */ - public static String globalInfo() { - return "This mutation operator inverts n successive bits."; - } + /** + * These are for GUI + */ + + /** + * This method allows the CommonJavaObjectEditorPanel to read the name to + * the current object. + * + * @return The name. + */ + public String getName() { + return "GA invert n bits mutation"; + } - /** This method allows you to set the number of mutations that occur in the - * genotype. - * @param mutations The number of mutations. - */ - public void setNumberOfMutations(int mutations) { - if (mutations < 0) mutations = 0; - this.m_NumberOfMutations = mutations; - } - public int getNumberOfMutations() { - return this.m_NumberOfMutations; - } - 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."; - } + /** + * This method returns a global info string + * + * @return description + */ + 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. + * + * @param mutations The number of mutations. + */ + public void setNumberOfMutations(int mutations) { + if (mutations < 0) { + mutations = 0; + } + this.m_NumberOfMutations = mutations; + } + + public int getNumberOfMutations() { + return this.m_NumberOfMutations; + } + + 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."; + } } \ No newline at end of file diff --git a/src/eva2/server/go/operators/mutation/MutateGANBit.java b/src/eva2/server/go/operators/mutation/MutateGANBit.java index eeb24588..1e3e3620 100644 --- a/src/eva2/server/go/operators/mutation/MutateGANBit.java +++ b/src/eva2/server/go/operators/mutation/MutateGANBit.java @@ -1,122 +1,151 @@ package eva2.server.go.operators.mutation; - -import java.util.BitSet; - import eva2.server.go.individuals.AbstractEAIndividual; import eva2.server.go.individuals.InterfaceGAIndividual; import eva2.server.go.populations.Population; import eva2.server.go.problems.InterfaceOptimizationProblem; 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 { - private int m_NumberOfMutations = 1; + + private int numberOfMutations = 1; public MutateGANBit() { - } + 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 */ + @Override public Object clone() { return new MutateGANBit(this); } - - /** This method allows you to evaluate wether two mutation operators - * are actually the same. - * @param mutator The other mutation operator + + /** + * 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 MutateGANBit) { - MutateGANBit mut = (MutateGANBit)mutator; - if (this.m_NumberOfMutations != mut.m_NumberOfMutations) return false; + MutateGANBit mut = (MutateGANBit) mutator; + if (this.numberOfMutations != mut.numberOfMutations) { + return false; + } 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. - * @param opt The optimization problem. + /** + * 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) { - } - /** 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. - * @param individual The individual that is to be mutated + * + * @param individual The individual that is to be mutated */ + @Override public void mutate(AbstractEAIndividual individual) { //System.out.println("Before Mutate: " +((GAIndividual)individual).getSolutionRepresentationFor()); if (individual instanceof InterfaceGAIndividual) { - BitSet tmpBitSet = ((InterfaceGAIndividual)individual).getBGenotype(); - int[] mutationIndices = new int[this.m_NumberOfMutations]; - for (int i = 0; i < mutationIndices.length; i++) mutationIndices[i] = RNG.randomInt(0, ((InterfaceGAIndividual)individual).getGenotypeLength());; + BitSet tmpBitSet = ((InterfaceGAIndividual) individual).getBGenotype(); + int[] mutationIndices = new int[this.numberOfMutations]; + 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* for (int i = 0; i < mutationIndices.length; 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. - * @param indy1 The original mother - * @param partners The original partners + /** + * 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 partners The original partners */ + @Override public void crossoverOnStrategyParameters(AbstractEAIndividual indy1, Population partners) { // 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 + * * @return A descriptive string. */ + @Override public String getStringRepresentation() { return "GA n-Bit mutation"; } -/********************************************************************************************************************** - * These are for GUI - */ - /** This method allows the CommonJavaObjectEditorPanel to read the - * name to the current object. + /** + * ******************************************************************************************************************** + * These are for GUI + */ + /** + * This method allows the CommonJavaObjectEditorPanel to read the name to + * the current object. + * * @return The name. */ public String getName() { return "GA n-Bit mutation"; } - /** This method returns a global info string + + /** + * This method returns a global info string + * * @return description */ public static String globalInfo() { 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. - * @param mutations The number of mutations. + * + * @param mutations The number of mutations. */ public void setNumberOfMutations(int mutations) { - if (mutations < 0) mutations = 0; - this.m_NumberOfMutations = mutations; + if (mutations < 0) { + mutations = 0; + } + this.numberOfMutations = mutations; } + public int getNumberOfMutations() { - return this.m_NumberOfMutations; + return this.numberOfMutations; } + public String numberOfMutationsTipText() { return "The number of bits to be mutated."; } diff --git a/src/eva2/server/go/operators/terminators/GenerationTerminator.java b/src/eva2/server/go/operators/terminators/GenerationTerminator.java index 88d823b1..d04e1758 100644 --- a/src/eva2/server/go/operators/terminators/GenerationTerminator.java +++ b/src/eva2/server/go/operators/terminators/GenerationTerminator.java @@ -9,80 +9,78 @@ package eva2.server.go.operators.terminators; * $Date: 2007-12-05 11:29:32 +0100 (Wed, 05 Dec 2007) $ * $Author: mkron $ */ -/*==========================================================================* - * IMPORTS - *==========================================================================*/ -import java.io.Serializable; - -import eva2.gui.BeanInspector; import eva2.server.go.InterfaceTerminator; import eva2.server.go.PopulationInterface; import eva2.server.go.populations.InterfaceSolutionSet; import eva2.server.go.problems.InterfaceOptimizationProblem; +import java.io.Serializable; -/*==========================================================================* - * CLASS DECLARATION - *==========================================================================*/ /** * */ -public class GenerationTerminator implements InterfaceTerminator, -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 class GenerationTerminator implements InterfaceTerminator, Serializable { - public GenerationTerminator() { - } + /** + * Number of fitness calls on the problem which is optimized + */ + protected int m_Generations = 100; + private String msg = ""; - public GenerationTerminator(int gens) { - m_Generations = gens; - } - - public boolean isTerminated(InterfaceSolutionSet solSet) { - return isTerminated(solSet.getCurrentPopulation()); - } + @Override + public void init(InterfaceOptimizationProblem prob) { + msg = "Not terminated."; + } - public boolean isTerminated(PopulationInterface Pop) { - if (m_Generations informerList) { - if (TRACE) { - System.out.println("initPlots"); - } if (m_StatsParams instanceof StatisticsParameter) { -// StringSelection ss = ((StatsParameter)m_StatsParams).getGraphSelection(); graphDesc = lastFieldSelection.getSelectedWithIndex(); -// for (int i=0; i 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; - } + /** + * + */ + public static long getRandomSeed() { + return randomSeed; + } - /** - * This method returns a random permutation of n int values - * - * @param length - * The number of int values - * @return The permutation [0-length-1] - */ - public static int[] randomPerm(int length) { - ArrayList intList = new ArrayList(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 0 or 1 evenly distributed. + */ + public static int randomInt() { + return randomInt(0, 1); + } - } - if (intList.size() > 1) - System.err.println("Error in randomPerm!"); - result[length - 1] = intList.get(0); - return result; - } + /** + * Returns an evenly distributes int value between zero and upperLim-1. + * + * @param upperLim upper exclusive limit of the random int + */ + public static int randomInt(int upperLim) { + return randomInt(0, upperLim - 1); + } - /** This method returns a evenly distributed int value. - * The boundarys are included. - * @param lo Lower bound. - * @param hi Upper bound. - * @return int - */ - public static int randomInt(Random rand, int lo,int hi) { - if (hi 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; - } + /** + * This method returns a evenly distributed int value. The boundarys are + * included. + * + * @param lo 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; + } - /** - * Returns a random long between 0 and Long.MAX_VALUE-1 (inclusively). - */ - public static long randomLong() { - return randomLong(0, Long.MAX_VALUE - 1); - } + /** + * This method returns a random permutation of n int values + * + * @param length The number of int values + * @return The permutation [0-length-1] + */ + public static int[] randomPerm(int length) { + ArrayList intList = new ArrayList(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). - */ - public static long randomLong(long lo, long hi) { - return (Math.abs(random.nextLong()) % (hi - lo + 1)) + lo; - } + } + if (intList.size() > 1) { + System.err.println("Error in randomPerm!"); + } + result[length - 1] = intList.get(0); + return result; + } - /** - * - */ - public static float randomFloat() { - return random.nextFloat(); - } + /** + * This method returns a evenly distributed int value. The boundarys are + * included. + * + * @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; + } - /** - * - */ - public static float randomFloat(float lo, float hi) { - return (hi - lo) * random.nextFloat() + lo; - } + /** + * Returns a random long between 0 and Long.MAX_VALUE-1 (inclusively). + */ + public static long randomLong() { + return randomLong(0, Long.MAX_VALUE - 1); + } - /** - * A random double value between 0 and 1. - */ - public static double randomDouble() { - return random.nextDouble(); - } + /** + * Returns a random long between the given values (inclusively). + */ + public static long randomLong(long lo, long hi) { + return (Math.abs(random.nextLong()) % (hi - lo + 1)) + lo; + } - /** - * - */ - public static double randomDouble(double lo,double hi) { - return (hi-lo)*random.nextDouble()+lo; - } + /** + * + */ + public static float randomFloat() { + 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. - */ - public static double[] randomDoubleArray(double[] lo,double[] hi) { - double[] xin = new double[lo.length]; - for (int i=0;ilength) { - EVAERROR.errorMsgOnce("Error, invalid cardinality " + cardinality + " requested for bit length "+ length +", cardinality will be reduced."); - cardinality=length; - } - BitSet bs = new BitSet(length); - int[] perm = randomPerm(length); - for (int i=0; i 0, - inside a D-Gaussian if - * nonUnif < 0. For case 2, the nonUnif parameter is used as standard - * 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 - * - * @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, - double nonUnif) { - double[] x = new double[center.length]; - int j; - double xLen, r; - int D = center.length; + /** + * Create a random bitset with given cardinality and lengths, + */ + public static BitSet randomBitSet(int cardinality, int length) { + if (cardinality > length) { + EVAERROR.errorMsgOnce("Error, invalid cardinality " + cardinality + " requested for bit length " + length + ", cardinality will be reduced."); + cardinality = length; + } + BitSet bs = new BitSet(length); + int[] perm = randomPerm(length); + for (int i = 0; i < cardinality; i++) { + bs.set(perm[i]); + } + return bs; + } - // ----------------------------------- Step 1. Direction - xLen = 0; - for (j = 0; j < D; j++) { - r = gaussianDouble(1); - x[j] = r; - xLen += x[j] * x[j]; - } + /** + * 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; + } - 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) - r = gaussianDouble(r / 2); // D-Gaussian - else if (nonUnif > 0) - r = Math.pow(r, nonUnif); // non-uniform hypersphere - else - r = Math.pow(r, 1. / D); // Real hypersphere + /** + * Return a Gaussian double with mean 0 and deviation dev. + * + * @param dev the deviation of the distribution. + * @return a Gaussian double with mean 0 and given deviation. + */ + 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 - * 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); - } - } + /** + * + */ + public static double exponentialDouble(double mean) { + // counter++; + return -mean * Math.log(randomDouble()); + } - /** - * 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; - } + /** + * Returns a vector denoting a random point around the center - inside a + * hypersphere of uniform distribution if nonUnif=0, - inside a hypersphere + * of non-uniform distribution if nonUnif > 0, - inside a D-Gaussian if + * nonUnif < 0. For case 2, the nonUnif parameter is used as standard + * 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 + * - /** - * 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; - } + * + * @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, + double nonUnif) { + double[] x = new double[center.length]; + int j; + double xLen, r; + int D = center.length; - // 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 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); - // } - // } + // ----------------------------------- Step 1. Direction + xLen = 0; + for (j = 0; j < D; j++) { + r = gaussianDouble(1); + x[j] = r; + xLen += x[j] * x[j]; + } - // 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)); - // } - // } + xLen = Math.sqrt(xLen); - /** - * 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; - // } + // ----------------------------------- Step 2. Random radius + + r = randomDouble(); + if (nonUnif < 0) { + r = gaussianDouble(r / 2); // D-Gaussian + } else if (nonUnif > 0) { + r = Math.pow(r, nonUnif); // non-uniform hypersphere + } else { + r = Math.pow(r, 1. / D); // Real hypersphere + } + for (j = 0; j < D; j++) { + x[j] = center[j] + radius * r * x[j] / xLen; + } + return x; + } + + /** + * 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; + } } \ No newline at end of file