001/*
002 * Licensed to the Apache Software Foundation (ASF) under one or more
003 * contributor license agreements.  See the NOTICE file distributed with
004 * this work for additional information regarding copyright ownership.
005 * The ASF licenses this file to You under the Apache License, Version 2.0
006 * (the "License"); you may not use this file except in compliance with
007 * the License.  You may obtain a copy of the License at
008 *
009 *      http://www.apache.org/licenses/LICENSE-2.0
010 *
011 * Unless required by applicable law or agreed to in writing, software
012 * distributed under the License is distributed on an "AS IS" BASIS,
013 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
014 * See the License for the specific language governing permissions and
015 * limitations under the License.
016 */
017
018package org.apache.commons.math3.optimization;
019
020import java.util.Arrays;
021import java.util.Comparator;
022
023import org.apache.commons.math3.analysis.MultivariateFunction;
024import org.apache.commons.math3.exception.MathIllegalStateException;
025import org.apache.commons.math3.exception.NotStrictlyPositiveException;
026import org.apache.commons.math3.exception.NullArgumentException;
027import org.apache.commons.math3.exception.util.LocalizedFormats;
028import org.apache.commons.math3.random.RandomVectorGenerator;
029
030/**
031 * Base class for all implementations of a multi-start optimizer.
032 *
033 * This interface is mainly intended to enforce the internal coherence of
034 * Commons-Math. Users of the API are advised to base their code on
035 * {@link MultivariateMultiStartOptimizer} or on
036 * {@link DifferentiableMultivariateMultiStartOptimizer}.
037 *
038 * @param <FUNC> Type of the objective function to be optimized.
039 *
040 * @deprecated As of 3.1 (to be removed in 4.0).
041 * @since 3.0
042 */
043@Deprecated
044public class BaseMultivariateMultiStartOptimizer<FUNC extends MultivariateFunction>
045    implements BaseMultivariateOptimizer<FUNC> {
046    /** Underlying classical optimizer. */
047    private final BaseMultivariateOptimizer<FUNC> optimizer;
048    /** Maximal number of evaluations allowed. */
049    private int maxEvaluations;
050    /** Number of evaluations already performed for all starts. */
051    private int totalEvaluations;
052    /** Number of starts to go. */
053    private int starts;
054    /** Random generator for multi-start. */
055    private RandomVectorGenerator generator;
056    /** Found optima. */
057    private PointValuePair[] optima;
058
059    /**
060     * Create a multi-start optimizer from a single-start optimizer.
061     *
062     * @param optimizer Single-start optimizer to wrap.
063     * @param starts Number of starts to perform. If {@code starts == 1},
064     * the {@link #optimize(int,MultivariateFunction,GoalType,double[])
065     * optimize} will return the same solution as {@code optimizer} would.
066     * @param generator Random vector generator to use for restarts.
067     * @throws NullArgumentException if {@code optimizer} or {@code generator}
068     * is {@code null}.
069     * @throws NotStrictlyPositiveException if {@code starts < 1}.
070     */
071    protected BaseMultivariateMultiStartOptimizer(final BaseMultivariateOptimizer<FUNC> optimizer,
072                                                      final int starts,
073                                                      final RandomVectorGenerator generator) {
074        if (optimizer == null ||
075            generator == null) {
076            throw new NullArgumentException();
077        }
078        if (starts < 1) {
079            throw new NotStrictlyPositiveException(starts);
080        }
081
082        this.optimizer = optimizer;
083        this.starts = starts;
084        this.generator = generator;
085    }
086
087    /**
088     * Get all the optima found during the last call to {@link
089     * #optimize(int,MultivariateFunction,GoalType,double[]) optimize}.
090     * The optimizer stores all the optima found during a set of
091     * restarts. The {@link #optimize(int,MultivariateFunction,GoalType,double[])
092     * optimize} method returns the best point only. This method
093     * returns all the points found at the end of each starts,
094     * including the best one already returned by the {@link
095     * #optimize(int,MultivariateFunction,GoalType,double[]) optimize} method.
096     * <br/>
097     * The returned array as one element for each start as specified
098     * in the constructor. It is ordered with the results from the
099     * runs that did converge first, sorted from best to worst
100     * objective value (i.e in ascending order if minimizing and in
101     * descending order if maximizing), followed by and null elements
102     * corresponding to the runs that did not converge. This means all
103     * elements will be null if the {@link #optimize(int,MultivariateFunction,GoalType,double[])
104     * optimize} method did throw an exception.
105     * This also means that if the first element is not {@code null}, it
106     * is the best point found across all starts.
107     *
108     * @return an array containing the optima.
109     * @throws MathIllegalStateException if {@link
110     * #optimize(int,MultivariateFunction,GoalType,double[]) optimize}
111     * has not been called.
112     */
113    public PointValuePair[] getOptima() {
114        if (optima == null) {
115            throw new MathIllegalStateException(LocalizedFormats.NO_OPTIMUM_COMPUTED_YET);
116        }
117        return optima.clone();
118    }
119
120    /** {@inheritDoc} */
121    public int getMaxEvaluations() {
122        return maxEvaluations;
123    }
124
125    /** {@inheritDoc} */
126    public int getEvaluations() {
127        return totalEvaluations;
128    }
129
130    /** {@inheritDoc} */
131    public ConvergenceChecker<PointValuePair> getConvergenceChecker() {
132        return optimizer.getConvergenceChecker();
133    }
134
135    /**
136     * {@inheritDoc}
137     */
138    public PointValuePair optimize(int maxEval, final FUNC f,
139                                       final GoalType goal,
140                                       double[] startPoint) {
141        maxEvaluations = maxEval;
142        RuntimeException lastException = null;
143        optima = new PointValuePair[starts];
144        totalEvaluations = 0;
145
146        // Multi-start loop.
147        for (int i = 0; i < starts; ++i) {
148            // CHECKSTYLE: stop IllegalCatch
149            try {
150                optima[i] = optimizer.optimize(maxEval - totalEvaluations, f, goal,
151                                               i == 0 ? startPoint : generator.nextVector());
152            } catch (RuntimeException mue) {
153                lastException = mue;
154                optima[i] = null;
155            }
156            // CHECKSTYLE: resume IllegalCatch
157
158            totalEvaluations += optimizer.getEvaluations();
159        }
160
161        sortPairs(goal);
162
163        if (optima[0] == null) {
164            throw lastException; // cannot be null if starts >=1
165        }
166
167        // Return the found point given the best objective function value.
168        return optima[0];
169    }
170
171    /**
172     * Sort the optima from best to worst, followed by {@code null} elements.
173     *
174     * @param goal Goal type.
175     */
176    private void sortPairs(final GoalType goal) {
177        Arrays.sort(optima, new Comparator<PointValuePair>() {
178                /** {@inheritDoc} */
179                public int compare(final PointValuePair o1,
180                                   final PointValuePair o2) {
181                    if (o1 == null) {
182                        return (o2 == null) ? 0 : 1;
183                    } else if (o2 == null) {
184                        return -1;
185                    }
186                    final double v1 = o1.getValue();
187                    final double v2 = o2.getValue();
188                    return (goal == GoalType.MINIMIZE) ?
189                        Double.compare(v1, v2) : Double.compare(v2, v1);
190                }
191            });
192    }
193}