BaseMultivariateMultiStartOptimizer.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.MultivariateFunction;
  21. import org.apache.commons.math3.exception.MathIllegalStateException;
  22. import org.apache.commons.math3.exception.NotStrictlyPositiveException;
  23. import org.apache.commons.math3.exception.NullArgumentException;
  24. import org.apache.commons.math3.exception.util.LocalizedFormats;
  25. import org.apache.commons.math3.random.RandomVectorGenerator;

  26. /**
  27.  * Base class for all implementations of a multi-start optimizer.
  28.  *
  29.  * This interface is mainly intended to enforce the internal coherence of
  30.  * Commons-Math. Users of the API are advised to base their code on
  31.  * {@link MultivariateMultiStartOptimizer} or on
  32.  * {@link DifferentiableMultivariateMultiStartOptimizer}.
  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 BaseMultivariateMultiStartOptimizer<FUNC extends MultivariateFunction>
  41.     implements BaseMultivariateOptimizer<FUNC> {
  42.     /** Underlying classical optimizer. */
  43.     private final BaseMultivariateOptimizer<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 PointValuePair[] 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,MultivariateFunction,GoalType,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 BaseMultivariateMultiStartOptimizer(final BaseMultivariateOptimizer<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,MultivariateFunction,GoalType,double[]) optimize}.
  83.      * The optimizer stores all the optima found during a set of
  84.      * restarts. The {@link #optimize(int,MultivariateFunction,GoalType,double[])
  85.      * optimize} method returns the best point only. This method
  86.      * returns all the points found at the end of each starts,
  87.      * including the best one already returned by the {@link
  88.      * #optimize(int,MultivariateFunction,GoalType,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 #optimize(int,MultivariateFunction,GoalType,double[])
  97.      * optimize} method did throw an exception.
  98.      * This also means that if the first element is not {@code null}, it
  99.      * is the best point found across all starts.
  100.      *
  101.      * @return an array containing the optima.
  102.      * @throws MathIllegalStateException if {@link
  103.      * #optimize(int,MultivariateFunction,GoalType,double[]) optimize}
  104.      * has not been called.
  105.      */
  106.     public PointValuePair[] getOptima() {
  107.         if (optima == null) {
  108.             throw new MathIllegalStateException(LocalizedFormats.NO_OPTIMUM_COMPUTED_YET);
  109.         }
  110.         return optima.clone();
  111.     }

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

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

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

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

  134.         // Multi-start loop.
  135.         for (int i = 0; i < starts; ++i) {
  136.             // CHECKSTYLE: stop IllegalCatch
  137.             try {
  138.                 optima[i] = optimizer.optimize(maxEval - totalEvaluations, f, goal,
  139.                                                i == 0 ? startPoint : generator.nextVector());
  140.             } catch (RuntimeException mue) {
  141.                 lastException = mue;
  142.                 optima[i] = null;
  143.             }
  144.             // CHECKSTYLE: resume IllegalCatch

  145.             totalEvaluations += optimizer.getEvaluations();
  146.         }

  147.         sortPairs(goal);

  148.         if (optima[0] == null) {
  149.             throw lastException; // cannot be null if starts >=1
  150.         }

  151.         // Return the found point given the best objective function value.
  152.         return optima[0];
  153.     }

  154.     /**
  155.      * Sort the optima from best to worst, followed by {@code null} elements.
  156.      *
  157.      * @param goal Goal type.
  158.      */
  159.     private void sortPairs(final GoalType goal) {
  160.         Arrays.sort(optima, new Comparator<PointValuePair>() {
  161.                 public int compare(final PointValuePair o1,
  162.                                    final PointValuePair o2) {
  163.                     if (o1 == null) {
  164.                         return (o2 == null) ? 0 : 1;
  165.                     } else if (o2 == null) {
  166.                         return -1;
  167.                     }
  168.                     final double v1 = o1.getValue();
  169.                     final double v2 = o2.getValue();
  170.                     return (goal == GoalType.MINIMIZE) ?
  171.                         Double.compare(v1, v2) : Double.compare(v2, v1);
  172.                 }
  173.             });
  174.     }
  175. }