MultiStartUnivariateOptimizer.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.math4.legacy.optim.univariate;

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

  20. import org.apache.commons.math4.legacy.exception.MathIllegalStateException;
  21. import org.apache.commons.math4.legacy.exception.NotStrictlyPositiveException;
  22. import org.apache.commons.math4.legacy.exception.util.LocalizedFormats;
  23. import org.apache.commons.math4.legacy.optim.MaxEval;
  24. import org.apache.commons.math4.legacy.optim.OptimizationData;
  25. import org.apache.commons.math4.legacy.optim.nonlinear.scalar.GoalType;
  26. import org.apache.commons.rng.UniformRandomProvider;

  27. /**
  28.  * Special implementation of the {@link UnivariateOptimizer} interface
  29.  * adding multi-start features to an existing optimizer.
  30.  * <br>
  31.  * This class wraps an optimizer in order to use it several times in
  32.  * turn with different starting points (trying to avoid being trapped
  33.  * in a local extremum when looking for a global one).
  34.  *
  35.  * @since 3.0
  36.  */
  37. public class MultiStartUnivariateOptimizer
  38.     extends UnivariateOptimizer {
  39.     /** Underlying classical optimizer. */
  40.     private final UnivariateOptimizer optimizer;
  41.     /** Number of evaluations already performed for all starts. */
  42.     private int totalEvaluations;
  43.     /** Number of starts to go. */
  44.     private final int starts;
  45.     /** Random generator for multi-start. */
  46.     private final UniformRandomProvider generator;
  47.     /** Found optima. */
  48.     private UnivariatePointValuePair[] optima;
  49.     /** Optimization data. */
  50.     private OptimizationData[] optimData;
  51.     /**
  52.      * Location in {@link #optimData} where the updated maximum
  53.      * number of evaluations will be stored.
  54.      */
  55.     private int maxEvalIndex = -1;
  56.     /**
  57.      * Location in {@link #optimData} where the updated start value
  58.      * will be stored.
  59.      */
  60.     private int searchIntervalIndex = -1;

  61.     /**
  62.      * Create a multi-start optimizer from a single-start optimizer.
  63.      *
  64.      * @param optimizer Single-start optimizer to wrap.
  65.      * @param starts Number of starts to perform. If {@code starts == 1},
  66.      * the {@code optimize} methods will return the same solution as
  67.      * {@code optimizer} would.
  68.      * @param generator Random generator to use for restarts.
  69.      * @throws NotStrictlyPositiveException if {@code starts < 1}.
  70.      */
  71.     public MultiStartUnivariateOptimizer(final UnivariateOptimizer optimizer,
  72.                                          final int starts,
  73.                                          final UniformRandomProvider generator) {
  74.         super(optimizer.getConvergenceChecker());

  75.         if (starts < 1) {
  76.             throw new NotStrictlyPositiveException(starts);
  77.         }

  78.         this.optimizer = optimizer;
  79.         this.starts = starts;
  80.         this.generator = generator;
  81.     }

  82.     /** {@inheritDoc} */
  83.     @Override
  84.     public int getEvaluations() {
  85.         return totalEvaluations;
  86.     }

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

  115.     /**
  116.      * {@inheritDoc}
  117.      *
  118.      * @throws MathIllegalStateException if {@code optData} does not contain an
  119.      * instance of {@link MaxEval} or {@link SearchInterval}.
  120.      */
  121.     @Override
  122.     public UnivariatePointValuePair optimize(OptimizationData... optData) {
  123.         // Store arguments in order to pass them to the internal optimizer.
  124.        optimData = optData;
  125.         // Set up base class and perform computations.
  126.         return super.optimize(optData);
  127.     }

  128.     /** {@inheritDoc} */
  129.     @Override
  130.     protected UnivariatePointValuePair doOptimize() {
  131.         // Remove all instances of "MaxEval" and "SearchInterval" from the
  132.         // array that will be passed to the internal optimizer.
  133.         // The former is to enforce smaller numbers of allowed evaluations
  134.         // (according to how many have been used up already), and the latter
  135.         // to impose a different start value for each start.
  136.         for (int i = 0; i < optimData.length; i++) {
  137.             if (optimData[i] instanceof MaxEval) {
  138.                 optimData[i] = null;
  139.                 maxEvalIndex = i;
  140.                 continue;
  141.             }
  142.             if (optimData[i] instanceof SearchInterval) {
  143.                 optimData[i] = null;
  144.                 searchIntervalIndex = i;
  145.                 continue;
  146.             }
  147.         }
  148.         if (maxEvalIndex == -1) {
  149.             throw new MathIllegalStateException();
  150.         }
  151.         if (searchIntervalIndex == -1) {
  152.             throw new MathIllegalStateException();
  153.         }

  154.         RuntimeException lastException = null;
  155.         optima = new UnivariatePointValuePair[starts];
  156.         totalEvaluations = 0;

  157.         final int maxEval = getMaxEvaluations();
  158.         final double min = getMin();
  159.         final double max = getMax();
  160.         final double startValue = getStartValue();

  161.         // Multi-start loop.
  162.         for (int i = 0; i < starts; i++) {
  163.             // CHECKSTYLE: stop IllegalCatch
  164.             try {
  165.                 // Decrease number of allowed evaluations.
  166.                 optimData[maxEvalIndex] = new MaxEval(maxEval - totalEvaluations);
  167.                 // New start value.
  168.                 final double s = (i == 0) ?
  169.                     startValue :
  170.                     min + generator.nextDouble() * (max - min);
  171.                 optimData[searchIntervalIndex] = new SearchInterval(min, max, s);
  172.                 // Optimize.
  173.                 optima[i] = optimizer.optimize(optimData);
  174.             } catch (RuntimeException mue) {
  175.                 lastException = mue;
  176.                 optima[i] = null;
  177.             }
  178.             // CHECKSTYLE: resume IllegalCatch

  179.             totalEvaluations += optimizer.getEvaluations();
  180.         }

  181.         sortPairs(getGoalType());

  182.         if (optima[0] == null) {
  183.             throw lastException; // Cannot be null if starts >= 1.
  184.         }

  185.         // Return the point with the best objective function value.
  186.         return optima[0];
  187.     }

  188.     /**
  189.      * Sort the optima from best to worst, followed by {@code null} elements.
  190.      *
  191.      * @param goal Goal type.
  192.      */
  193.     private void sortPairs(final GoalType goal) {
  194.         Arrays.sort(optima, new Comparator<UnivariatePointValuePair>() {
  195.                 /** {@inheritDoc} */
  196.                 @Override
  197.                 public int compare(final UnivariatePointValuePair o1,
  198.                                    final UnivariatePointValuePair o2) {
  199.                     if (o1 == null) {
  200.                         return (o2 == null) ? 0 : 1;
  201.                     } else if (o2 == null) {
  202.                         return -1;
  203.                     }
  204.                     final double v1 = o1.getValue();
  205.                     final double v2 = o2.getValue();
  206.                     return (goal == GoalType.MINIMIZE) ?
  207.                         Double.compare(v1, v2) : Double.compare(v2, v1);
  208.                 }
  209.             });
  210.     }
  211. }