commons-commits mailing list archives

Site index · List index
Message view « Date » · « Thread »
Top « Date » · « Thread »
From er...@apache.org
Subject svn commit: r990792 [2/5] - in /commons/proper/math/trunk/src: main/java/org/apache/commons/math/ main/java/org/apache/commons/math/optimization/ main/java/org/apache/commons/math/optimization/direct/ main/java/org/apache/commons/math/optimization/fitt...
Date Mon, 30 Aug 2010 13:06:24 GMT
Modified: commons/proper/math/trunk/src/main/java/org/apache/commons/math/optimization/SimpleScalarValueChecker.java
URL: http://svn.apache.org/viewvc/commons/proper/math/trunk/src/main/java/org/apache/commons/math/optimization/SimpleScalarValueChecker.java?rev=990792&r1=990791&r2=990792&view=diff
==============================================================================
--- commons/proper/math/trunk/src/main/java/org/apache/commons/math/optimization/SimpleScalarValueChecker.java (original)
+++ commons/proper/math/trunk/src/main/java/org/apache/commons/math/optimization/SimpleScalarValueChecker.java Mon Aug 30 13:06:22 2010
@@ -17,65 +17,76 @@
 
 package org.apache.commons.math.optimization;
 
-import org.apache.commons.math.util.FastMath;
 import org.apache.commons.math.util.MathUtils;
+import org.apache.commons.math.util.FastMath;
+import org.apache.commons.math.exception.DimensionMismatchException;
 
 /**
- * Simple implementation of the {@link RealConvergenceChecker} interface using
+ * Simple implementation of the {@link ConvergenceChecker} interface using
  * only objective function values.
- * <p>
+ *
  * Convergence is considered to have been reached if either the relative
  * difference between the objective function values is smaller than a
  * threshold or if either the absolute difference between the objective
  * function values is smaller than another threshold.
- * </p>
+ *
  * @version $Revision$ $Date$
- * @since 2.0
+ * @since 3.0
  */
-public class SimpleScalarValueChecker implements RealConvergenceChecker {
-
-    /** Default relative threshold. */
-    private static final double DEFAULT_RELATIVE_THRESHOLD = 100 * MathUtils.EPSILON;
-
-    /** Default absolute threshold. */
-    private static final double DEFAULT_ABSOLUTE_THRESHOLD = 100 * MathUtils.SAFE_MIN;
-
-    /** Relative tolerance threshold. */
-    private final double relativeThreshold;
-
-    /** Absolute tolerance threshold. */
-    private final double absoluteThreshold;
-
-   /** Build an instance with default threshold.
+public class SimpleScalarValueChecker
+    extends AbstractConvergenceChecker<RealPointValuePair> {
+    /**
+     * Build an instance with default thresholds.
      */
-    public SimpleScalarValueChecker() {
-        this.relativeThreshold = DEFAULT_RELATIVE_THRESHOLD;
-        this.absoluteThreshold = DEFAULT_ABSOLUTE_THRESHOLD;
-    }
+    public SimpleScalarValueChecker() {}
 
-    /** Build an instance with a specified threshold.
-     * <p>
+    /** Build an instance with specified thresholds.
+     *
      * In order to perform only relative checks, the absolute tolerance
      * must be set to a negative value. In order to perform only absolute
      * checks, the relative tolerance must be set to a negative value.
-     * </p>
+     *
      * @param relativeThreshold relative tolerance threshold
      * @param absoluteThreshold absolute tolerance threshold
      */
     public SimpleScalarValueChecker(final double relativeThreshold,
                                     final double absoluteThreshold) {
-        this.relativeThreshold = relativeThreshold;
-        this.absoluteThreshold = absoluteThreshold;
+        super(relativeThreshold, absoluteThreshold);
     }
 
-    /** {@inheritDoc} */
+    /**
+     * Check if the optimization algorithm has converged considering the
+     * last two points.
+     * This method may be called several time from the same algorithm
+     * iteration with different points. This can be detected by checking the
+     * iteration number at each call if needed. Each time this method is
+     * called, the previous and current point correspond to points with the
+     * same role at each iteration, so they can be compared. As an example,
+     * simplex-based algorithms call this method for all points of the simplex,
+     * not only for the best or worst ones.
+     *
+     * @param iteration Index of current iteration
+     * @param points Points used for checking convergence. The list must
+     * contain two elements:
+     * <ul>
+     *  <li>the previous best point,</li>
+     *  <li>the current best point.</li>
+     * </ul>
+     * @return {@code true} if the algorithm has converged.
+     * @throws DimensionMismatchException if the length of the {@code points}
+     * list is not equal to 2.
+     */
     public boolean converged(final int iteration,
-                             final RealPointValuePair previous,
-                             final RealPointValuePair current) {
-        final double p          = previous.getValue();
-        final double c          = current.getValue();
+                             final RealPointValuePair ... points) {
+        if (points.length != 2) {
+            throw new DimensionMismatchException(points.length, 2);
+        }
+
+        final double p = points[0].getValue();
+        final double c = points[1].getValue();
         final double difference = FastMath.abs(p - c);
-        final double size       = FastMath.max(FastMath.abs(p), FastMath.abs(c));
-        return (difference <= (size * relativeThreshold)) || (difference <= absoluteThreshold);
+        final double size = FastMath.max(FastMath.abs(p), FastMath.abs(c));
+        return (difference <= size * getRelativeThreshold() ||
+                difference <= getAbsoluteThreshold());
     }
 }

Modified: commons/proper/math/trunk/src/main/java/org/apache/commons/math/optimization/SimpleVectorialPointChecker.java
URL: http://svn.apache.org/viewvc/commons/proper/math/trunk/src/main/java/org/apache/commons/math/optimization/SimpleVectorialPointChecker.java?rev=990792&r1=990791&r2=990792&view=diff
==============================================================================
--- commons/proper/math/trunk/src/main/java/org/apache/commons/math/optimization/SimpleVectorialPointChecker.java (original)
+++ commons/proper/math/trunk/src/main/java/org/apache/commons/math/optimization/SimpleVectorialPointChecker.java Mon Aug 30 13:06:22 2010
@@ -17,74 +17,83 @@
 
 package org.apache.commons.math.optimization;
 
-import org.apache.commons.math.util.FastMath;
 import org.apache.commons.math.util.MathUtils;
+import org.apache.commons.math.exception.DimensionMismatchException;
 
 /**
- * Simple implementation of the {@link VectorialConvergenceChecker} interface using
+ * Simple implementation of the {@link ConvergenceChecker} interface using
  * only point coordinates.
- * <p>
+ *
  * Convergence is considered to have been reached if either the relative
  * difference between each point coordinate are smaller than a threshold
  * or if either the absolute difference between the point coordinates are
  * smaller than another threshold.
- * </p>
+ *
  * @version $Revision$ $Date$
- * @since 2.0
+ * @since 3.0
  */
-public class SimpleVectorialPointChecker implements VectorialConvergenceChecker {
-
-    /** Default relative threshold. */
-    private static final double DEFAULT_RELATIVE_THRESHOLD = 100 * MathUtils.EPSILON;
-
-    /** Default absolute threshold. */
-    private static final double DEFAULT_ABSOLUTE_THRESHOLD = 100 * MathUtils.SAFE_MIN;
-
-    /** Relative tolerance threshold. */
-    private final double relativeThreshold;
-
-    /** Absolute tolerance threshold. */
-    private final double absoluteThreshold;
-
-   /** Build an instance with default threshold.
+public class SimpleVectorialPointChecker
+    extends AbstractConvergenceChecker<VectorialPointValuePair> {
+    /**
+     * Build an instance with default threshold.
      */
-    public SimpleVectorialPointChecker() {
-        this.relativeThreshold = DEFAULT_RELATIVE_THRESHOLD;
-        this.absoluteThreshold = DEFAULT_ABSOLUTE_THRESHOLD;
-    }
+    public SimpleVectorialPointChecker() {}
 
-    /** Build an instance with a specified threshold.
-     * <p>
+    /**
+     * Build an instance with a specified threshold.
+     *
      * In order to perform only relative checks, the absolute tolerance
      * must be set to a negative value. In order to perform only absolute
      * checks, the relative tolerance must be set to a negative value.
-     * </p>
+     *
      * @param relativeThreshold relative tolerance threshold
      * @param absoluteThreshold absolute tolerance threshold
      */
     public SimpleVectorialPointChecker(final double relativeThreshold,
                                        final double absoluteThreshold) {
-        this.relativeThreshold = relativeThreshold;
-        this.absoluteThreshold = absoluteThreshold;
+        super(relativeThreshold, absoluteThreshold);
     }
 
-    /** {@inheritDoc} */
+    /**
+     * Check if the optimization algorithm has converged considering the
+     * last two points.
+     * This method may be called several time from the same algorithm
+     * iteration with different points. This can be detected by checking the
+     * iteration number at each call if needed. Each time this method is
+     * called, the previous and current point correspond to points with the
+     * same role at each iteration, so they can be compared. As an example,
+     * simplex-based algorithms call this method for all points of the simplex,
+     * not only for the best or worst ones.
+     *
+     * @param iteration Index of current iteration
+     * @param points Points used for checking convergence. The list must
+     * contain two elements:
+     * <ul>
+     *  <li>the previous best point,</li>
+     *  <li>the current best point.</li>
+     * </ul>
+     * @return {@code true} if the algorithm has converged.
+     * @throws DimensionMismatchException if the length of the {@code points}
+     * list is not equal to 2.
+     */
     public boolean converged(final int iteration,
-                             final VectorialPointValuePair previous,
-                             final VectorialPointValuePair current) {
-        final double[] p = previous.getPointRef();
-        final double[] c = current.getPointRef();
+                             final VectorialPointValuePair ... points) {
+        if (points.length != 2) {
+            throw new DimensionMismatchException(points.length, 2);
+        }
+
+        final double[] p = points[0].getPointRef();
+        final double[] c = points[1].getPointRef();
         for (int i = 0; i < p.length; ++i) {
-            final double pi         = p[i];
-            final double ci         = c[i];
-            final double difference = FastMath.abs(pi - ci);
-            final double size       = FastMath.max(FastMath.abs(pi), FastMath.abs(ci));
-            if ((difference > (size * relativeThreshold)) &&
-                (difference > absoluteThreshold)) {
+            final double pi = p[i];
+            final double ci = c[i];
+            final double difference = Math.abs(pi - ci);
+            final double size = Math.max(Math.abs(pi), Math.abs(ci));
+            if (difference > size * getRelativeThreshold() &&
+                difference > getAbsoluteThreshold()) {
                 return false;
             }
         }
         return true;
     }
-
 }

Modified: commons/proper/math/trunk/src/main/java/org/apache/commons/math/optimization/SimpleVectorialValueChecker.java
URL: http://svn.apache.org/viewvc/commons/proper/math/trunk/src/main/java/org/apache/commons/math/optimization/SimpleVectorialValueChecker.java?rev=990792&r1=990791&r2=990792&view=diff
==============================================================================
--- commons/proper/math/trunk/src/main/java/org/apache/commons/math/optimization/SimpleVectorialValueChecker.java (original)
+++ commons/proper/math/trunk/src/main/java/org/apache/commons/math/optimization/SimpleVectorialValueChecker.java Mon Aug 30 13:06:22 2010
@@ -19,72 +19,82 @@ package org.apache.commons.math.optimiza
 
 import org.apache.commons.math.util.FastMath;
 import org.apache.commons.math.util.MathUtils;
+import org.apache.commons.math.exception.DimensionMismatchException;
 
 /**
- * Simple implementation of the {@link VectorialConvergenceChecker} interface using
+ * Simple implementation of the {@link ConvergenceChecker} interface using
  * only objective function values.
- * <p>
+ *
  * Convergence is considered to have been reached if either the relative
  * difference between the objective function values is smaller than a
  * threshold or if either the absolute difference between the objective
  * function values is smaller than another threshold for all vectors elements.
- * </p>
+ *
  * @version $Revision$ $Date$
- * @since 2.0
+ * @since 3.0
  */
-public class SimpleVectorialValueChecker implements VectorialConvergenceChecker {
-
-    /** Default relative threshold. */
-    private static final double DEFAULT_RELATIVE_THRESHOLD = 100 * MathUtils.EPSILON;
-
-    /** Default absolute threshold. */
-    private static final double DEFAULT_ABSOLUTE_THRESHOLD = 100 * MathUtils.SAFE_MIN;
-
-    /** Relative tolerance threshold. */
-    private final double relativeThreshold;
-
-    /** Absolute tolerance threshold. */
-    private final double absoluteThreshold;
-
-   /** Build an instance with default threshold.
+public class SimpleVectorialValueChecker
+    extends AbstractConvergenceChecker<VectorialPointValuePair> {
+    /**
+     * Build an instance with default thresholds.
      */
-    public SimpleVectorialValueChecker() {
-        this.relativeThreshold = DEFAULT_RELATIVE_THRESHOLD;
-        this.absoluteThreshold = DEFAULT_ABSOLUTE_THRESHOLD;
-    }
+    public SimpleVectorialValueChecker() {}
 
-    /** Build an instance with a specified threshold.
-     * <p>
+    /**
+     * Build an instance with specified thresholds.
+     *
      * In order to perform only relative checks, the absolute tolerance
      * must be set to a negative value. In order to perform only absolute
      * checks, the relative tolerance must be set to a negative value.
-     * </p>
+     *
      * @param relativeThreshold relative tolerance threshold
      * @param absoluteThreshold absolute tolerance threshold
      */
     public SimpleVectorialValueChecker(final double relativeThreshold,
                                        final double absoluteThreshold) {
-        this.relativeThreshold = relativeThreshold;
-        this.absoluteThreshold = absoluteThreshold;
+        super(relativeThreshold, absoluteThreshold);
     }
 
-    /** {@inheritDoc} */
+    /**
+     * Check if the optimization algorithm has converged considering the
+     * last two points.
+     * This method may be called several time from the same algorithm
+     * iteration with different points. This can be detected by checking the
+     * iteration number at each call if needed. Each time this method is
+     * called, the previous and current point correspond to points with the
+     * same role at each iteration, so they can be compared. As an example,
+     * simplex-based algorithms call this method for all points of the simplex,
+     * not only for the best or worst ones.
+     *
+     * @param iteration Index of current iteration
+     * @param points Points used for checking convergence. The list must
+     * contain two elements:
+     * <ul>
+     *  <li>the previous best point,</li>
+     *  <li>the current best point.</li>
+     * </ul>
+     * @return {@code true} if the algorithm has converged.
+     * @throws DimensionMismatchException if the length of the {@code points}
+     * list is not equal to 2.
+     */
     public boolean converged(final int iteration,
-                             final VectorialPointValuePair previous,
-                             final VectorialPointValuePair current) {
-        final double[] p        = previous.getValueRef();
-        final double[] c        = current.getValueRef();
+                             final VectorialPointValuePair ... points) {
+        if (points.length != 2) {
+            throw new DimensionMismatchException(points.length, 2);
+        }
+
+        final double[] p = points[0].getValueRef();
+        final double[] c = points[1].getValueRef();
         for (int i = 0; i < p.length; ++i) {
             final double pi         = p[i];
             final double ci         = c[i];
             final double difference = FastMath.abs(pi - ci);
             final double size       = FastMath.max(FastMath.abs(pi), FastMath.abs(ci));
-            if ((difference > (size * relativeThreshold)) &&
-                (difference > absoluteThreshold)) {
+            if (difference > size * getRelativeThreshold() &&
+                difference > getAbsoluteThreshold()) {
                 return false;
             }
         }
         return true;
     }
-
 }

Modified: commons/proper/math/trunk/src/main/java/org/apache/commons/math/optimization/direct/DirectSearchOptimizer.java
URL: http://svn.apache.org/viewvc/commons/proper/math/trunk/src/main/java/org/apache/commons/math/optimization/direct/DirectSearchOptimizer.java?rev=990792&r1=990791&r2=990792&view=diff
==============================================================================
--- commons/proper/math/trunk/src/main/java/org/apache/commons/math/optimization/direct/DirectSearchOptimizer.java (original)
+++ commons/proper/math/trunk/src/main/java/org/apache/commons/math/optimization/direct/DirectSearchOptimizer.java Mon Aug 30 13:06:22 2010
@@ -22,16 +22,19 @@ import java.util.Comparator;
 
 import org.apache.commons.math.FunctionEvaluationException;
 import org.apache.commons.math.MathRuntimeException;
-import org.apache.commons.math.MaxEvaluationsExceededException;
-import org.apache.commons.math.MaxIterationsExceededException;
+import org.apache.commons.math.util.Incrementor;
 import org.apache.commons.math.analysis.MultivariateRealFunction;
+import org.apache.commons.math.exception.MaxCountExceededException;
+import org.apache.commons.math.exception.TooManyEvaluationsException;
+import org.apache.commons.math.exception.DimensionMismatchException;
 import org.apache.commons.math.exception.util.LocalizedFormats;
 import org.apache.commons.math.optimization.GoalType;
 import org.apache.commons.math.optimization.MultivariateRealOptimizer;
 import org.apache.commons.math.optimization.OptimizationException;
-import org.apache.commons.math.optimization.RealConvergenceChecker;
+import org.apache.commons.math.optimization.ConvergenceChecker;
 import org.apache.commons.math.optimization.RealPointValuePair;
 import org.apache.commons.math.optimization.SimpleScalarValueChecker;
+import org.apache.commons.math.optimization.general.AbstractScalarOptimizer;
 
 /**
  * This class implements simplex-based direct search optimization
@@ -67,7 +70,7 @@ import org.apache.commons.math.optimizat
  * change, the start configuration will be reset to a default one with the
  * appropriate dimensions.</p>
  *
- * <p>If {@link #setConvergenceChecker(RealConvergenceChecker)} is not called,
+ * <p>If {@link #setConvergenceChecker(ConvergenceChecker)} is not called,
  * a default {@link SimpleScalarValueChecker} is used.</p>
  *
  * <p>Convergence is checked by providing the <em>worst</em> points of
@@ -86,41 +89,24 @@ import org.apache.commons.math.optimizat
  * @version $Revision$ $Date$
  * @since 1.2
  */
-public abstract class DirectSearchOptimizer implements MultivariateRealOptimizer {
-
+public abstract class DirectSearchOptimizer
+    extends AbstractScalarOptimizer
+    implements MultivariateRealOptimizer {
     /** Simplex. */
     protected RealPointValuePair[] simplex;
-
-    /** Objective function. */
-    private MultivariateRealFunction f;
-
-    /** Convergence checker. */
-    private RealConvergenceChecker checker;
-
-    /** Maximal number of iterations allowed. */
-    private int maxIterations;
-
-    /** Number of iterations already performed. */
-    private int iterations;
-
-    /** Maximal number of evaluations allowed. */
-    private int maxEvaluations;
-
-    /** Number of evaluations already performed. */
-    private int evaluations;
-
     /** Start simplex configuration. */
     private double[][] startConfiguration;
 
-    /** Simple constructor.
+    /**
+     * Default constructor.
      */
     protected DirectSearchOptimizer() {
         setConvergenceChecker(new SimpleScalarValueChecker());
-        setMaxIterations(Integer.MAX_VALUE);
-        setMaxEvaluations(Integer.MAX_VALUE);
     }
 
-    /** Set start configuration for simplex.
+    /**
+     * Set start configuration for simplex.
+     *
      * <p>The start configuration for simplex is built from a box parallel to
      * the canonical axes of the space. The simplex is the subset of vertices
      * of a box parallel to the canonical axes. It is built as the path followed
@@ -132,9 +118,10 @@ public abstract class DirectSearchOptimi
      * start simplex would be: { (1, 1, 1), (2, 1, 1), (2, 11, 1), (2, 11, 3) }.
      * The first vertex would be set to the start point at (1, 1, 1) and the
      * last vertex would be set to the diagonally opposite vertex at (2, 11, 3).</p>
-     * @param steps steps along the canonical axes representing box edges,
-     * they may be negative but not null
-     * @exception IllegalArgumentException if one step is null
+     *
+     * @param steps Steps along the canonical axes representing box edges. They
+     * may be negative but not zero.
+     * @throws IllegalArgumentException if one step is zero.
      */
     public void setStartConfiguration(final double[] steps)
         throws IllegalArgumentException {
@@ -154,14 +141,16 @@ public abstract class DirectSearchOptimi
         }
     }
 
-    /** Set start configuration for simplex.
-     * <p>The real initial simplex will be set up by moving the reference
+    /**
+     * Set start configuration for simplex.
+     * The real initial simplex will be set up by moving the reference
      * simplex such that its first point is located at the start point of the
-     * optimization.</p>
-     * @param referenceSimplex reference simplex
-     * @exception IllegalArgumentException if the reference simplex does not
+     * optimization.
+     *
+     * @param referenceSimplex Reference simplex.
+     * @throws IllegalArgumentException if the reference simplex does not
      * contain at least one point, or if there is a dimension mismatch
-     * in the reference simplex or if one of its vertices is duplicated
+     * in the reference simplex or if one of its vertices is duplicated.
      */
     public void setStartConfiguration(final double[][] referenceSimplex)
         throws IllegalArgumentException {
@@ -183,8 +172,7 @@ public abstract class DirectSearchOptimi
 
             // safety checks
             if (refI.length != n) {
-                throw MathRuntimeException.createIllegalArgumentException(
-                      LocalizedFormats.DIMENSIONS_MISMATCH_SIMPLE, refI.length, n);
+                throw new DimensionMismatchException(refI.length, n);
             }
             for (int j = 0; j < i; ++j) {
                 final double[] refJ = referenceSimplex[j];
@@ -208,92 +196,46 @@ public abstract class DirectSearchOptimi
                     confI[k] = refI[k] - ref0[k];
                 }
             }
-
         }
-
     }
 
     /** {@inheritDoc} */
-    public void setMaxIterations(int maxIterations) {
-        this.maxIterations = maxIterations;
-    }
-
-    /** {@inheritDoc} */
-    public int getMaxIterations() {
-        return maxIterations;
-    }
-
-    /** {@inheritDoc} */
-    public void setMaxEvaluations(int maxEvaluations) {
-        this.maxEvaluations = maxEvaluations;
-    }
-
-    /** {@inheritDoc} */
-    public int getMaxEvaluations() {
-        return maxEvaluations;
-    }
-
-    /** {@inheritDoc} */
-    public int getIterations() {
-        return iterations;
-    }
-
-    /** {@inheritDoc} */
-    public int getEvaluations() {
-        return evaluations;
-    }
-
-    /** {@inheritDoc} */
-    public void setConvergenceChecker(RealConvergenceChecker convergenceChecker) {
-        this.checker = convergenceChecker;
-    }
-
-    /** {@inheritDoc} */
-    public RealConvergenceChecker getConvergenceChecker() {
-        return checker;
-    }
-
-    /** {@inheritDoc} */
-    public RealPointValuePair optimize(final MultivariateRealFunction function,
-                                       final GoalType goalType,
-                                       final double[] startPoint)
-        throws FunctionEvaluationException, OptimizationException,
-        IllegalArgumentException {
+    protected RealPointValuePair doOptimize()
+        throws FunctionEvaluationException {
 
+        final double[] startPoint = getStartPoint();
         if ((startConfiguration == null) ||
             (startConfiguration.length != startPoint.length)) {
-            // no initial configuration has been set up for simplex
-            // build a default one from a unit hypercube
+            // No initial configuration has been set up for simplex
+            // build a default one from a unit hypercube.
             final double[] unit = new double[startPoint.length];
             Arrays.fill(unit, 1.0);
             setStartConfiguration(unit);
         }
+        
+        final boolean isMinim = (getGoalType() == GoalType.MINIMIZE);
+        final Comparator<RealPointValuePair> comparator
+            = new Comparator<RealPointValuePair>() {
+            public int compare(final RealPointValuePair o1,
+                               final RealPointValuePair o2) {
+                final double v1 = o1.getValue();
+                final double v2 = o2.getValue();
+                return isMinim ? Double.compare(v1, v2) : Double.compare(v2, v1);
+            }
+        };
 
-        this.f = function;
-        final Comparator<RealPointValuePair> comparator =
-            new Comparator<RealPointValuePair>() {
-                public int compare(final RealPointValuePair o1,
-                                   final RealPointValuePair o2) {
-                    final double v1 = o1.getValue();
-                    final double v2 = o2.getValue();
-                    return (goalType == GoalType.MINIMIZE) ?
-                            Double.compare(v1, v2) : Double.compare(v2, v1);
-                }
-            };
-
-        // initialize search
-        iterations  = 0;
-        evaluations = 0;
+        // Initialize search.
         buildSimplex(startPoint);
         evaluateSimplex(comparator);
 
         RealPointValuePair[] previous = new RealPointValuePair[simplex.length];
+        int iteration = 0;
+        final ConvergenceChecker<RealPointValuePair> checker = getConvergenceChecker();
         while (true) {
-
-            if (iterations > 0) {
+            if (iteration > 0) {
                 boolean converged = true;
                 for (int i = 0; i < simplex.length; ++i) {
-                    converged &= checker.converged(iterations, previous[i], simplex[i]);
+                    converged &= checker.converged(iteration, previous[i], simplex[i]);
                 }
                 if (converged) {
                     // we have found an optimum
@@ -301,65 +243,37 @@ public abstract class DirectSearchOptimi
                 }
             }
 
-            // we still need to search
+            // We still need to search.
             System.arraycopy(simplex, 0, previous, 0, simplex.length);
             iterateSimplex(comparator);
-
-        }
-
-    }
-
-    /** Increment the iterations counter by 1.
-     * @exception OptimizationException if the maximal number
-     * of iterations is exceeded
-     */
-    protected void incrementIterationsCounter()
-        throws OptimizationException {
-        if (++iterations > maxIterations) {
-            throw new OptimizationException(new MaxIterationsExceededException(maxIterations));
+            ++iteration;
         }
     }
 
-    /** Compute the next simplex of the algorithm.
-     * @param comparator comparator to use to sort simplex vertices from best to worst
-     * @exception FunctionEvaluationException if the function cannot be evaluated at
-     * some point
-     * @exception OptimizationException if the algorithm fails to converge
-     * @exception IllegalArgumentException if the start point dimension is wrong
+    /**
+     * Compute the next simplex of the algorithm.
+     *
+     * @param comparator Comparator to use to sort simplex vertices from best to worst.
+     * @throws FunctionEvaluationException if the function cannot be evaluated at
+     * some point.
+     * @throws TooManyEvaluationsException if the algorithm fails to converge.
+     * @throws DimensionMismatchException if the start point dimension is wrong.
      */
     protected abstract void iterateSimplex(final Comparator<RealPointValuePair> comparator)
-        throws FunctionEvaluationException, OptimizationException, IllegalArgumentException;
+        throws FunctionEvaluationException;
 
-    /** Evaluate the objective function on one point.
-     * <p>A side effect of this method is to count the number of
-     * function evaluations</p>
-     * @param x point on which the objective function should be evaluated
-     * @return objective function value at the given point
-     * @exception FunctionEvaluationException if no value can be computed for the
-     * parameters or if the maximal number of evaluations is exceeded
-     * @exception IllegalArgumentException if the start point dimension is wrong
+    /**
+     * Build an initial simplex.
+     *
+     * @param startPoint Start point for optimization.
+     * @throws DimensionMismatchException if the start point does not match
+     * simplex dimension.
      */
-    protected double evaluate(final double[] x)
-        throws FunctionEvaluationException, IllegalArgumentException {
-        if (++evaluations > maxEvaluations) {
-            throw new FunctionEvaluationException(new MaxEvaluationsExceededException(maxEvaluations),
-                                                  x);
-        }
-        return f.value(x);
-    }
-
-    /** Build an initial simplex.
-     * @param startPoint the start point for optimization
-     * @exception IllegalArgumentException if the start point does not match
-     * simplex dimension
-     */
-    private void buildSimplex(final double[] startPoint)
-        throws IllegalArgumentException {
+    private void buildSimplex(final double[] startPoint) {
 
         final int n = startPoint.length;
         if (n != startConfiguration.length) {
-            throw MathRuntimeException.createIllegalArgumentException(
-                  LocalizedFormats.DIMENSIONS_MISMATCH_SIMPLE, n, startConfiguration.length);
+            throw new DimensionMismatchException(n, startConfiguration.length);
         }
 
         // set first vertex
@@ -368,41 +282,43 @@ public abstract class DirectSearchOptimi
 
         // set remaining vertices
         for (int i = 0; i < n; ++i) {
-            final double[] confI   = startConfiguration[i];
+            final double[] confI = startConfiguration[i];
             final double[] vertexI = new double[n];
             for (int k = 0; k < n; ++k) {
                 vertexI[k] = startPoint[k] + confI[k];
             }
             simplex[i + 1] = new RealPointValuePair(vertexI, Double.NaN);
         }
-
     }
 
-    /** Evaluate all the non-evaluated points of the simplex.
-     * @param comparator comparator to use to sort simplex vertices from best to worst
-     * @exception FunctionEvaluationException if no value can be computed for the parameters
-     * @exception OptimizationException if the maximal number of evaluations is exceeded
+    /**
+     * Evaluate all the non-evaluated points of the simplex.
+     *
+     * @param comparator Comparator to use to sort simplex vertices from best to worst.
+     * @throws FunctionEvaluationException if no value can be computed for the parameters.
+     * @throws TooManyEvaluationsException if the maximal number of evaluations is exceeded.
      */
     protected void evaluateSimplex(final Comparator<RealPointValuePair> comparator)
-        throws FunctionEvaluationException, OptimizationException {
+        throws FunctionEvaluationException {
 
-        // evaluate the objective function at all non-evaluated simplex points
+        // Evaluate the objective function at all non-evaluated simplex points.
         for (int i = 0; i < simplex.length; ++i) {
             final RealPointValuePair vertex = simplex[i];
             final double[] point = vertex.getPointRef();
             if (Double.isNaN(vertex.getValue())) {
-                simplex[i] = new RealPointValuePair(point, evaluate(point), false);
+                simplex[i] = new RealPointValuePair(point, computeObjectiveValue(point), false);
             }
         }
 
-        // sort the simplex from best to worst
+        // Sort the simplex from best to worst.
         Arrays.sort(simplex, comparator);
-
     }
 
-    /** Replace the worst point of the simplex by a new point.
-     * @param pointValuePair point to insert
-     * @param comparator comparator to use to sort simplex vertices from best to worst
+    /**
+     * Replace the worst point of the simplex by a new point.
+     *
+     * @param pointValuePair Point to insert.
+     * @param comparator Comparator to use to sort simplex vertices from best to worst.
      */
     protected void replaceWorstPoint(RealPointValuePair pointValuePair,
                                      final Comparator<RealPointValuePair> comparator) {
@@ -410,11 +326,10 @@ public abstract class DirectSearchOptimi
         for (int i = 0; i < n; ++i) {
             if (comparator.compare(simplex[i], pointValuePair) > 0) {
                 RealPointValuePair tmp = simplex[i];
-                simplex[i]         = pointValuePair;
-                pointValuePair     = tmp;
+                simplex[i] = pointValuePair;
+                pointValuePair = tmp;
             }
         }
         simplex[n] = pointValuePair;
     }
-
 }

Modified: commons/proper/math/trunk/src/main/java/org/apache/commons/math/optimization/direct/MultiDirectional.java
URL: http://svn.apache.org/viewvc/commons/proper/math/trunk/src/main/java/org/apache/commons/math/optimization/direct/MultiDirectional.java?rev=990792&r1=990791&r2=990792&view=diff
==============================================================================
--- commons/proper/math/trunk/src/main/java/org/apache/commons/math/optimization/direct/MultiDirectional.java (original)
+++ commons/proper/math/trunk/src/main/java/org/apache/commons/math/optimization/direct/MultiDirectional.java Mon Aug 30 13:06:22 2010
@@ -20,8 +20,7 @@ package org.apache.commons.math.optimiza
 import java.util.Comparator;
 
 import org.apache.commons.math.FunctionEvaluationException;
-import org.apache.commons.math.optimization.OptimizationException;
-import org.apache.commons.math.optimization.RealConvergenceChecker;
+import org.apache.commons.math.optimization.ConvergenceChecker;
 import org.apache.commons.math.optimization.RealPointValuePair;
 
 /**
@@ -59,72 +58,72 @@ public class MultiDirectional extends Di
     /** {@inheritDoc} */
     @Override
     protected void iterateSimplex(final Comparator<RealPointValuePair> comparator)
-        throws FunctionEvaluationException, OptimizationException, IllegalArgumentException {
+        throws FunctionEvaluationException {
 
-        final RealConvergenceChecker checker = getConvergenceChecker();
+        final ConvergenceChecker<RealPointValuePair> checker = getConvergenceChecker();
+        int iteration = 0;
         while (true) {
+            ++iteration;
 
-            incrementIterationsCounter();
-
-            // save the original vertex
+            // Save the original vertex.
             final RealPointValuePair[] original = simplex;
             final RealPointValuePair best = original[0];
 
-            // perform a reflection step
+            // Perform a reflection step.
             final RealPointValuePair reflected = evaluateNewSimplex(original, 1.0, comparator);
             if (comparator.compare(reflected, best) < 0) {
 
-                // compute the expanded simplex
+                // Compute the expanded simplex.
                 final RealPointValuePair[] reflectedSimplex = simplex;
                 final RealPointValuePair expanded = evaluateNewSimplex(original, khi, comparator);
                 if (comparator.compare(reflected, expanded) <= 0) {
-                    // accept the reflected simplex
+                    // Accept the reflected simplex.
                     simplex = reflectedSimplex;
                 }
 
                 return;
-
             }
 
-            // compute the contracted simplex
+            // Compute the contracted simplex.
             final RealPointValuePair contracted = evaluateNewSimplex(original, gamma, comparator);
             if (comparator.compare(contracted, best) < 0) {
-                // accept the contracted simplex
+                // Accept the contracted simplex.
                 return;
             }
 
-            // check convergence
-            final int iter = getIterations();
+            // Check convergence.
             boolean converged = true;
             for (int i = 0; i < simplex.length; ++i) {
-                converged &= checker.converged(iter, original[i], simplex[i]);
+                converged &= checker.converged(iteration, original[i], simplex[i]);
             }
             if (converged) {
                 return;
             }
-
         }
-
     }
 
-    /** Compute and evaluate a new simplex.
-     * @param original original simplex (to be preserved)
-     * @param coeff linear coefficient
-     * @param comparator comparator to use to sort simplex vertices from best to poorest
-     * @return best point in the transformed simplex
-     * @exception FunctionEvaluationException if the function cannot be evaluated at
-     * some point
-     * @exception OptimizationException if the maximal number of evaluations is exceeded
+    /**
+     * Compute and evaluate a new simplex.
+     *
+     * @param original Original simplex (to be preserved).
+     * @param coeff Linear coefficient.
+     * @param comparator Comparator to use to sort simplex vertices from best
+     * to poorest.
+     * @return the best point in the transformed simplex.
+     * @exception FunctionEvaluationException if the function cannot be
+     * evaluated at some point.
+     * @exception TooManyEvaluationsException if the maximal number of
+     * evaluations is exceeded.
      */
     private RealPointValuePair evaluateNewSimplex(final RealPointValuePair[] original,
                                               final double coeff,
                                               final Comparator<RealPointValuePair> comparator)
-        throws FunctionEvaluationException, OptimizationException {
+        throws FunctionEvaluationException {
 
         final double[] xSmallest = original[0].getPointRef();
         final int n = xSmallest.length;
 
-        // create the linearly transformed simplex
+        // Create the linearly transformed simplex.
         simplex = new RealPointValuePair[n + 1];
         simplex[0] = original[0];
         for (int i = 1; i <= n; ++i) {
@@ -136,10 +135,8 @@ public class MultiDirectional extends Di
             simplex[i] = new RealPointValuePair(xTransformed, Double.NaN, false);
         }
 
-        // evaluate it
+        // Evaluate the simplex.
         evaluateSimplex(comparator);
         return simplex[0];
-
     }
-
 }

Modified: commons/proper/math/trunk/src/main/java/org/apache/commons/math/optimization/direct/NelderMead.java
URL: http://svn.apache.org/viewvc/commons/proper/math/trunk/src/main/java/org/apache/commons/math/optimization/direct/NelderMead.java?rev=990792&r1=990791&r2=990792&view=diff
==============================================================================
--- commons/proper/math/trunk/src/main/java/org/apache/commons/math/optimization/direct/NelderMead.java (original)
+++ commons/proper/math/trunk/src/main/java/org/apache/commons/math/optimization/direct/NelderMead.java Mon Aug 30 13:06:22 2010
@@ -20,7 +20,6 @@ package org.apache.commons.math.optimiza
 import java.util.Comparator;
 
 import org.apache.commons.math.FunctionEvaluationException;
-import org.apache.commons.math.optimization.OptimizationException;
 import org.apache.commons.math.optimization.RealPointValuePair;
 
 /**
@@ -72,9 +71,7 @@ public class NelderMead extends DirectSe
     /** {@inheritDoc} */
     @Override
     protected void iterateSimplex(final Comparator<RealPointValuePair> comparator)
-        throws FunctionEvaluationException, OptimizationException {
-
-        incrementIterationsCounter();
+        throws FunctionEvaluationException {
 
         // the simplex has n+1 point if dimension is n
         final int n = simplex.length - 1;
@@ -104,7 +101,8 @@ public class NelderMead extends DirectSe
         for (int j = 0; j < n; ++j) {
             xR[j] = centroid[j] + rho * (centroid[j] - xWorst[j]);
         }
-        final RealPointValuePair reflected = new RealPointValuePair(xR, evaluate(xR), false);
+        final RealPointValuePair reflected
+            = new RealPointValuePair(xR, computeObjectiveValue(xR), false);
 
         if ((comparator.compare(best, reflected) <= 0) &&
             (comparator.compare(reflected, secondBest) < 0)) {
@@ -119,7 +117,8 @@ public class NelderMead extends DirectSe
             for (int j = 0; j < n; ++j) {
                 xE[j] = centroid[j] + khi * (xR[j] - centroid[j]);
             }
-            final RealPointValuePair expanded = new RealPointValuePair(xE, evaluate(xE), false);
+            final RealPointValuePair expanded
+                = new RealPointValuePair(xE, computeObjectiveValue(xE), false);
 
             if (comparator.compare(expanded, reflected) < 0) {
                 // accept the expansion point
@@ -138,7 +137,8 @@ public class NelderMead extends DirectSe
                 for (int j = 0; j < n; ++j) {
                     xC[j] = centroid[j] + gamma * (xR[j] - centroid[j]);
                 }
-                final RealPointValuePair outContracted = new RealPointValuePair(xC, evaluate(xC), false);
+                final RealPointValuePair outContracted
+                    = new RealPointValuePair(xC, computeObjectiveValue(xC), false);
 
                 if (comparator.compare(outContracted, reflected) <= 0) {
                     // accept the contraction point
@@ -153,7 +153,8 @@ public class NelderMead extends DirectSe
                 for (int j = 0; j < n; ++j) {
                     xC[j] = centroid[j] - gamma * (centroid[j] - xWorst[j]);
                 }
-                final RealPointValuePair inContracted = new RealPointValuePair(xC, evaluate(xC), false);
+                final RealPointValuePair inContracted
+                    = new RealPointValuePair(xC, computeObjectiveValue(xC), false);
 
                 if (comparator.compare(inContracted, worst) < 0) {
                     // accept the contraction point
@@ -173,9 +174,6 @@ public class NelderMead extends DirectSe
                 simplex[i] = new RealPointValuePair(x, Double.NaN, false);
             }
             evaluateSimplex(comparator);
-
         }
-
     }
-
 }

Modified: commons/proper/math/trunk/src/main/java/org/apache/commons/math/optimization/fitting/CurveFitter.java
URL: http://svn.apache.org/viewvc/commons/proper/math/trunk/src/main/java/org/apache/commons/math/optimization/fitting/CurveFitter.java?rev=990792&r1=990791&r2=990792&view=diff
==============================================================================
--- commons/proper/math/trunk/src/main/java/org/apache/commons/math/optimization/fitting/CurveFitter.java (original)
+++ commons/proper/math/trunk/src/main/java/org/apache/commons/math/optimization/fitting/CurveFitter.java Mon Aug 30 13:06:22 2010
@@ -24,7 +24,6 @@ import org.apache.commons.math.FunctionE
 import org.apache.commons.math.analysis.DifferentiableMultivariateVectorialFunction;
 import org.apache.commons.math.analysis.MultivariateMatrixFunction;
 import org.apache.commons.math.optimization.DifferentiableMultivariateVectorialOptimizer;
-import org.apache.commons.math.optimization.OptimizationException;
 import org.apache.commons.math.optimization.VectorialPointValuePair;
 
 /** Fitter for parametric univariate real functions y = f(x).
@@ -120,12 +119,12 @@ public class CurveFitter {
      * @return fitted parameters
      * @exception FunctionEvaluationException if the objective function throws one during
      * the search
-     * @exception OptimizationException if the algorithm failed to converge
-     * @exception IllegalArgumentException if the start point dimension is wrong
+     * @exception ConvergenceException if the algorithm failed to converge
+     * @exception IllegalArgumentException if the start point dimension is wrong.
      */
     public double[] fit(final ParametricRealFunction f,
                         final double[] initialGuess)
-        throws FunctionEvaluationException, OptimizationException, IllegalArgumentException {
+        throws FunctionEvaluationException {
 
         // prepare least squares problem
         double[] target  = new double[observations.size()];
@@ -143,7 +142,6 @@ public class CurveFitter {
 
         // extract the coefficients
         return optimum.getPointRef();
-
     }
 
     /** Vectorial function computing function theoretical values. */

Modified: commons/proper/math/trunk/src/main/java/org/apache/commons/math/optimization/fitting/PolynomialFitter.java
URL: http://svn.apache.org/viewvc/commons/proper/math/trunk/src/main/java/org/apache/commons/math/optimization/fitting/PolynomialFitter.java?rev=990792&r1=990791&r2=990792&view=diff
==============================================================================
--- commons/proper/math/trunk/src/main/java/org/apache/commons/math/optimization/fitting/PolynomialFitter.java (original)
+++ commons/proper/math/trunk/src/main/java/org/apache/commons/math/optimization/fitting/PolynomialFitter.java Mon Aug 30 13:06:22 2010
@@ -21,7 +21,7 @@ import org.apache.commons.math.FunctionE
 import org.apache.commons.math.MathRuntimeException;
 import org.apache.commons.math.analysis.polynomials.PolynomialFunction;
 import org.apache.commons.math.optimization.DifferentiableMultivariateVectorialOptimizer;
-import org.apache.commons.math.optimization.OptimizationException;
+import org.apache.commons.math.exception.ConvergenceException;
 
 /** This class implements a curve fitting specialized for polynomials.
  * <p>Polynomial fitting is a very simple case of curve fitting. The
@@ -69,10 +69,9 @@ public class PolynomialFitter {
 
     /** Get the polynomial fitting the weighted (x, y) points.
      * @return polynomial function best fitting the observed points
-     * @exception OptimizationException if the algorithm failed to converge
+     * @exception ConvergenceException if the algorithm failed to converge
      */
-    public PolynomialFunction fit()
-        throws OptimizationException {
+    public PolynomialFunction fit() {
         try {
             return new PolynomialFunction(fitter.fit(new ParametricPolynomial(), new double[degree + 1]));
         } catch (FunctionEvaluationException fee) {

Modified: commons/proper/math/trunk/src/main/java/org/apache/commons/math/optimization/general/AbstractLeastSquaresOptimizer.java
URL: http://svn.apache.org/viewvc/commons/proper/math/trunk/src/main/java/org/apache/commons/math/optimization/general/AbstractLeastSquaresOptimizer.java?rev=990792&r1=990791&r2=990792&view=diff
==============================================================================
--- commons/proper/math/trunk/src/main/java/org/apache/commons/math/optimization/general/AbstractLeastSquaresOptimizer.java (original)
+++ commons/proper/math/trunk/src/main/java/org/apache/commons/math/optimization/general/AbstractLeastSquaresOptimizer.java Mon Aug 30 13:06:22 2010
@@ -18,8 +18,7 @@
 package org.apache.commons.math.optimization.general;
 
 import org.apache.commons.math.FunctionEvaluationException;
-import org.apache.commons.math.MaxEvaluationsExceededException;
-import org.apache.commons.math.MaxIterationsExceededException;
+import org.apache.commons.math.exception.ConvergenceException;
 import org.apache.commons.math.analysis.DifferentiableMultivariateVectorialFunction;
 import org.apache.commons.math.analysis.MultivariateMatrixFunction;
 import org.apache.commons.math.exception.util.LocalizedFormats;
@@ -27,155 +26,72 @@ import org.apache.commons.math.linear.In
 import org.apache.commons.math.linear.LUDecompositionImpl;
 import org.apache.commons.math.linear.MatrixUtils;
 import org.apache.commons.math.linear.RealMatrix;
-import org.apache.commons.math.optimization.OptimizationException;
 import org.apache.commons.math.optimization.SimpleVectorialValueChecker;
-import org.apache.commons.math.optimization.VectorialConvergenceChecker;
+import org.apache.commons.math.optimization.ConvergenceChecker;
 import org.apache.commons.math.optimization.DifferentiableMultivariateVectorialOptimizer;
 import org.apache.commons.math.optimization.VectorialPointValuePair;
 import org.apache.commons.math.util.FastMath;
 
 /**
  * Base class for implementing least squares optimizers.
- * <p>This base class handles the boilerplate methods associated to thresholds
- * settings, jacobian and error estimation.</p>
+ * It handles the boilerplate methods associated to thresholds settings,
+ * jacobian and error estimation.
+ *
  * @version $Revision$ $Date$
  * @since 1.2
  *
  */
-public abstract class AbstractLeastSquaresOptimizer implements DifferentiableMultivariateVectorialOptimizer {
-
-    /** Default maximal number of iterations allowed. */
-    public static final int DEFAULT_MAX_ITERATIONS = 100;
-
-    /** Convergence checker. */
-    protected VectorialConvergenceChecker checker;
-
+public abstract class AbstractLeastSquaresOptimizer
+    extends BaseAbstractVectorialOptimizer<DifferentiableMultivariateVectorialFunction>
+    implements DifferentiableMultivariateVectorialOptimizer {
     /**
      * Jacobian matrix of the weighted residuals.
-     * <p>This matrix is in canonical form just after the calls to
+     * This matrix is in canonical form just after the calls to
      * {@link #updateJacobian()}, but may be modified by the solver
      * in the derived class (the {@link LevenbergMarquardtOptimizer
-     * Levenberg-Marquardt optimizer} does this).</p>
+     * Levenberg-Marquardt optimizer} does this).
      */
     protected double[][] weightedResidualJacobian;
-
     /** Number of columns of the jacobian matrix. */
     protected int cols;
-
     /** Number of rows of the jacobian matrix. */
     protected int rows;
-
-    /**
-     * Target value for the objective functions at optimum.
-     * @since 2.1
-     */
-    protected double[] targetValues;
-
-    /**
-     * Weight for the least squares cost computation.
-     * @since 2.1
-     */
-    protected double[] residualsWeights;
-
     /** Current point. */
     protected double[] point;
-
     /** Current objective function value. */
     protected double[] objective;
-
+    /** Current residuals. */
+    protected double[] residuals;
     /** Weighted residuals */
     protected double[] weightedResiduals;
-
     /** Cost value (square root of the sum of the residuals). */
     protected double cost;
-
-    /** Maximal number of iterations allowed. */
-    private int maxIterations;
-
-    /** Number of iterations already performed. */
-    private int iterations;
-
-    /** Maximal number of evaluations allowed. */
-    private int maxEvaluations;
-
-    /** Number of evaluations already performed. */
-    private int objectiveEvaluations;
-
-    /** Number of jacobian evaluations. */
-    private int jacobianEvaluations;
-
-    /** Objective function. */
-    private DifferentiableMultivariateVectorialFunction function;
-
     /** Objective function derivatives. */
     private MultivariateMatrixFunction jF;
+    /** Number of evaluations of the Jacobian. */
+    private int jacobianEvaluations;
 
-    /** Simple constructor with default settings.
-     * <p>The convergence check is set to a {@link SimpleVectorialValueChecker}
-     * and the maximal number of evaluation is set to its default value.</p>
+    /**
+     * Simple constructor with default settings.
+     * The convergence check is set to a {@link SimpleVectorialValueChecker}.
      */
-    protected AbstractLeastSquaresOptimizer() {
-        setConvergenceChecker(new SimpleVectorialValueChecker());
-        setMaxIterations(DEFAULT_MAX_ITERATIONS);
-        setMaxEvaluations(Integer.MAX_VALUE);
-    }
-
-    /** {@inheritDoc} */
-    public void setMaxIterations(int maxIterations) {
-        this.maxIterations = maxIterations;
-    }
-
-    /** {@inheritDoc} */
-    public int getMaxIterations() {
-        return maxIterations;
-    }
-
-    /** {@inheritDoc} */
-    public int getIterations() {
-        return iterations;
-    }
-
-    /** {@inheritDoc} */
-    public void setMaxEvaluations(int maxEvaluations) {
-        this.maxEvaluations = maxEvaluations;
-    }
-
-    /** {@inheritDoc} */
-    public int getMaxEvaluations() {
-        return maxEvaluations;
-    }
-
-    /** {@inheritDoc} */
-    public int getEvaluations() {
-        return objectiveEvaluations;
+    protected AbstractLeastSquaresOptimizer() {}
+    /**
+     * @param checker Convergence checker.
+     * @param maxEvaluations Maximal number of function evaluations.
+     */
+    protected AbstractLeastSquaresOptimizer(ConvergenceChecker<VectorialPointValuePair> checker,
+                                            int maxEvaluations) {
+        super(checker, maxEvaluations);
     }
 
-    /** {@inheritDoc} */
+    /**
+     * @return the number of evaluations of the Jacobian function.
+     */
     public int getJacobianEvaluations() {
         return jacobianEvaluations;
     }
 
-    /** {@inheritDoc} */
-    public void setConvergenceChecker(VectorialConvergenceChecker convergenceChecker) {
-        this.checker = convergenceChecker;
-    }
-
-    /** {@inheritDoc} */
-    public VectorialConvergenceChecker getConvergenceChecker() {
-        return checker;
-    }
-
-    /** Increment the iterations counter by 1.
-     * @exception OptimizationException if the maximal number
-     * of iterations is exceeded
-     */
-    protected void incrementIterationsCounter()
-        throws OptimizationException {
-        if (++iterations > maxIterations) {
-            throw new OptimizationException(new MaxIterationsExceededException(maxIterations));
-        }
-    }
-
     /**
      * Update the jacobian matrix.
      * @exception FunctionEvaluationException if the function jacobian
@@ -188,6 +104,9 @@ public abstract class AbstractLeastSquar
             throw new FunctionEvaluationException(point, LocalizedFormats.DIMENSIONS_MISMATCH_SIMPLE,
                                                   weightedResidualJacobian.length, rows);
         }
+
+        final double[] residualsWeights = getWeightRef();
+
         for (int i = 0; i < rows; i++) {
             final double[] ji = weightedResidualJacobian[i];
             double wi = FastMath.sqrt(residualsWeights[i]);
@@ -204,18 +123,16 @@ public abstract class AbstractLeastSquar
      * or its dimension doesn't match problem dimension or maximal number of
      * of evaluations is exceeded
      */
-    protected void updateResidualsAndCost()
-        throws FunctionEvaluationException {
-
-        if (++objectiveEvaluations > maxEvaluations) {
-            throw new FunctionEvaluationException(new MaxEvaluationsExceededException(maxEvaluations),
-                                                  point);
-        }
-        objective = function.value(point);
+    protected void updateResidualsAndCost() throws FunctionEvaluationException {
+        objective = computeObjectiveValue(point);
         if (objective.length != rows) {
             throw new FunctionEvaluationException(point, LocalizedFormats.DIMENSIONS_MISMATCH_SIMPLE,
                                                   objective.length, rows);
         }
+
+        final double[] targetValues = getTargetRef();
+        final double[] residualsWeights = getWeightRef();
+
         cost = 0;
         int index = 0;
         for (int i = 0; i < rows; i++) {
@@ -225,7 +142,6 @@ public abstract class AbstractLeastSquar
             index += cols;
         }
         cost = FastMath.sqrt(cost);
-
     }
 
     /**
@@ -249,7 +165,7 @@ public abstract class AbstractLeastSquar
      * @return chi-square value
      */
     public double getChiSquare() {
-        return cost*cost;
+        return cost * cost;
     }
 
     /**
@@ -257,11 +173,11 @@ public abstract class AbstractLeastSquar
      * @return covariance matrix
      * @exception FunctionEvaluationException if the function jacobian cannot
      * be evaluated
-     * @exception OptimizationException if the covariance matrix
+     * @exception ConvergenceException if the covariance matrix
      * cannot be computed (singular problem)
      */
     public double[][] getCovariances()
-        throws FunctionEvaluationException, OptimizationException {
+        throws FunctionEvaluationException {
 
         // set up the jacobian
         updateJacobian();
@@ -285,7 +201,7 @@ public abstract class AbstractLeastSquar
                 new LUDecompositionImpl(MatrixUtils.createRealMatrix(jTj)).getSolver().getInverse();
             return inverse.getData();
         } catch (InvalidMatrixException ime) {
-            throw new OptimizationException(LocalizedFormats.UNABLE_TO_COMPUTE_COVARIANCE_SINGULAR_PROBLEM);
+            throw new ConvergenceException(LocalizedFormats.UNABLE_TO_COMPUTE_COVARIANCE_SINGULAR_PROBLEM);
         }
 
     }
@@ -295,16 +211,15 @@ public abstract class AbstractLeastSquar
      * <p>Guessing is covariance-based, it only gives rough order of magnitude.</p>
      * @return errors in optimized parameters
      * @exception FunctionEvaluationException if the function jacobian cannot b evaluated
-     * @exception OptimizationException if the covariances matrix cannot be computed
+     * @exception ConvergenceException if the covariances matrix cannot be computed
      * or the number of degrees of freedom is not positive (number of measurements
      * lesser or equal to number of parameters)
      */
     public double[] guessParametersErrors()
-        throws FunctionEvaluationException, OptimizationException {
+        throws FunctionEvaluationException {
         if (rows <= cols) {
-            throw new OptimizationException(
-                    LocalizedFormats.NO_DEGREES_OF_FREEDOM,
-                    rows, cols);
+            throw new ConvergenceException(LocalizedFormats.NO_DEGREES_OF_FREEDOM,
+                                           rows, cols);
         }
         double[] errors = new double[cols];
         final double c = FastMath.sqrt(getChiSquare() / (rows - cols));
@@ -319,46 +234,24 @@ public abstract class AbstractLeastSquar
     public VectorialPointValuePair optimize(final DifferentiableMultivariateVectorialFunction f,
                                             final double[] target, final double[] weights,
                                             final double[] startPoint)
-        throws FunctionEvaluationException, OptimizationException, IllegalArgumentException {
-
-        if (target.length != weights.length) {
-            throw new OptimizationException(LocalizedFormats.DIMENSIONS_MISMATCH_SIMPLE,
-                                            target.length, weights.length);
-        }
+        throws FunctionEvaluationException {
+        // Reset counter.
+        jacobianEvaluations = 0;
 
-        // reset counters
-        iterations           = 0;
-        objectiveEvaluations = 0;
-        jacobianEvaluations  = 0;
-
-        // store least squares problem characteristics
-        function         = f;
-        jF               = f.jacobian();
-        targetValues     = target.clone();
-        residualsWeights = weights.clone();
-        this.point       = startPoint.clone();
-
-        // arrays shared with the other private methods
-        rows      = target.length;
-        cols      = point.length;
+        // Store least squares problem characteristics.
+        jF = f.jacobian();
+        this.residuals = new double[target.length];
+
+        // Arrays shared with the other private methods.
+        point = startPoint.clone();
+        rows = target.length;
+        cols = point.length;
 
         weightedResidualJacobian = new double[rows][cols];
         this.weightedResiduals = new double[rows];
 
         cost = Double.POSITIVE_INFINITY;
 
-        return doOptimize();
-
+        return super.optimize(f, target, weights, startPoint);
     }
-
-    /** Perform the bulk of optimization algorithm.
-     * @return the point/value pair giving the optimal value for objective function
-     * @exception FunctionEvaluationException if the objective function throws one during
-     * the search
-     * @exception OptimizationException if the algorithm failed to converge
-     * @exception IllegalArgumentException if the start point dimension is wrong
-     */
-    protected abstract VectorialPointValuePair doOptimize()
-        throws FunctionEvaluationException, OptimizationException, IllegalArgumentException;
-
 }

Modified: commons/proper/math/trunk/src/main/java/org/apache/commons/math/optimization/general/AbstractScalarDifferentiableOptimizer.java
URL: http://svn.apache.org/viewvc/commons/proper/math/trunk/src/main/java/org/apache/commons/math/optimization/general/AbstractScalarDifferentiableOptimizer.java?rev=990792&r1=990791&r2=990792&view=diff
==============================================================================
--- commons/proper/math/trunk/src/main/java/org/apache/commons/math/optimization/general/AbstractScalarDifferentiableOptimizer.java (original)
+++ commons/proper/math/trunk/src/main/java/org/apache/commons/math/optimization/general/AbstractScalarDifferentiableOptimizer.java Mon Aug 30 13:06:22 2010
@@ -22,8 +22,7 @@ import org.apache.commons.math.analysis.
 import org.apache.commons.math.analysis.MultivariateVectorialFunction;
 import org.apache.commons.math.optimization.DifferentiableMultivariateRealOptimizer;
 import org.apache.commons.math.optimization.GoalType;
-import org.apache.commons.math.optimization.OptimizationException;
-import org.apache.commons.math.optimization.RealConvergenceChecker;
+import org.apache.commons.math.optimization.ConvergenceChecker;
 import org.apache.commons.math.optimization.RealPointValuePair;
 
 /**
@@ -37,63 +36,39 @@ import org.apache.commons.math.optimizat
 public abstract class AbstractScalarDifferentiableOptimizer
     extends BaseAbstractScalarOptimizer<DifferentiableMultivariateRealFunction>
     implements DifferentiableMultivariateRealOptimizer {
-
-    /** Convergence checker.
-     * @deprecated in 2.2 (to be removed in 3.0). Please use the accessor
-     * {@link BaseAbstractScalarOptimizer#getConvergenceChecker()} instead.
-     */
-    protected RealConvergenceChecker checker;
     /**
-     * Type of optimization.
-     * @since 2.1
-     * @deprecated in 2.2 (to be removed in 3.0). Please use the accessor
-     * {@link BaseAbstractScalarOptimizer#getGoalType()} instead.
-     */
-    protected GoalType goal;
-    /** Current point set.
-     * @deprecated in 2.2 (to be removed in 3.0).
+     * Objective function gradient.
      */
-    protected double[] point;
-
-    /** Number of gradient evaluations. */
-    private int gradientEvaluations;
-
-    /** Objective function gradient. */
     private MultivariateVectorialFunction gradient;
 
     /**
      * Simple constructor with default settings.
-     * The convergence check is set to a {@link org.apache.commons.math.optimization.SimpleScalarValueChecker},
-     * the allowed number of iterations and evaluations are set to their
-     * default values.
+     * The convergence check is set to a
+     * {@link org.apache.commons.math.optimization.SimpleScalarValueChecker
+     * SimpleScalarValueChecker}.
      */
     protected AbstractScalarDifferentiableOptimizer() {}
     /**
      * @param checker Convergence checker.
-     * @param maxIterations Maximum number of iterations.
-     * @param maxEvaluations Maximum number of evaluations.
+     * @param maxEvaluations Maximum number of function evaluations.
      */
-    protected AbstractScalarDifferentiableOptimizer(RealConvergenceChecker checker,
-                                                    int maxIterations,
+    protected AbstractScalarDifferentiableOptimizer(ConvergenceChecker<RealPointValuePair> checker,
                                                     int maxEvaluations) {
-        super(checker, maxIterations, maxEvaluations);
-        this.checker = checker; // Do not use (deprecated).
-    }
-
-    /** {@inheritDoc} */
-    public int getGradientEvaluations() {
-        return gradientEvaluations;
+        super(checker, maxEvaluations);
     }
 
     /**
      * Compute the gradient vector.
-     * @param evaluationPoint point at which the gradient must be evaluated
-     * @return gradient at the specified point
-     * @exception FunctionEvaluationException if the function gradient
+     *
+     * @param evaluationPoint Point at which the gradient must be evaluated.
+     * @return the gradient at the specified point.
+     * @throws FunctionEvaluationException if the function gradient cannot be
+     * evaluated.
+     * @throws TooManyEvaluationsException if the allowed number of evaluations
+     * is exceeded.
      */
     protected double[] computeObjectiveGradient(final double[] evaluationPoint)
         throws FunctionEvaluationException {
-        ++gradientEvaluations;
         return gradient.value(evaluationPoint);
     }
 
@@ -101,17 +76,10 @@ public abstract class AbstractScalarDiff
     public RealPointValuePair optimize(final DifferentiableMultivariateRealFunction f,
                                        final GoalType goalType,
                                        final double[] startPoint)
-        throws FunctionEvaluationException,
-               OptimizationException {
-        // reset counters
-        gradientEvaluations = 0;
-
-        // store optimization problem characteristics
+        throws FunctionEvaluationException {
+        // Store optimization problem characteristics.
         gradient = f.gradient();
 
-        goal = goalType; // Do not use (deprecated).
-        point = startPoint.clone(); // Do not use (deprecated).
-
         return super.optimize(f, goalType, startPoint);
     }
 }

Modified: commons/proper/math/trunk/src/main/java/org/apache/commons/math/optimization/general/AbstractScalarOptimizer.java
URL: http://svn.apache.org/viewvc/commons/proper/math/trunk/src/main/java/org/apache/commons/math/optimization/general/AbstractScalarOptimizer.java?rev=990792&r1=990791&r2=990792&view=diff
==============================================================================
--- commons/proper/math/trunk/src/main/java/org/apache/commons/math/optimization/general/AbstractScalarOptimizer.java (original)
+++ commons/proper/math/trunk/src/main/java/org/apache/commons/math/optimization/general/AbstractScalarOptimizer.java Mon Aug 30 13:06:22 2010
@@ -19,7 +19,8 @@ package org.apache.commons.math.optimiza
 
 import org.apache.commons.math.analysis.MultivariateRealFunction;
 import org.apache.commons.math.optimization.MultivariateRealOptimizer;
-import org.apache.commons.math.optimization.RealConvergenceChecker;
+import org.apache.commons.math.optimization.ConvergenceChecker;
+import org.apache.commons.math.optimization.RealPointValuePair;
 
 /**
  * Base class for implementing optimizers for multivariate (not necessarily
@@ -33,19 +34,16 @@ public abstract class AbstractScalarOpti
     implements MultivariateRealOptimizer {
     /**
      * Simple constructor with default settings.
-     * The convergence check is set to a {@link org.apache.commons.math.optimization.SimpleScalarValueChecker},
-     * the allowed number of iterations and evaluations are set to their
-     * default values.
+     * The convergence check is set to a
+     * {@link org.apache.commons.math.optimization.SimpleScalarValueChecker}.
      */
     protected AbstractScalarOptimizer() {}
     /**
      * @param checker Convergence checker.
-     * @param maxIterations Maximum number of iterations.
-     * @param maxEvaluations Maximum number of evaluations.
+     * @param maxEvaluations Maximum number of function evaluations.
      */
-    protected AbstractScalarOptimizer(RealConvergenceChecker checker,
-                                      int maxIterations,
+    protected AbstractScalarOptimizer(ConvergenceChecker<RealPointValuePair> checker,
                                       int maxEvaluations) {
-        super(checker, maxIterations, maxEvaluations);
+        super(checker, maxEvaluations);
     }
 }

Modified: commons/proper/math/trunk/src/main/java/org/apache/commons/math/optimization/general/BaseAbstractScalarOptimizer.java
URL: http://svn.apache.org/viewvc/commons/proper/math/trunk/src/main/java/org/apache/commons/math/optimization/general/BaseAbstractScalarOptimizer.java?rev=990792&r1=990791&r2=990792&view=diff
==============================================================================
--- commons/proper/math/trunk/src/main/java/org/apache/commons/math/optimization/general/BaseAbstractScalarOptimizer.java (original)
+++ commons/proper/math/trunk/src/main/java/org/apache/commons/math/optimization/general/BaseAbstractScalarOptimizer.java Mon Aug 30 13:06:22 2010
@@ -18,13 +18,14 @@
 package org.apache.commons.math.optimization.general;
 
 import org.apache.commons.math.FunctionEvaluationException;
-import org.apache.commons.math.MaxEvaluationsExceededException;
-import org.apache.commons.math.MaxIterationsExceededException;
+import org.apache.commons.math.util.Incrementor;
+import org.apache.commons.math.exception.MaxCountExceededException;
+import org.apache.commons.math.exception.TooManyEvaluationsException;
 import org.apache.commons.math.analysis.MultivariateRealFunction;
 import org.apache.commons.math.optimization.BaseMultivariateRealOptimizer;
 import org.apache.commons.math.optimization.GoalType;
 import org.apache.commons.math.optimization.OptimizationException;
-import org.apache.commons.math.optimization.RealConvergenceChecker;
+import org.apache.commons.math.optimization.ConvergenceChecker;
 import org.apache.commons.math.optimization.RealPointValuePair;
 import org.apache.commons.math.optimization.SimpleScalarValueChecker;
 
@@ -37,6 +38,7 @@ import org.apache.commons.math.optimizat
  * A class that implements an optimization algorithm should inherit from
  * {@link AbstractScalarOptimizer} or from
  * {@link AbstractScalarDifferentiableOptimizer}.
+ *
  * @param <T> the type of the objective function to be optimized
  *
  * @version $Revision$ $Date$
@@ -44,136 +46,93 @@ import org.apache.commons.math.optimizat
  */
 public abstract class BaseAbstractScalarOptimizer<T extends MultivariateRealFunction>
     implements BaseMultivariateRealOptimizer<T> {
-    /** Default maximal number of iterations allowed ({@value}). */
-    public static final int DEFAULT_MAX_ITERATIONS = 1000;
-    /** Default maximal number of iterations allowed ({@value}). */
-    public static final int DEFAULT_MAX_EVALUATIONS = 10000;
-
+    /** Evaluations counter. */
+    protected final Incrementor evaluations = new Incrementor();
     /** Convergence checker. */
-    private RealConvergenceChecker checker;
+    private ConvergenceChecker<RealPointValuePair> checker;
     /** Type of optimization. */
     private GoalType goal;
     /** Initial guess. */
     private double[] start;
-    /** Maximal number of iterations allowed. */
-    private int maxIterations;
-    /** Number of iterations already performed. */
-    private int iterations;
-    /** Maximal number of evaluations allowed. */
-    private int maxEvaluations;
-    /** Number of evaluations already performed. */
-    private int evaluations;
     /** Objective function. */
     private MultivariateRealFunction function;
 
     /**
      * Simple constructor with default settings.
-     * The convergence check is set to a {@link SimpleScalarValueChecker},
-     * the allowed number of iterations and evaluations are set to their
-     * default values.
+     * The convergence check is set to a {@link SimpleScalarValueChecker} and
+     * the allowed number of evaluations is set to {@link Integer#MAX_VALUE}.
      */
     protected BaseAbstractScalarOptimizer() {
-        this(new SimpleScalarValueChecker(),
-             DEFAULT_MAX_ITERATIONS,
-             DEFAULT_MAX_EVALUATIONS);
+        this(new SimpleScalarValueChecker(), Integer.MAX_VALUE);
     }
     /**
      * @param checker Convergence checker.
-     * @param maxIterations Maximum number of iterations.
-     * @param maxEvaluations Maximum number of evaluations.
+     * @param maxEvaluations Maximum number of function evaluations.
      */
-    protected BaseAbstractScalarOptimizer(RealConvergenceChecker checker,
-                                          int maxIterations,
+    protected BaseAbstractScalarOptimizer(ConvergenceChecker<RealPointValuePair> checker,
                                           int maxEvaluations) {
         this.checker = checker;
-        this.maxIterations = maxIterations;
-        this.maxEvaluations = maxEvaluations;
-    }
-
-    /** {@inheritDoc} */
-    public void setMaxIterations(int maxIterations) {
-        this.maxIterations = maxIterations;
-    }
-
-    /** {@inheritDoc} */
-    public int getMaxIterations() {
-        return maxIterations;
-    }
-
-    /** {@inheritDoc} */
-    public int getIterations() {
-        return iterations;
+        evaluations.setMaximalCount(maxEvaluations);
     }
 
     /** {@inheritDoc} */
     public void setMaxEvaluations(int maxEvaluations) {
-        this.maxEvaluations = maxEvaluations;
+        evaluations.setMaximalCount(maxEvaluations);
     }
 
     /** {@inheritDoc} */
     public int getMaxEvaluations() {
-        return maxEvaluations;
+        return evaluations.getMaximalCount();
     }
 
     /** {@inheritDoc} */
     public int getEvaluations() {
-        return evaluations;
+        return evaluations.getCount();
     }
 
     /** {@inheritDoc} */
-    public void setConvergenceChecker(RealConvergenceChecker convergenceChecker) {
+    public void setConvergenceChecker(ConvergenceChecker<RealPointValuePair> convergenceChecker) {
         this.checker = convergenceChecker;
     }
 
     /** {@inheritDoc} */
-    public RealConvergenceChecker getConvergenceChecker() {
+    public ConvergenceChecker<RealPointValuePair> getConvergenceChecker() {
         return checker;
     }
 
     /**
-     * Increment the iterations counter by 1.
-     * @throws OptimizationException if the maximal number
-     * of iterations is exceeded
-     */
-    protected void incrementIterationsCounter()
-        throws OptimizationException {
-        if (++iterations > maxIterations) {
-            throw new OptimizationException(new MaxIterationsExceededException(maxIterations));
-        }
-    }
-
-    /**
      * Compute the objective function value.
-     * @param evaluationPoint point at which the objective function must be evaluated
-     * @return objective function value at specified point
-     * @throws FunctionEvaluationException if the function cannot be evaluated
-     * or its dimension doesn't match problem dimension or the maximal number
-     * of iterations is exceeded
+     *
+     * @param point Point at which the objective function must be evaluated.
+     * @return the objective function value at the specified point.
+     * @throws FunctionEvaluationException if the function cannot be evaluated.
+     * @throws TooManyEvaluationsException if the maximal number of evaluations is
+     * exceeded.
      */
-    protected double computeObjectiveValue(double[] evaluationPoint)
+    protected double computeObjectiveValue(double[] point)
         throws FunctionEvaluationException {
-        if (++evaluations > maxEvaluations) {
-            throw new FunctionEvaluationException(new MaxEvaluationsExceededException(maxEvaluations),
-                                                  evaluationPoint);
+        try {
+            evaluations.incrementCount();
+        } catch (MaxCountExceededException e) {
+            throw new TooManyEvaluationsException(e.getMax());
         }
-        return function.value(evaluationPoint);
+        return function.value(point);
     }
 
     /** {@inheritDoc} */
     public RealPointValuePair optimize(T f,
                                        GoalType goalType,
                                        double[] startPoint)
-        throws FunctionEvaluationException, OptimizationException {
-
-        // reset counters
-        iterations = 0;
-        evaluations = 0;
+        throws FunctionEvaluationException {
+        // Reset.
+        evaluations.resetCount();
 
-        // store optimization problem characteristics
+        // Store optimization problem characteristics.
         function = f;
         goal = goalType;
         start = startPoint.clone();
 
+        // Perform computation.
         return doOptimize();
     }
 
@@ -192,13 +151,12 @@ public abstract class BaseAbstractScalar
     }
 
     /**
-     * Perform the bulk of optimization algorithm.
+     * Perform the bulk of the optimization algorithm.
+     *
      * @return the point/value pair giving the optimal value for objective function
      * @throws FunctionEvaluationException if the objective function throws one during
      * the search
-     * @throws OptimizationException if the algorithm failed to converge
-     * @throws IllegalArgumentException if the start point dimension is wrong
      */
     protected abstract RealPointValuePair doOptimize()
-        throws FunctionEvaluationException, OptimizationException;
+        throws FunctionEvaluationException;
 }

Added: commons/proper/math/trunk/src/main/java/org/apache/commons/math/optimization/general/BaseAbstractVectorialOptimizer.java
URL: http://svn.apache.org/viewvc/commons/proper/math/trunk/src/main/java/org/apache/commons/math/optimization/general/BaseAbstractVectorialOptimizer.java?rev=990792&view=auto
==============================================================================
--- commons/proper/math/trunk/src/main/java/org/apache/commons/math/optimization/general/BaseAbstractVectorialOptimizer.java (added)
+++ commons/proper/math/trunk/src/main/java/org/apache/commons/math/optimization/general/BaseAbstractVectorialOptimizer.java Mon Aug 30 13:06:22 2010
@@ -0,0 +1,172 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements.  See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License.  You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package org.apache.commons.math.optimization.general;
+
+import org.apache.commons.math.FunctionEvaluationException;
+import org.apache.commons.math.util.Incrementor;
+import org.apache.commons.math.exception.MaxCountExceededException;
+import org.apache.commons.math.exception.TooManyEvaluationsException;
+import org.apache.commons.math.exception.DimensionMismatchException;
+import org.apache.commons.math.analysis.MultivariateVectorialFunction;
+import org.apache.commons.math.optimization.BaseMultivariateVectorialOptimizer;
+import org.apache.commons.math.optimization.GoalType;
+import org.apache.commons.math.optimization.OptimizationException;
+import org.apache.commons.math.optimization.ConvergenceChecker;
+import org.apache.commons.math.optimization.VectorialPointValuePair;
+import org.apache.commons.math.optimization.SimpleVectorialValueChecker;
+
+/**
+ * Base class for implementing optimizers for multivariate scalar functions.
+ * This base class handles the boiler-plate methods associated to thresholds
+ * settings, iterations and evaluations counting.
+ *
+ * @param <FUNC> the type of the objective function to be optimized
+ *
+ * @version $Revision$ $Date$
+ * @since 3.0
+ */
+public abstract class BaseAbstractVectorialOptimizer<FUNC extends MultivariateVectorialFunction>
+    implements BaseMultivariateVectorialOptimizer<FUNC> {
+    /** Evaluations counter. */
+    protected final Incrementor evaluations = new Incrementor();
+    /** Convergence checker. */
+    private ConvergenceChecker<VectorialPointValuePair> checker;
+    /** Target value for the objective functions at optimum. */
+    private double[] target;
+    /** Weight for the least squares cost computation. */
+    private double[] weight;
+    /** Initial guess. */
+    private double[] start;
+    /** Objective function. */
+    private MultivariateVectorialFunction function;
+
+    /**
+     * Simple constructor with default settings.
+     * The convergence check is set to a {@link SimpleVectorialValueChecker} and
+     * the allowed number of evaluations is set to {@link Integer#MAX_VALUE}.
+     */
+    protected BaseAbstractVectorialOptimizer() {
+        this(new SimpleVectorialValueChecker(),  Integer.MAX_VALUE);
+    }
+    /**
+     * @param checker Convergence checker.
+     * @param maxEvaluations Maximum number of function evaluations.
+     */
+    protected BaseAbstractVectorialOptimizer(ConvergenceChecker<VectorialPointValuePair> checker,
+                                             int maxEvaluations) {
+        this.checker = checker;
+        evaluations.setMaximalCount(maxEvaluations);
+    }
+
+    /** {@inheritDoc} */
+    public void setMaxEvaluations(int maxEvaluations) {
+        evaluations.setMaximalCount(maxEvaluations);
+    }
+
+    /** {@inheritDoc} */
+    public int getMaxEvaluations() {
+        return evaluations.getMaximalCount();
+    }
+
+    /** {@inheritDoc} */
+    public int getEvaluations() {
+        return evaluations.getCount();
+    }
+
+    /** {@inheritDoc} */
+    public void setConvergenceChecker(ConvergenceChecker<VectorialPointValuePair> convergenceChecker) {
+        this.checker = convergenceChecker;
+    }
+
+    /** {@inheritDoc} */
+    public ConvergenceChecker<VectorialPointValuePair> getConvergenceChecker() {
+        return checker;
+    }
+
+    /**
+     * Compute the objective function value.
+     *
+     * @param point Point at which the objective function must be evaluated.
+     * @return the objective function value at the specified point.
+     * @throws FunctionEvaluationException if the function cannot be evaluated.
+     * @throws TooManyEvaluationsException if the maximal number of evaluations is
+     * exceeded.
+     */
+    protected double[] computeObjectiveValue(double[] point)
+        throws FunctionEvaluationException {
+        try {
+            evaluations.incrementCount();
+        } catch (MaxCountExceededException e) {
+            throw new TooManyEvaluationsException(e.getMax());
+        }
+        return function.value(point);
+    }
+
+    /** {@inheritDoc} */
+    public VectorialPointValuePair optimize(FUNC f,
+                                            double[] target, double[] weight,
+                                            double[] startPoint)
+        throws FunctionEvaluationException {
+
+        if (target.length != weight.length) {
+            throw new DimensionMismatchException(target.length, weight.length);
+        }
+
+        // Reset.
+        evaluations.resetCount();
+
+        // Store optimization problem characteristics.
+        function = f;
+        this.target = target.clone();
+        this.weight = weight.clone();
+        start = startPoint.clone();
+
+        // Perform computation.
+        return doOptimize();
+    }
+
+    /**
+     * @return the initial guess.
+     */
+    public double[] getStartPoint() {
+        return start.clone();
+    }
+
+    /**
+     * Perform the bulk of the optimization algorithm.
+     *
+     * @return the point/value pair giving the optimal value for objective function
+     * @throws FunctionEvaluationException if the objective function throws one during
+     * the search
+     */
+    protected abstract VectorialPointValuePair doOptimize()
+        throws FunctionEvaluationException;
+
+    /**
+     * @return a reference to the {@link #target array}.
+     */
+    protected double[] getTargetRef() {
+        return target;
+    }
+    /**
+     * @return a reference to the {@link #weight array}.
+     */
+    protected double[] getWeightRef() {
+        return weight;
+    }
+}

Propchange: commons/proper/math/trunk/src/main/java/org/apache/commons/math/optimization/general/BaseAbstractVectorialOptimizer.java
------------------------------------------------------------------------------
    svn:eol-style = native



Mime
View raw message