commons-commits mailing list archives

Site index · List index
Message view « Date » · « Thread »
Top « Date » · « Thread »
From t.@apache.org
Subject svn commit: r1235038 - in /commons/proper/math/trunk/src/main/java/org/apache/commons/math: exception/util/ genetics/
Date Mon, 23 Jan 2012 22:26:38 GMT
Author: tn
Date: Mon Jan 23 22:26:37 2012
New Revision: 1235038

URL: http://svn.apache.org/viewvc?rev=1235038&view=rev
Log:
Added localized messages for exceptions thrown in the genetics package,
improved javadoc, added final for parameters.
JIRA: MATH-575

Modified:
    commons/proper/math/trunk/src/main/java/org/apache/commons/math/exception/util/LocalizedFormats.java
    commons/proper/math/trunk/src/main/java/org/apache/commons/math/genetics/AbstractListChromosome.java
    commons/proper/math/trunk/src/main/java/org/apache/commons/math/genetics/BinaryChromosome.java
    commons/proper/math/trunk/src/main/java/org/apache/commons/math/genetics/BinaryMutation.java
    commons/proper/math/trunk/src/main/java/org/apache/commons/math/genetics/Chromosome.java
    commons/proper/math/trunk/src/main/java/org/apache/commons/math/genetics/ElitisticListPopulation.java
    commons/proper/math/trunk/src/main/java/org/apache/commons/math/genetics/FixedGenerationCount.java
    commons/proper/math/trunk/src/main/java/org/apache/commons/math/genetics/GeneticAlgorithm.java
    commons/proper/math/trunk/src/main/java/org/apache/commons/math/genetics/InvalidRepresentationException.java
    commons/proper/math/trunk/src/main/java/org/apache/commons/math/genetics/ListPopulation.java
    commons/proper/math/trunk/src/main/java/org/apache/commons/math/genetics/OnePointCrossover.java
    commons/proper/math/trunk/src/main/java/org/apache/commons/math/genetics/PermutationChromosome.java
    commons/proper/math/trunk/src/main/java/org/apache/commons/math/genetics/RandomKey.java
    commons/proper/math/trunk/src/main/java/org/apache/commons/math/genetics/RandomKeyMutation.java
    commons/proper/math/trunk/src/main/java/org/apache/commons/math/genetics/TournamentSelection.java

Modified: commons/proper/math/trunk/src/main/java/org/apache/commons/math/exception/util/LocalizedFormats.java
URL: http://svn.apache.org/viewvc/commons/proper/math/trunk/src/main/java/org/apache/commons/math/exception/util/LocalizedFormats.java?rev=1235038&r1=1235037&r2=1235038&view=diff
==============================================================================
--- commons/proper/math/trunk/src/main/java/org/apache/commons/math/exception/util/LocalizedFormats.java
(original)
+++ commons/proper/math/trunk/src/main/java/org/apache/commons/math/exception/util/LocalizedFormats.java
Mon Jan 23 22:26:37 2012
@@ -80,6 +80,7 @@ public enum LocalizedFormats implements 
     CROSSING_BOUNDARY_LOOPS("some outline boundary loops cross each other"),
     CUMULATIVE_PROBABILITY_RETURNED_NAN("Cumulative probability function returned NaN for
argument {0} p = {1}"),
     DIFFERENT_ROWS_LENGTHS("some rows have length {0} while others have length {1}"),
+    DIFFERENT_ORIG_AND_PERMUTED_DATA("original and permuted data must contain the same elements"),
     DIGEST_NOT_INITIALIZED("digest not initialized"),
     DIMENSIONS_MISMATCH_2x2("got {0}x{1} but expected {2}x{3}"), /* keep */
     DIMENSIONS_MISMATCH_SIMPLE("{0} != {1}"), /* keep */
@@ -133,7 +134,10 @@ public enum LocalizedFormats implements 
     INTEGRATION_METHOD_NEEDS_AT_LEAST_TWO_PREVIOUS_POINTS("{0} method needs at least two
previous points"),
     INTERNAL_ERROR("internal error, please fill a bug report at {0}"),
     INVALID_BINARY_DIGIT("invalid binary digit: {0}"),
+    INVALID_BINARY_CHROMOSOME("binary mutation works on BinaryChromosome only"),
     INVALID_BRACKETING_PARAMETERS("invalid bracketing parameters:  lower bound={0},  initial={1},
upper bound={2}"),
+    INVALID_CROSSOVER_CHROMOSOME_LENGTH("both chromosomes must have same lengths: ({0}) ({1})"),
+    INVALID_FIXED_LENGTH_CHROMOSOME("one-point crossover works only on instances of AbstractListChromosome"),
     INVALID_INTERVAL_INITIAL_VALUE_PARAMETERS("invalid interval, initial value parameters:
 lower={0}, initial={1}, upper={2}"),
     INVALID_ITERATIONS_LIMITS("invalid iteration limits: min={0}, max={1}"),
     INVALID_MAX_ITERATIONS("bad value for maximum iterations number: {0}"),
@@ -270,6 +274,9 @@ public enum LocalizedFormats implements 
     OUT_OF_BOUND_SIGNIFICANCE_LEVEL("out of bounds significance level {0}, must be between
{1} and {2}"),
     SIGNIFICANCE_LEVEL("significance level ({0})"), /* keep */
     OUT_OF_ORDER_ABSCISSA_ARRAY("the abscissae array must be sorted in a strictly increasing
order, but the {0}-th element is {1} whereas {2}-th is {3}"),
+    OUT_OF_RANGE_CROSSOVER_RATE("crossover rate ({0}) out of [{1}, {2}] range"),
+    OUT_OF_RANGE_ELITISM_RATE("elitism rate ({0}) out of [{1}, {2}] range"),
+    OUT_OF_RANGE_MUTATION_RATE("mutation rate ({0}) out of [{1}, {2}] range"),
     OUT_OF_RANGE_ROOT_OF_UNITY_INDEX("out of range root of unity index {0} (must be in [{1};{2}])"),
     OUT_OF_RANGE("out of range"), /* keep */
     OUT_OF_RANGE_SIMPLE("{0} out of [{1}, {2}] range"), /* keep */
@@ -303,10 +310,12 @@ public enum LocalizedFormats implements 
     SINGULAR_OPERATOR("operator is singular"),
     SUBARRAY_ENDS_AFTER_ARRAY_END("subarray ends after array end"),
     TOO_LARGE_CUTOFF_SINGULAR_VALUE("cutoff singular value is {0}, should be at most {1}"),
+    TOO_LARGE_TOURNAMENT_ARITY("tournament arity ({0}) cannot be bigger than population size
({1})"),
     TOO_MANY_ELEMENTS_TO_DISCARD_FROM_ARRAY("cannot discard {0} elements from a {1} elements
array"),
     TOO_MUCH_CANCELLATION("too much cancellation in a denominator"),
     TOO_MANY_REGRESSORS("too many regressors ({0}) specified, only {1} in the model"),
     TOO_SMALL_COST_RELATIVE_TOLERANCE("cost relative tolerance is too small ({0}), no further
reduction in the sum of squares is possible"),
+    TOO_SMALL_GENERATION_COUNT("number of generations ({0}) must be >= {1}"),
     TOO_SMALL_INTEGRATION_INTERVAL("too small integration interval: length = {0}"),
     TOO_SMALL_ORTHOGONALITY_TOLERANCE("orthogonality tolerance is too small ({0}), solution
is orthogonal to the jacobian"),
     TOO_SMALL_PARAMETERS_RELATIVE_TOLERANCE("parameters relative tolerance is too small ({0}),
no further improvement in the approximate solution is possible"),
@@ -340,6 +349,9 @@ public enum LocalizedFormats implements 
     WEIGHT_AT_LEAST_ONE_NON_ZERO("weigth array must contain at least one non-zero value"),
     WRONG_BLOCK_LENGTH("wrong array shape (block length = {0}, expected {1})"),
     WRONG_NUMBER_OF_POINTS("{0} points are required, got only {1}"),
+    WRONG_SEQUENCE_LENGTH_RANDOMKEY("length of sequence for decoding ({0}) has to be equal
to the RandomKey length ({1})"),
+    WRONG_REPR_AND_SREPR_SIZE("size of representation and sorted representation must be equals:
{0} != {1}"),
+    WRONG_ORIG_AND_PERMUTED_SIZE("original and permuted data must have same length: {0} !=
{1}"),
     NUMBER_OF_POINTS("number of points ({0})"), /* keep */
     ZERO_DENOMINATOR("denominator must be different from 0"),
     ZERO_DENOMINATOR_IN_FRACTION("zero denominator in fraction {0}/{1}"),

Modified: commons/proper/math/trunk/src/main/java/org/apache/commons/math/genetics/AbstractListChromosome.java
URL: http://svn.apache.org/viewvc/commons/proper/math/trunk/src/main/java/org/apache/commons/math/genetics/AbstractListChromosome.java?rev=1235038&r1=1235037&r2=1235038&view=diff
==============================================================================
--- commons/proper/math/trunk/src/main/java/org/apache/commons/math/genetics/AbstractListChromosome.java
(original)
+++ commons/proper/math/trunk/src/main/java/org/apache/commons/math/genetics/AbstractListChromosome.java
Mon Jan 23 22:26:37 2012
@@ -36,6 +36,8 @@ public abstract class AbstractListChromo
     /**
      * Constructor.
      * @param representation inner representation of the chromosome
+     * @throws InvalidRepresentationException iff the <code>representation</code>
can not represent
+     *         a valid chromosome
      */
     public AbstractListChromosome(final List<T> representation) {
         checkValidity(representation);

Modified: commons/proper/math/trunk/src/main/java/org/apache/commons/math/genetics/BinaryChromosome.java
URL: http://svn.apache.org/viewvc/commons/proper/math/trunk/src/main/java/org/apache/commons/math/genetics/BinaryChromosome.java?rev=1235038&r1=1235037&r2=1235038&view=diff
==============================================================================
--- commons/proper/math/trunk/src/main/java/org/apache/commons/math/genetics/BinaryChromosome.java
(original)
+++ commons/proper/math/trunk/src/main/java/org/apache/commons/math/genetics/BinaryChromosome.java
Mon Jan 23 22:26:37 2012
@@ -32,6 +32,8 @@ public abstract class BinaryChromosome e
     /**
      * Constructor.
      * @param representation list of {0,1} values representing the chromosome
+     * @throws InvalidRepresentationException iff the <code>representation</code>
can not represent
+     *         a valid chromosome
      */
     public BinaryChromosome(List<Integer> representation) {
         super(representation);
@@ -40,6 +42,8 @@ public abstract class BinaryChromosome e
     /**
      * Constructor.
      * @param representation array of {0,1} values representing the chromosome
+     * @throws InvalidRepresentationException iff the <code>representation</code>
can not represent
+     *         a valid chromosome
      */
     public BinaryChromosome(Integer[] representation) {
         super(representation);

Modified: commons/proper/math/trunk/src/main/java/org/apache/commons/math/genetics/BinaryMutation.java
URL: http://svn.apache.org/viewvc/commons/proper/math/trunk/src/main/java/org/apache/commons/math/genetics/BinaryMutation.java?rev=1235038&r1=1235037&r2=1235038&view=diff
==============================================================================
--- commons/proper/math/trunk/src/main/java/org/apache/commons/math/genetics/BinaryMutation.java
(original)
+++ commons/proper/math/trunk/src/main/java/org/apache/commons/math/genetics/BinaryMutation.java
Mon Jan 23 22:26:37 2012
@@ -19,6 +19,9 @@ package org.apache.commons.math.genetics
 import java.util.ArrayList;
 import java.util.List;
 
+import org.apache.commons.math.exception.MathIllegalArgumentException;
+import org.apache.commons.math.exception.util.LocalizedFormats;
+
 /**
  * Mutation for {@link BinaryChromosome}s. Randomly changes one gene.
  *
@@ -31,10 +34,12 @@ public class BinaryMutation implements M
      * Mutate the given chromosome. Randomly changes one gene.
      * @param original the original chromosome.
      * @return the mutated chromomsome.
+     * @throws MathIllegalArgumentException if the <code>chromosome</code> is
not an instance
+     *         of {@link BinaryChromosome}.
      */
     public Chromosome mutate(Chromosome original) {
         if (!(original instanceof BinaryChromosome)) {
-            throw new IllegalArgumentException("Binary mutation works on BinaryChromosome
only.");
+            throw new MathIllegalArgumentException(LocalizedFormats.INVALID_BINARY_CHROMOSOME);
         }
 
         BinaryChromosome origChrom = (BinaryChromosome) original;

Modified: commons/proper/math/trunk/src/main/java/org/apache/commons/math/genetics/Chromosome.java
URL: http://svn.apache.org/viewvc/commons/proper/math/trunk/src/main/java/org/apache/commons/math/genetics/Chromosome.java?rev=1235038&r1=1235037&r2=1235038&view=diff
==============================================================================
--- commons/proper/math/trunk/src/main/java/org/apache/commons/math/genetics/Chromosome.java
(original)
+++ commons/proper/math/trunk/src/main/java/org/apache/commons/math/genetics/Chromosome.java
Mon Jan 23 22:26:37 2012
@@ -27,9 +27,7 @@ package org.apache.commons.math.genetics
  */
 public abstract class Chromosome implements Comparable<Chromosome>,Fitness {
 
-    /**
-     * Cached value of the fitness of this chromosome.
-     */
+    /** Cached value of the fitness of this chromosome. */
     private double fitness = Double.MIN_VALUE;
 
     /**
@@ -61,7 +59,7 @@ public abstract class Chromosome impleme
      *     <li>0 if the two chromosomes have the same fitness</li>
      * </ul>
      */
-    public int compareTo(Chromosome another) {
+    public int compareTo(final Chromosome another) {
         return ((Double)this.getFitness()).compareTo(another.getFitness());
     }
 
@@ -72,7 +70,7 @@ public abstract class Chromosome impleme
      * @param another chromosome to compare
      * @return true if <code>another</code> is equivalent to this chromosome
      */
-    protected boolean isSame(Chromosome another) {
+    protected boolean isSame(final Chromosome another) {
         return false;
     }
 
@@ -81,12 +79,11 @@ public abstract class Chromosome impleme
      * representation. If such chromosome is found, it is returned, if no such
      * chromosome exists, returns <code>null</code>.
      *
-     * @param population
-     *            Population to search
+     * @param population Population to search
      * @return Chromosome with the same representation, or <code>null</code>
if
      *         no such chromosome exists.
      */
-    protected Chromosome findSameChromosome(Population population) {
+    protected Chromosome findSameChromosome(final Population population) {
         for (Chromosome anotherChr : population) {
             if (this.isSame(anotherChr)) {
                 return anotherChr;
@@ -99,10 +96,9 @@ public abstract class Chromosome impleme
      * Searches the population for a chromosome representing the same solution,
      * and if it finds one, updates the fitness to its value.
      *
-     * @param population
-     *            Population to search
+     * @param population Population to search
      */
-    public void searchForFitnessUpdate(Population population) {
+    public void searchForFitnessUpdate(final Population population) {
         Chromosome sameChromosome = findSameChromosome(population);
         if (sameChromosome != null) {
             fitness = sameChromosome.getFitness();

Modified: commons/proper/math/trunk/src/main/java/org/apache/commons/math/genetics/ElitisticListPopulation.java
URL: http://svn.apache.org/viewvc/commons/proper/math/trunk/src/main/java/org/apache/commons/math/genetics/ElitisticListPopulation.java?rev=1235038&r1=1235037&r2=1235038&view=diff
==============================================================================
--- commons/proper/math/trunk/src/main/java/org/apache/commons/math/genetics/ElitisticListPopulation.java
(original)
+++ commons/proper/math/trunk/src/main/java/org/apache/commons/math/genetics/ElitisticListPopulation.java
Mon Jan 23 22:26:37 2012
@@ -19,6 +19,8 @@ package org.apache.commons.math.genetics
 import java.util.Collections;
 import java.util.List;
 
+import org.apache.commons.math.exception.OutOfRangeException;
+import org.apache.commons.math.exception.util.LocalizedFormats;
 import org.apache.commons.math.util.FastMath;
 
 /**
@@ -36,15 +38,14 @@ public class ElitisticListPopulation ext
     /**
      * Creates a new ElitisticListPopulation instance.
      *
-     * @param chromosomes
-     *            list of chromosomes in the population
-     * @param populationLimit
-     *            maximal size of the population
-     * @param elitismRate
-     *            how many best chromosomes will be directly transferred to the
-     *            next generation [in %]
+     * @param chromosomes list of chromosomes in the population
+     * @param populationLimit maximal size of the population
+     * @param elitismRate how many best chromosomes will be directly transferred to the
+     *                    next generation [in %]
      */
-    public ElitisticListPopulation(List<Chromosome> chromosomes, int populationLimit,
double elitismRate) {
+    public ElitisticListPopulation(final List<Chromosome> chromosomes,
+                                   final int populationLimit,
+                                   final double elitismRate) {
         super(chromosomes, populationLimit);
         this.elitismRate = elitismRate;
     }
@@ -54,19 +55,17 @@ public class ElitisticListPopulation ext
      * chromosome list.
      *
      * @param populationLimit maximal size of the population
-     * @param elitismRate
-     *            how many best chromosomes will be directly transferred to the
-     *            next generation [in %]
+     * @param elitismRate how many best chromosomes will be directly transferred to the
+     *                    next generation [in %]
      */
-    public ElitisticListPopulation(int populationLimit, double elitismRate) {
+    public ElitisticListPopulation(final int populationLimit, final double elitismRate) {
         super(populationLimit);
         this.elitismRate = elitismRate;
     }
 
     /**
-     * Start the population for the next generation. The
-     * <code>{@link #elitismRate}<code> percents of the best
-     * chromosomes are directly copied to the next generation.
+     * Start the population for the next generation. The <code>{@link #elitismRate}<code>
+     * percents of the best chromosomes are directly copied to the next generation.
      *
      * @return the beginnings of the next generation.
      */
@@ -89,13 +88,13 @@ public class ElitisticListPopulation ext
      * Sets the elitism rate, i.e. how many best chromosomes will be directly
      * transferred to the next generation [in %].
      *
-     * @param elitismRate
-     *            how many best chromosomes will be directly transferred to the
-     *            next generation [in %]
+     * @param elitismRate how many best chromosomes will be directly transferred to the
+     *                    next generation [in %]
+     * @throws OutOfRangeException if the elitism rate is outside the [0, 1] range
      */
-    public void setElitismRate(double elitismRate) {
+    public void setElitismRate(final double elitismRate) {
         if (elitismRate < 0 || elitismRate > 1) {
-            throw new IllegalArgumentException("Elitism rate has to be in [0,1]");
+            throw new OutOfRangeException(LocalizedFormats.OUT_OF_RANGE_ELITISM_RATE, elitismRate,
0, 1);
         }
         this.elitismRate = elitismRate;
     }

Modified: commons/proper/math/trunk/src/main/java/org/apache/commons/math/genetics/FixedGenerationCount.java
URL: http://svn.apache.org/viewvc/commons/proper/math/trunk/src/main/java/org/apache/commons/math/genetics/FixedGenerationCount.java?rev=1235038&r1=1235037&r2=1235038&view=diff
==============================================================================
--- commons/proper/math/trunk/src/main/java/org/apache/commons/math/genetics/FixedGenerationCount.java
(original)
+++ commons/proper/math/trunk/src/main/java/org/apache/commons/math/genetics/FixedGenerationCount.java
Mon Jan 23 22:26:37 2012
@@ -16,6 +16,9 @@
  */
 package org.apache.commons.math.genetics;
 
+import org.apache.commons.math.exception.NumberIsTooSmallException;
+import org.apache.commons.math.exception.util.LocalizedFormats;
+
 /**
  * Stops after a fixed number of generations.  Each time
  * {@link #isSatisfied(Population)} is invoked, a generation counter is
@@ -37,10 +40,12 @@ public class FixedGenerationCount implem
      * Create a new FixedGenerationCount instance.
      *
      * @param maxGenerations number of generations to evolve
+     * @throws NumberIsTooSmallException if the number of generations is &lt; 1
      */
-    public FixedGenerationCount(int maxGenerations) {
+    public FixedGenerationCount(final int maxGenerations) {
         if (maxGenerations <= 0) {
-            throw new IllegalArgumentException("The number of generations has to be >=
0");
+            throw new NumberIsTooSmallException(LocalizedFormats.TOO_SMALL_GENERATION_COUNT,
+                                                maxGenerations, 1, true);
         }
         this.maxGenerations = maxGenerations;
     }
@@ -53,7 +58,7 @@ public class FixedGenerationCount implem
      * @param population ignored (no impact on result)
      * @return <code>true</code> IFF the maximum number of generations has been
exceeded
      */
-    public boolean isSatisfied(Population population) {
+    public boolean isSatisfied(final Population population) {
         if (this.numGenerations < this.maxGenerations) {
             numGenerations++;
             return false;

Modified: commons/proper/math/trunk/src/main/java/org/apache/commons/math/genetics/GeneticAlgorithm.java
URL: http://svn.apache.org/viewvc/commons/proper/math/trunk/src/main/java/org/apache/commons/math/genetics/GeneticAlgorithm.java?rev=1235038&r1=1235037&r2=1235038&view=diff
==============================================================================
--- commons/proper/math/trunk/src/main/java/org/apache/commons/math/genetics/GeneticAlgorithm.java
(original)
+++ commons/proper/math/trunk/src/main/java/org/apache/commons/math/genetics/GeneticAlgorithm.java
Mon Jan 23 22:26:37 2012
@@ -16,6 +16,8 @@
  */
 package org.apache.commons.math.genetics;
 
+import org.apache.commons.math.exception.OutOfRangeException;
+import org.apache.commons.math.exception.util.LocalizedFormats;
 import org.apache.commons.math.random.RandomGenerator;
 import org.apache.commons.math.random.JDKRandomGenerator;
 
@@ -61,16 +63,21 @@ public class GeneticAlgorithm {
      * @param mutationPolicy The {@link MutationPolicy}
      * @param mutationRate The mutation rate as a percentage (0-1 inclusive)
      * @param selectionPolicy The {@link SelectionPolicy}
+     * @throws OutOfRangeException if the crossover or mutation rate is outside the [0, 1]
range
      */
-    public GeneticAlgorithm(
-            CrossoverPolicy crossoverPolicy, double crossoverRate,
-            MutationPolicy mutationPolicy, double mutationRate,
-            SelectionPolicy selectionPolicy) {
+    public GeneticAlgorithm(final CrossoverPolicy crossoverPolicy,
+                            final double crossoverRate,
+                            final MutationPolicy mutationPolicy,
+                            final double mutationRate,
+                            final SelectionPolicy selectionPolicy) {
+
         if (crossoverRate < 0 || crossoverRate > 1) {
-            throw new IllegalArgumentException("crossoverRate must be between 0 and 1");
+            throw new OutOfRangeException(LocalizedFormats.OUT_OF_RANGE_CROSSOVER_RATE,
+                                          crossoverRate, 0, 1);
         }
         if (mutationRate < 0 || mutationRate > 1) {
-            throw new IllegalArgumentException("mutationRate must be between 0 and 1");
+            throw new OutOfRangeException(LocalizedFormats.OUT_OF_RANGE_MUTATION_RATE,
+                                          mutationRate, 0, 1);
         }
         this.crossoverPolicy = crossoverPolicy;
         this.crossoverRate = crossoverRate;
@@ -84,7 +91,7 @@ public class GeneticAlgorithm {
      *
      * @param random random generator
      */
-    public static synchronized void setRandomGenerator(RandomGenerator random) {
+    public static synchronized void setRandomGenerator(final RandomGenerator random) {
         randomGenerator = random;
     }
 
@@ -107,7 +114,7 @@ public class GeneticAlgorithm {
      * @param condition the stopping condition used to stop evolution.
      * @return the population that satisfies the stopping condition.
      */
-    public Population evolve(Population initial, StoppingCondition condition) {
+    public Population evolve(final Population initial, final StoppingCondition condition)
{
         Population current = initial;
         generationsEvolved = 0;
         while (!condition.isSatisfied(current)) {
@@ -139,7 +146,7 @@ public class GeneticAlgorithm {
      * @param current the current population.
      * @return the population for the next generation.
      */
-    public Population nextGeneration(Population current) {
+    public Population nextGeneration(final Population current) {
         Population nextGeneration = current.nextGeneration();
 
         RandomGenerator randGen = getRandomGenerator();

Modified: commons/proper/math/trunk/src/main/java/org/apache/commons/math/genetics/InvalidRepresentationException.java
URL: http://svn.apache.org/viewvc/commons/proper/math/trunk/src/main/java/org/apache/commons/math/genetics/InvalidRepresentationException.java?rev=1235038&r1=1235037&r2=1235038&view=diff
==============================================================================
--- commons/proper/math/trunk/src/main/java/org/apache/commons/math/genetics/InvalidRepresentationException.java
(original)
+++ commons/proper/math/trunk/src/main/java/org/apache/commons/math/genetics/InvalidRepresentationException.java
Mon Jan 23 22:26:37 2012
@@ -36,8 +36,7 @@ public class InvalidRepresentationExcept
      * @param pattern Message pattern.
      * @param args Arguments.
      */
-    public InvalidRepresentationException(Localizable pattern,
-            Object ... args) {
+    public InvalidRepresentationException(Localizable pattern, Object ... args) {
        super(pattern, args);
     }
 

Modified: commons/proper/math/trunk/src/main/java/org/apache/commons/math/genetics/ListPopulation.java
URL: http://svn.apache.org/viewvc/commons/proper/math/trunk/src/main/java/org/apache/commons/math/genetics/ListPopulation.java?rev=1235038&r1=1235037&r2=1235038&view=diff
==============================================================================
--- commons/proper/math/trunk/src/main/java/org/apache/commons/math/genetics/ListPopulation.java
(original)
+++ commons/proper/math/trunk/src/main/java/org/apache/commons/math/genetics/ListPopulation.java
Mon Jan 23 22:26:37 2012
@@ -44,13 +44,15 @@ public abstract class ListPopulation imp
      *
      * @param chromosomes list of chromosomes in the population
      * @param populationLimit maximal size of the population
+     * @throws NumberIsTooLargeException if the list of chromosomes exceeds the population
limit
+     * @throws NotPositiveException if the population limit is not a positive number (&lt;
1)
      */
-    public ListPopulation (List<Chromosome> chromosomes, int populationLimit) {
+    public ListPopulation(final List<Chromosome> chromosomes, final int populationLimit)
{
         if (chromosomes.size() > populationLimit) {
             throw new NumberIsTooLargeException(LocalizedFormats.LIST_OF_CHROMOSOMES_BIGGER_THAN_POPULATION_SIZE,
                                                 chromosomes.size(), populationLimit, false);
         }
-        if (populationLimit < 0) {
+        if (populationLimit <= 0) {
             throw new NotPositiveException(LocalizedFormats.POPULATION_LIMIT_NOT_POSITIVE,
populationLimit);
         }
 
@@ -59,13 +61,13 @@ public abstract class ListPopulation imp
     }
 
     /**
-     * Creates a new ListPopulation instance and initializes its inner
-     * chromosome list.
+     * Creates a new ListPopulation instance and initializes its inner chromosome list.
      *
      * @param populationLimit maximal size of the population
+     * @throws NotPositiveException if the population limit is not a positive number (&lt;
1)
      */
-    public ListPopulation (int populationLimit) {
-        if (populationLimit < 0) {
+    public ListPopulation(final int populationLimit) {
+        if (populationLimit <= 0) {
             throw new NotPositiveException(LocalizedFormats.POPULATION_LIMIT_NOT_POSITIVE,
populationLimit);
         }
         this.populationLimit = populationLimit;
@@ -76,7 +78,7 @@ public abstract class ListPopulation imp
      * Sets the list of chromosomes.
      * @param chromosomes the list of chromosomes
      */
-    public void setChromosomes(List<Chromosome> chromosomes) {
+    public void setChromosomes(final List<Chromosome> chromosomes) {
         this.chromosomes = chromosomes;
     }
 
@@ -92,7 +94,7 @@ public abstract class ListPopulation imp
      * Add the given chromosome to the population.
      * @param chromosome the chromosome to add.
      */
-    public void addChromosome(Chromosome chromosome) {
+    public void addChromosome(final Chromosome chromosome) {
         this.chromosomes.add(chromosome);
     }
 
@@ -124,7 +126,7 @@ public abstract class ListPopulation imp
      * Sets the maximal population size.
      * @param populationLimit maximal population size.
      */
-    public void setPopulationLimit(int populationLimit) {
+    public void setPopulationLimit(final int populationLimit) {
         this.populationLimit = populationLimit;
     }
 

Modified: commons/proper/math/trunk/src/main/java/org/apache/commons/math/genetics/OnePointCrossover.java
URL: http://svn.apache.org/viewvc/commons/proper/math/trunk/src/main/java/org/apache/commons/math/genetics/OnePointCrossover.java?rev=1235038&r1=1235037&r2=1235038&view=diff
==============================================================================
--- commons/proper/math/trunk/src/main/java/org/apache/commons/math/genetics/OnePointCrossover.java
(original)
+++ commons/proper/math/trunk/src/main/java/org/apache/commons/math/genetics/OnePointCrossover.java
Mon Jan 23 22:26:37 2012
@@ -19,6 +19,9 @@ package org.apache.commons.math.genetics
 import java.util.ArrayList;
 import java.util.List;
 
+import org.apache.commons.math.exception.MathIllegalArgumentException;
+import org.apache.commons.math.exception.util.LocalizedFormats;
+
 
 /**
  * One point crossover policy. A random crossover point is selected and the
@@ -65,11 +68,14 @@ public class OnePointCrossover<T> implem
      * @param first first parent (p1)
      * @param second second parent (p2)
      * @return pair of two children (c1,c2)
+     * @throws MathIllegalArgumentException iff one of the chromosomes is
+     *         not an instance of {@link AbstractListChromosome} or the length
+     *         of the two chromosomes is not equal
      */
     @SuppressWarnings("unchecked") // OK because of instanceof checks
-    public ChromosomePair crossover(Chromosome first, Chromosome second) {
+    public ChromosomePair crossover(final Chromosome first, final Chromosome second) {
         if (! (first instanceof AbstractListChromosome<?> && second instanceof
AbstractListChromosome<?>)) {
-            throw new IllegalArgumentException("One point crossover works on FixedLengthChromosomes
only.");
+            throw new MathIllegalArgumentException(LocalizedFormats.INVALID_FIXED_LENGTH_CHROMOSOME);
         }
         return crossover((AbstractListChromosome<T>) first, (AbstractListChromosome<T>)
second);
     }
@@ -81,11 +87,14 @@ public class OnePointCrossover<T> implem
      * @param first the first chromosome.
      * @param second the second chromosome.
      * @return the pair of new chromosomes that resulted from the crossover.
+     * @throws MathIllegalArgumentException if the length of the two chromosomes is different
      */
-    private ChromosomePair crossover(AbstractListChromosome<T> first, AbstractListChromosome<T>
second) {
+    private ChromosomePair crossover(final AbstractListChromosome<T> first,
+                                     final AbstractListChromosome<T> second) {
         int length = first.getLength();
         if (length != second.getLength()) {
-            throw new IllegalArgumentException("Both chromosomes must have same lengths.");
+            throw new MathIllegalArgumentException(LocalizedFormats.INVALID_CROSSOVER_CHROMOSOME_LENGTH,
+                                                   length, second.getLength());
         }
 
         // array representations of the parents
@@ -109,10 +118,8 @@ public class OnePointCrossover<T> implem
             child2Rep.add(parent1Rep.get(i));
         }
 
-        return new ChromosomePair(
-                first.newFixedLengthChromosome(child1Rep),
-                second.newFixedLengthChromosome(child2Rep)
-                );
+        return new ChromosomePair(first.newFixedLengthChromosome(child1Rep),
+                                  second.newFixedLengthChromosome(child2Rep));
     }
 
 }

Modified: commons/proper/math/trunk/src/main/java/org/apache/commons/math/genetics/PermutationChromosome.java
URL: http://svn.apache.org/viewvc/commons/proper/math/trunk/src/main/java/org/apache/commons/math/genetics/PermutationChromosome.java?rev=1235038&r1=1235037&r2=1235038&view=diff
==============================================================================
--- commons/proper/math/trunk/src/main/java/org/apache/commons/math/genetics/PermutationChromosome.java
(original)
+++ commons/proper/math/trunk/src/main/java/org/apache/commons/math/genetics/PermutationChromosome.java
Mon Jan 23 22:26:37 2012
@@ -34,10 +34,8 @@ public interface PermutationChromosome<T
      * represents a permutation (3,0,1,2), and the unpermuted sequence is
      * (a,b,c,d), this yields (d,a,b,c).
      *
-     * @param sequence
-     *            the unpermuted (original) sequence of objects
-     * @return permutation of <code>sequence</code> represented by this
-     *         permutation
+     * @param sequence the unpermuted (original) sequence of objects
+     * @return permutation of <code>sequence</code> represented by this permutation
      */
     List<T> decode(List<T> sequence);
 

Modified: commons/proper/math/trunk/src/main/java/org/apache/commons/math/genetics/RandomKey.java
URL: http://svn.apache.org/viewvc/commons/proper/math/trunk/src/main/java/org/apache/commons/math/genetics/RandomKey.java?rev=1235038&r1=1235037&r2=1235038&view=diff
==============================================================================
--- commons/proper/math/trunk/src/main/java/org/apache/commons/math/genetics/RandomKey.java
(original)
+++ commons/proper/math/trunk/src/main/java/org/apache/commons/math/genetics/RandomKey.java
Mon Jan 23 22:26:37 2012
@@ -21,6 +21,8 @@ import java.util.Arrays;
 import java.util.Collections;
 import java.util.Comparator;
 import java.util.List;
+
+import org.apache.commons.math.exception.MathIllegalArgumentException;
 import org.apache.commons.math.exception.util.LocalizedFormats;
 
 /**
@@ -64,9 +66,7 @@ import org.apache.commons.math.exception
  */
 public abstract class RandomKey<T> extends AbstractListChromosome<Double> implements
PermutationChromosome<T> {
 
-    /**
-     * Cache of sorted representation (unmodifiable).
-     */
+    /** Cache of sorted representation (unmodifiable). */
     private final List<Double> sortedRepresentation;
 
     /**
@@ -78,8 +78,10 @@ public abstract class RandomKey<T> exten
      * Constructor.
      *
      * @param representation list of [0,1] values representing the permutation
+     * @throws InvalidRepresentationException iff the <code>representation</code>
can not represent
+     *         a valid chromosome
      */
-    public RandomKey(List<Double> representation) {
+    public RandomKey(final List<Double> representation) {
         super(representation);
         // store the sorted representation
         List<Double> sortedRepr = new ArrayList<Double> (getRepresentation());
@@ -96,14 +98,14 @@ public abstract class RandomKey<T> exten
      *
      * @param representation array of [0,1] values representing the permutation
      */
-    public RandomKey(Double[] representation) {
+    public RandomKey(final Double[] representation) {
         this(Arrays.asList(representation));
     }
 
     /**
      * {@inheritDoc}
      */
-    public List<T> decode(List<T> sequence) {
+    public List<T> decode(final List<T> sequence) {
         return decodeGeneric(sequence, getRepresentation(), sortedRepresentation);
     }
 
@@ -117,14 +119,17 @@ public abstract class RandomKey<T> exten
      * @param sortedRepr sorted <code>representation</code>
      * @return list with the sequence values permuted according to the representation
      */
-    private static <S> List<S> decodeGeneric(List<S> sequence, List<Double>
representation, List<Double> sortedRepr) {
+    private static <S> List<S> decodeGeneric(final List<S> sequence, List<Double>
representation,
+                                             final List<Double> sortedRepr) {
         int l = sequence.size();
 
         if (representation.size() != l) {
-            throw new IllegalArgumentException(String.format("Length of sequence for decoding
(%s) has to be equal to the length of the RandomKey (%s)", l, representation.size()));
+            throw new MathIllegalArgumentException(LocalizedFormats.WRONG_SEQUENCE_LENGTH_RANDOMKEY,
+                                                   l, representation.size());
         }
         if (representation.size() != sortedRepr.size()) {
-            throw new IllegalArgumentException(String.format("Representation and sortedRepr
must have same sizes, %d != %d", representation.size(), sortedRepr.size()));
+            throw new MathIllegalArgumentException(LocalizedFormats.WRONG_REPR_AND_SREPR_SIZE,
+                                                   representation.size(), sortedRepr.size());
         }
 
         List<Double> reprCopy = new ArrayList<Double> (representation);// do
not modify the orig. representation
@@ -147,7 +152,7 @@ public abstract class RandomKey<T> exten
      * @return true iff chromosomes encode the same permutation
      */
     @Override
-    protected boolean isSame(Chromosome another) {
+    protected boolean isSame(final Chromosome another) {
         // type check
         if (! (another instanceof RandomKey<?>)) {
             return false;
@@ -176,11 +181,12 @@ public abstract class RandomKey<T> exten
      * {@inheritDoc}
      */
     @Override
-    protected void checkValidity(java.util.List<Double> chromosomeRepresentation) throws
InvalidRepresentationException {
+    protected void checkValidity(final List<Double> chromosomeRepresentation)
+        throws InvalidRepresentationException {
+
         for (double val : chromosomeRepresentation) {
             if (val < 0 || val > 1) {
-                throw new InvalidRepresentationException(
-                        LocalizedFormats.OUT_OF_RANGE_SIMPLE, val, 0, 1);
+                throw new InvalidRepresentationException(LocalizedFormats.OUT_OF_RANGE_SIMPLE,
val, 0, 1);
             }
         }
     }
@@ -190,11 +196,10 @@ public abstract class RandomKey<T> exten
      * Generates a representation corresponding to a random permutation of
      * length l which can be passed to the RandomKey constructor.
      *
-     * @param l
-     *            length of the permutation
+     * @param l length of the permutation
      * @return representation of a random permutation
      */
-    public static final List<Double> randomPermutation(int l) {
+    public static final List<Double> randomPermutation(final int l) {
         List<Double> repr = new ArrayList<Double>(l);
         for (int i=0; i<l; i++) {
             repr.add(GeneticAlgorithm.getRandomGenerator().nextDouble());
@@ -206,11 +211,10 @@ public abstract class RandomKey<T> exten
      * Generates a representation corresponding to an identity permutation of
      * length l which can be passed to the RandomKey constructor.
      *
-     * @param l
-     *            length of the permutation
+     * @param l length of the permutation
      * @return representation of an identity permutation
      */
-    public static final List<Double> identityPermutation(int l) {
+    public static final List<Double> identityPermutation(final int l) {
         List<Double> repr = new ArrayList<Double>(l);
         for (int i=0; i<l; i++) {
             repr.add((double)i/l);
@@ -231,7 +235,8 @@ public abstract class RandomKey<T> exten
      * @param comparator how the data will be compared
      * @return list representation of the permutation corresponding to the parameters
      */
-    public static <S> List<Double> comparatorPermutation(List<S> data,
Comparator<S> comparator) {
+    public static <S> List<Double> comparatorPermutation(final List<S>
data,
+                                                         final Comparator<S> comparator)
{
         List<S> sortedData = new ArrayList<S> (data);
         Collections.sort(sortedData, comparator);
 
@@ -248,12 +253,18 @@ public abstract class RandomKey<T> exten
      * @param <S> type of the data
      * @param originalData the original, unpermuted data
      * @param permutedData the data, somehow permuted
-     * @return representation of a permutation corresponding to the permutation <code>originalData
-> permutedData</code>
-     * @throws IllegalArgumentException iff the <code>permutedData</code> and
<code>originalData</code> contains different data
-     */
-    public static <S> List<Double> inducedPermutation(List<S> originalData,
List<S> permutedData) throws IllegalArgumentException {
+     * @return representation of a permutation corresponding to the permutation
+     * <code>originalData -> permutedData</code>
+     * @throws IllegalArgumentException iff the <code>permutedData</code> and
+     * <code>originalData</code> contains different data
+     */
+    public static <S> List<Double> inducedPermutation(final List<S> originalData,
+                                                      final List<S> permutedData)
+        throws IllegalArgumentException {
+
         if (originalData.size() != permutedData.size()) {
-            throw new IllegalArgumentException("originalData and permutedData must have same
length");
+            throw new MathIllegalArgumentException(LocalizedFormats.WRONG_ORIG_AND_PERMUTED_SIZE,
+                                                   originalData.size(), permutedData.size());
         }
         int l = originalData.size();
 
@@ -263,7 +274,7 @@ public abstract class RandomKey<T> exten
         for (int i=0; i<l; i++) {
             int index = origDataCopy.indexOf(permutedData.get(i));
             if (index == -1) {
-                throw new IllegalArgumentException("originalData and permutedData must contain
the same objects.");
+                throw new MathIllegalArgumentException(LocalizedFormats.DIFFERENT_ORIG_AND_PERMUTED_DATA);
             }
             res[index] = (double) i / l;
             origDataCopy.set(index, null);
@@ -285,7 +296,7 @@ public abstract class RandomKey<T> exten
      * @param l length of list to generate
      * @return list of integers from 0 to l-1
      */
-    private static List<Integer> baseSequence(int l) {
+    private static List<Integer> baseSequence(final int l) {
         List<Integer> baseSequence = new ArrayList<Integer> (l);
         for (int i=0; i<l; i++) {
             baseSequence.add(i);

Modified: commons/proper/math/trunk/src/main/java/org/apache/commons/math/genetics/RandomKeyMutation.java
URL: http://svn.apache.org/viewvc/commons/proper/math/trunk/src/main/java/org/apache/commons/math/genetics/RandomKeyMutation.java?rev=1235038&r1=1235037&r2=1235038&view=diff
==============================================================================
--- commons/proper/math/trunk/src/main/java/org/apache/commons/math/genetics/RandomKeyMutation.java
(original)
+++ commons/proper/math/trunk/src/main/java/org/apache/commons/math/genetics/RandomKeyMutation.java
Mon Jan 23 22:26:37 2012
@@ -37,11 +37,10 @@ public class RandomKeyMutation implement
      * @throws MathIllegalArgumentException if <code>original</code> is not a
      * {@link RandomKey} instance
      */
-    public Chromosome mutate(Chromosome original) {
+    public Chromosome mutate(final Chromosome original) {
         if (!(original instanceof RandomKey<?>)) {
-            throw new MathIllegalArgumentException(
-                    LocalizedFormats.RANDOMKEY_MUTATION_WRONG_CLASS,
-                    original.getClass().getSimpleName());
+            throw new MathIllegalArgumentException(LocalizedFormats.RANDOMKEY_MUTATION_WRONG_CLASS,
+                                                   original.getClass().getSimpleName());
         }
 
         RandomKey<?> originalRk = (RandomKey<?>) original;

Modified: commons/proper/math/trunk/src/main/java/org/apache/commons/math/genetics/TournamentSelection.java
URL: http://svn.apache.org/viewvc/commons/proper/math/trunk/src/main/java/org/apache/commons/math/genetics/TournamentSelection.java?rev=1235038&r1=1235037&r2=1235038&view=diff
==============================================================================
--- commons/proper/math/trunk/src/main/java/org/apache/commons/math/genetics/TournamentSelection.java
(original)
+++ commons/proper/math/trunk/src/main/java/org/apache/commons/math/genetics/TournamentSelection.java
Mon Jan 23 22:26:37 2012
@@ -19,6 +19,9 @@ package org.apache.commons.math.genetics
 import java.util.ArrayList;
 import java.util.List;
 
+import org.apache.commons.math.exception.MathIllegalArgumentException;
+import org.apache.commons.math.exception.util.LocalizedFormats;
+
 /**
  * Tournament selection scheme. Each of the two selected chromosomes is selected
  * based on n-ary tournament -- this is done by drawing {@link #arity} random
@@ -36,10 +39,9 @@ public class TournamentSelection impleme
     /**
      * Creates a new TournamentSelection instance.
      *
-     * @param arity
-     *            how many chromosomes will be drawn to the tournament
+     * @param arity how many chromosomes will be drawn to the tournament
      */
-    public TournamentSelection(int arity) {
+    public TournamentSelection(final int arity) {
         this.arity = arity;
     }
 
@@ -49,15 +51,12 @@ public class TournamentSelection impleme
      * drawing {@link #arity} random chromosomes without replacement from the
      * population, and then selecting the fittest chromosome among them.
      *
-     * @param population
-     *            the population from which the chromosomes are choosen.
+     * @param population the population from which the chromosomes are choosen.
      * @return the selected chromosomes.
      */
-    public ChromosomePair select(Population population) {
-        return new ChromosomePair(
-                tournament((ListPopulation) population),
-                tournament((ListPopulation)population)
-                );
+    public ChromosomePair select(final Population population) {
+        return new ChromosomePair(tournament((ListPopulation) population),
+                                  tournament((ListPopulation)population));
     }
 
     /**
@@ -65,13 +64,15 @@ public class TournamentSelection impleme
      * chromosomes without replacement from the population, and then select the
      * fittest chromosome among them.
      *
-     * @param population
-     *            the population from which the chromosomes are choosen.
+     * @param population the population from which the chromosomes are choosen.
      * @return the selected chromosome.
+     * @throws MathIllegalArgumentException if the tournament arity is bigger than the
+     * population size
      */
-    private Chromosome tournament(ListPopulation population) {
+    private Chromosome tournament(final ListPopulation population) {
         if (population.getPopulationSize() < this.arity) {
-            throw new IllegalArgumentException("Tournament arity cannot be bigger than population
size.");
+            throw new MathIllegalArgumentException(LocalizedFormats.TOO_LARGE_TOURNAMENT_ARITY,
+                                                   arity, population.getPopulationSize());
         }
         // auxiliary population
         ListPopulation tournamentPopulation = new ListPopulation(this.arity) {
@@ -108,7 +109,7 @@ public class TournamentSelection impleme
      *
      * @param arity arity of the tournament
      */
-    public void setArity(int arity) {
+    public void setArity(final int arity) {
         this.arity = arity;
     }
 



Mime
View raw message