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.  *      https://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. /*
  18.  * This is not the original file distributed by the Apache Software Foundation
  19.  * It has been modified by the Hipparchus project
  20.  */

  21. package org.hipparchus.optim.univariate;

  22. import java.util.Arrays;
  23. import java.util.Comparator;

  24. import org.hipparchus.exception.LocalizedCoreFormats;
  25. import org.hipparchus.exception.MathIllegalStateException;
  26. import org.hipparchus.exception.MathIllegalArgumentException;
  27. import org.hipparchus.optim.MaxEval;
  28. import org.hipparchus.optim.OptimizationData;
  29. import org.hipparchus.optim.nonlinear.scalar.GoalType;
  30. import org.hipparchus.random.RandomGenerator;

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

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

  78.         if (starts < 1) {
  79.             throw new MathIllegalArgumentException(LocalizedCoreFormats.NUMBER_TOO_SMALL,
  80.                                                    starts, 1);
  81.         }

  82.         this.optimizer = optimizer;
  83.         this.starts = starts;
  84.         this.generator = generator;
  85.     }

  86.     /** {@inheritDoc} */
  87.     @Override
  88.     public int getEvaluations() {
  89.         return totalEvaluations;
  90.     }

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

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

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

  158.         RuntimeException lastException = null;
  159.         optima = new UnivariatePointValuePair[starts];
  160.         totalEvaluations = 0;

  161.         final int maxEval = getMaxEvaluations();
  162.         final double min = getMin();
  163.         final double max = getMax();
  164.         final double startValue = getStartValue();

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

  183.             totalEvaluations += optimizer.getEvaluations();
  184.         }

  185.         sortPairs(getGoalType());

  186.         if (optima[0] == null) {
  187.             throw lastException; // Cannot be null if starts >= 1.
  188.         }

  189.         // Return the point with the best objective function value.
  190.         return optima[0];
  191.     }

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