BaseMultivariateVectorMultiStartOptimizer.java

  1. /*
  2.  * Licensed to the Apache Software Foundation (ASF) under one or more
  3.  * contributor license agreements.  See the NOTICE file distributed with
  4.  * this work for additional information regarding copyright ownership.
  5.  * The ASF licenses this file to You under the Apache License, Version 2.0
  6.  * (the "License"); you may not use this file except in compliance with
  7.  * the License.  You may obtain a copy of the License at
  8.  *
  9.  *      http://www.apache.org/licenses/LICENSE-2.0
  10.  *
  11.  * Unless required by applicable law or agreed to in writing, software
  12.  * distributed under the License is distributed on an "AS IS" BASIS,
  13.  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  14.  * See the License for the specific language governing permissions and
  15.  * limitations under the License.
  16.  */

  17. package org.apache.commons.math3.optimization;

  18. import java.util.Arrays;
  19. import java.util.Comparator;

  20. import org.apache.commons.math3.analysis.MultivariateVectorFunction;
  21. import org.apache.commons.math3.exception.ConvergenceException;
  22. import org.apache.commons.math3.exception.MathIllegalStateException;
  23. import org.apache.commons.math3.exception.NotStrictlyPositiveException;
  24. import org.apache.commons.math3.exception.NullArgumentException;
  25. import org.apache.commons.math3.exception.util.LocalizedFormats;
  26. import org.apache.commons.math3.random.RandomVectorGenerator;

  27. /**
  28.  * Base class for all implementations of a multi-start optimizer.
  29.  *
  30.  * This interface is mainly intended to enforce the internal coherence of
  31.  * Commons-Math. Users of the API are advised to base their code on
  32.  * {@link DifferentiableMultivariateVectorMultiStartOptimizer}.
  33.  *
  34.  * @param <FUNC> Type of the objective function to be optimized.
  35.  *
  36.  * @deprecated As of 3.1 (to be removed in 4.0).
  37.  * @since 3.0
  38.  */
  39. @Deprecated
  40. public class BaseMultivariateVectorMultiStartOptimizer<FUNC extends MultivariateVectorFunction>
  41.     implements BaseMultivariateVectorOptimizer<FUNC> {
  42.     /** Underlying classical optimizer. */
  43.     private final BaseMultivariateVectorOptimizer<FUNC> optimizer;
  44.     /** Maximal number of evaluations allowed. */
  45.     private int maxEvaluations;
  46.     /** Number of evaluations already performed for all starts. */
  47.     private int totalEvaluations;
  48.     /** Number of starts to go. */
  49.     private int starts;
  50.     /** Random generator for multi-start. */
  51.     private RandomVectorGenerator generator;
  52.     /** Found optima. */
  53.     private PointVectorValuePair[] optima;

  54.     /**
  55.      * Create a multi-start optimizer from a single-start optimizer.
  56.      *
  57.      * @param optimizer Single-start optimizer to wrap.
  58.      * @param starts Number of starts to perform. If {@code starts == 1},
  59.      * the {@link #optimize(int,MultivariateVectorFunction,double[],double[],double[])
  60.      * optimize} will return the same solution as {@code optimizer} would.
  61.      * @param generator Random vector generator to use for restarts.
  62.      * @throws NullArgumentException if {@code optimizer} or {@code generator}
  63.      * is {@code null}.
  64.      * @throws NotStrictlyPositiveException if {@code starts < 1}.
  65.      */
  66.     protected BaseMultivariateVectorMultiStartOptimizer(final BaseMultivariateVectorOptimizer<FUNC> optimizer,
  67.                                                            final int starts,
  68.                                                            final RandomVectorGenerator generator) {
  69.         if (optimizer == null ||
  70.             generator == null) {
  71.             throw new NullArgumentException();
  72.         }
  73.         if (starts < 1) {
  74.             throw new NotStrictlyPositiveException(starts);
  75.         }

  76.         this.optimizer = optimizer;
  77.         this.starts = starts;
  78.         this.generator = generator;
  79.     }

  80.     /**
  81.      * Get all the optima found during the last call to {@link
  82.      * #optimize(int,MultivariateVectorFunction,double[],double[],double[]) optimize}.
  83.      * The optimizer stores all the optima found during a set of
  84.      * restarts. The {@link #optimize(int,MultivariateVectorFunction,double[],double[],double[])
  85.      * optimize} method returns the best point only. This method
  86.      * returns all the points found at the end of each starts, including
  87.      * the best one already returned by the {@link
  88.      * #optimize(int,MultivariateVectorFunction,double[],double[],double[]) optimize} method.
  89.      * <br/>
  90.      * The returned array as one element for each start as specified
  91.      * in the constructor. It is ordered with the results from the
  92.      * runs that did converge first, sorted from best to worst
  93.      * objective value (i.e. in ascending order if minimizing and in
  94.      * descending order if maximizing), followed by and null elements
  95.      * corresponding to the runs that did not converge. This means all
  96.      * elements will be null if the {@link
  97.      * #optimize(int,MultivariateVectorFunction,double[],double[],double[]) optimize} method did
  98.      * throw a {@link ConvergenceException}). This also means that if
  99.      * the first element is not {@code null}, it is the best point found
  100.      * across all starts.
  101.      *
  102.      * @return array containing the optima
  103.      * @throws MathIllegalStateException if {@link
  104.      * #optimize(int,MultivariateVectorFunction,double[],double[],double[]) optimize} has not been
  105.      * called.
  106.      */
  107.     public PointVectorValuePair[] getOptima() {
  108.         if (optima == null) {
  109.             throw new MathIllegalStateException(LocalizedFormats.NO_OPTIMUM_COMPUTED_YET);
  110.         }
  111.         return optima.clone();
  112.     }

  113.     /** {@inheritDoc} */
  114.     public int getMaxEvaluations() {
  115.         return maxEvaluations;
  116.     }

  117.     /** {@inheritDoc} */
  118.     public int getEvaluations() {
  119.         return totalEvaluations;
  120.     }

  121.     /** {@inheritDoc} */
  122.     public ConvergenceChecker<PointVectorValuePair> getConvergenceChecker() {
  123.         return optimizer.getConvergenceChecker();
  124.     }

  125.     /**
  126.      * {@inheritDoc}
  127.      */
  128.     public PointVectorValuePair optimize(int maxEval, final FUNC f,
  129.                                             double[] target, double[] weights,
  130.                                             double[] startPoint) {
  131.         maxEvaluations = maxEval;
  132.         RuntimeException lastException = null;
  133.         optima = new PointVectorValuePair[starts];
  134.         totalEvaluations = 0;

  135.         // Multi-start loop.
  136.         for (int i = 0; i < starts; ++i) {

  137.             // CHECKSTYLE: stop IllegalCatch
  138.             try {
  139.                 optima[i] = optimizer.optimize(maxEval - totalEvaluations, f, target, weights,
  140.                                                i == 0 ? startPoint : generator.nextVector());
  141.             } catch (ConvergenceException oe) {
  142.                 optima[i] = null;
  143.             } catch (RuntimeException mue) {
  144.                 lastException = mue;
  145.                 optima[i] = null;
  146.             }
  147.             // CHECKSTYLE: resume IllegalCatch

  148.             totalEvaluations += optimizer.getEvaluations();
  149.         }

  150.         sortPairs(target, weights);

  151.         if (optima[0] == null) {
  152.             throw lastException; // cannot be null if starts >=1
  153.         }

  154.         // Return the found point given the best objective function value.
  155.         return optima[0];
  156.     }

  157.     /**
  158.      * Sort the optima from best to worst, followed by {@code null} elements.
  159.      *
  160.      * @param target Target value for the objective functions at optimum.
  161.      * @param weights Weights for the least-squares cost computation.
  162.      */
  163.     private void sortPairs(final double[] target,
  164.                            final double[] weights) {
  165.         Arrays.sort(optima, new Comparator<PointVectorValuePair>() {
  166.                 public int compare(final PointVectorValuePair o1,
  167.                                    final PointVectorValuePair o2) {
  168.                     if (o1 == null) {
  169.                         return (o2 == null) ? 0 : 1;
  170.                     } else if (o2 == null) {
  171.                         return -1;
  172.                     }
  173.                     return Double.compare(weightedResidual(o1), weightedResidual(o2));
  174.                 }
  175.                 private double weightedResidual(final PointVectorValuePair pv) {
  176.                     final double[] value = pv.getValueRef();
  177.                     double sum = 0;
  178.                     for (int i = 0; i < value.length; ++i) {
  179.                         final double ri = value[i] - target[i];
  180.                         sum += weights[i] * ri * ri;
  181.                     }
  182.                     return sum;
  183.                 }
  184.             });
  185.     }
  186. }