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.direct;
019
020import org.apache.commons.math3.util.Incrementor;
021import org.apache.commons.math3.exception.MaxCountExceededException;
022import org.apache.commons.math3.exception.TooManyEvaluationsException;
023import org.apache.commons.math3.exception.DimensionMismatchException;
024import org.apache.commons.math3.exception.NullArgumentException;
025import org.apache.commons.math3.analysis.MultivariateVectorFunction;
026import org.apache.commons.math3.optimization.OptimizationData;
027import org.apache.commons.math3.optimization.InitialGuess;
028import org.apache.commons.math3.optimization.Target;
029import org.apache.commons.math3.optimization.Weight;
030import org.apache.commons.math3.optimization.BaseMultivariateVectorOptimizer;
031import org.apache.commons.math3.optimization.ConvergenceChecker;
032import org.apache.commons.math3.optimization.PointVectorValuePair;
033import org.apache.commons.math3.optimization.SimpleVectorValueChecker;
034import org.apache.commons.math3.linear.RealMatrix;
035
036/**
037 * Base class for implementing optimizers for multivariate scalar functions.
038 * This base class handles the boiler-plate methods associated to thresholds
039 * settings, iterations and evaluations counting.
040 *
041 * @param <FUNC> the type of the objective function to be optimized
042 *
043 * @version $Id: BaseAbstractMultivariateVectorOptimizer.java 1499808 2013-07-04 17:00:42Z sebb $
044 * @deprecated As of 3.1 (to be removed in 4.0).
045 * @since 3.0
046 */
047@Deprecated
048public abstract class BaseAbstractMultivariateVectorOptimizer<FUNC extends MultivariateVectorFunction>
049    implements BaseMultivariateVectorOptimizer<FUNC> {
050    /** Evaluations counter. */
051    protected final Incrementor evaluations = new Incrementor();
052    /** Convergence checker. */
053    private ConvergenceChecker<PointVectorValuePair> checker;
054    /** Target value for the objective functions at optimum. */
055    private double[] target;
056    /** Weight matrix. */
057    private RealMatrix weightMatrix;
058    /** Weight for the least squares cost computation.
059     * @deprecated
060     */
061    @Deprecated
062    private double[] weight;
063    /** Initial guess. */
064    private double[] start;
065    /** Objective function. */
066    private FUNC function;
067
068    /**
069     * Simple constructor with default settings.
070     * The convergence check is set to a {@link SimpleVectorValueChecker}.
071     * @deprecated See {@link SimpleVectorValueChecker#SimpleVectorValueChecker()}
072     */
073    @Deprecated
074    protected BaseAbstractMultivariateVectorOptimizer() {
075        this(new SimpleVectorValueChecker());
076    }
077    /**
078     * @param checker Convergence checker.
079     */
080    protected BaseAbstractMultivariateVectorOptimizer(ConvergenceChecker<PointVectorValuePair> checker) {
081        this.checker = checker;
082    }
083
084    /** {@inheritDoc} */
085    public int getMaxEvaluations() {
086        return evaluations.getMaximalCount();
087    }
088
089    /** {@inheritDoc} */
090    public int getEvaluations() {
091        return evaluations.getCount();
092    }
093
094    /** {@inheritDoc} */
095    public ConvergenceChecker<PointVectorValuePair> getConvergenceChecker() {
096        return checker;
097    }
098
099    /**
100     * Compute the objective function value.
101     *
102     * @param point Point at which the objective function must be evaluated.
103     * @return the objective function value at the specified point.
104     * @throws TooManyEvaluationsException if the maximal number of evaluations is
105     * exceeded.
106     */
107    protected double[] computeObjectiveValue(double[] point) {
108        try {
109            evaluations.incrementCount();
110        } catch (MaxCountExceededException e) {
111            throw new TooManyEvaluationsException(e.getMax());
112        }
113        return function.value(point);
114    }
115
116    /** {@inheritDoc}
117     *
118     * @deprecated As of 3.1. Please use
119     * {@link #optimize(int,MultivariateVectorFunction,OptimizationData[])}
120     * instead.
121     */
122    @Deprecated
123    public PointVectorValuePair optimize(int maxEval, FUNC f, double[] t, double[] w,
124                                         double[] startPoint) {
125        return optimizeInternal(maxEval, f, t, w, startPoint);
126    }
127
128    /**
129     * Optimize an objective function.
130     *
131     * @param maxEval Allowed number of evaluations of the objective function.
132     * @param f Objective function.
133     * @param optData Optimization data. The following data will be looked for:
134     * <ul>
135     *  <li>{@link Target}</li>
136     *  <li>{@link Weight}</li>
137     *  <li>{@link InitialGuess}</li>
138     * </ul>
139     * @return the point/value pair giving the optimal value of the objective
140     * function.
141     * @throws TooManyEvaluationsException if the maximal number of
142     * evaluations is exceeded.
143     * @throws DimensionMismatchException if the initial guess, target, and weight
144     * arguments have inconsistent dimensions.
145     *
146     * @since 3.1
147     */
148    protected PointVectorValuePair optimize(int maxEval,
149                                            FUNC f,
150                                            OptimizationData... optData)
151        throws TooManyEvaluationsException,
152               DimensionMismatchException {
153        return optimizeInternal(maxEval, f, optData);
154    }
155
156    /**
157     * Optimize an objective function.
158     * Optimization is considered to be a weighted least-squares minimization.
159     * The cost function to be minimized is
160     * <code>&sum;weight<sub>i</sub>(objective<sub>i</sub> - target<sub>i</sub>)<sup>2</sup></code>
161     *
162     * @param f Objective function.
163     * @param t Target value for the objective functions at optimum.
164     * @param w Weights for the least squares cost computation.
165     * @param startPoint Start point for optimization.
166     * @return the point/value pair giving the optimal value for objective
167     * function.
168     * @param maxEval Maximum number of function evaluations.
169     * @throws org.apache.commons.math3.exception.DimensionMismatchException
170     * if the start point dimension is wrong.
171     * @throws org.apache.commons.math3.exception.TooManyEvaluationsException
172     * if the maximal number of evaluations is exceeded.
173     * @throws org.apache.commons.math3.exception.NullArgumentException if
174     * any argument is {@code null}.
175     * @deprecated As of 3.1. Please use
176     * {@link #optimizeInternal(int,MultivariateVectorFunction,OptimizationData[])}
177     * instead.
178     */
179    @Deprecated
180    protected PointVectorValuePair optimizeInternal(final int maxEval, final FUNC f,
181                                                    final double[] t, final double[] w,
182                                                    final double[] startPoint) {
183        // Checks.
184        if (f == null) {
185            throw new NullArgumentException();
186        }
187        if (t == null) {
188            throw new NullArgumentException();
189        }
190        if (w == null) {
191            throw new NullArgumentException();
192        }
193        if (startPoint == null) {
194            throw new NullArgumentException();
195        }
196        if (t.length != w.length) {
197            throw new DimensionMismatchException(t.length, w.length);
198        }
199
200        return optimizeInternal(maxEval, f,
201                                new Target(t),
202                                new Weight(w),
203                                new InitialGuess(startPoint));
204    }
205
206    /**
207     * Optimize an objective function.
208     *
209     * @param maxEval Allowed number of evaluations of the objective function.
210     * @param f Objective function.
211     * @param optData Optimization data. The following data will be looked for:
212     * <ul>
213     *  <li>{@link Target}</li>
214     *  <li>{@link Weight}</li>
215     *  <li>{@link InitialGuess}</li>
216     * </ul>
217     * @return the point/value pair giving the optimal value of the objective
218     * function.
219     * @throws TooManyEvaluationsException if the maximal number of
220     * evaluations is exceeded.
221     * @throws DimensionMismatchException if the initial guess, target, and weight
222     * arguments have inconsistent dimensions.
223     *
224     * @since 3.1
225     */
226    protected PointVectorValuePair optimizeInternal(int maxEval,
227                                                    FUNC f,
228                                                    OptimizationData... optData)
229        throws TooManyEvaluationsException,
230               DimensionMismatchException {
231        // Set internal state.
232        evaluations.setMaximalCount(maxEval);
233        evaluations.resetCount();
234        function = f;
235        // Retrieve other settings.
236        parseOptimizationData(optData);
237        // Check input consistency.
238        checkParameters();
239        // Allow subclasses to reset their own internal state.
240        setUp();
241        // Perform computation.
242        return doOptimize();
243    }
244
245    /**
246     * Gets the initial values of the optimized parameters.
247     *
248     * @return the initial guess.
249     */
250    public double[] getStartPoint() {
251        return start.clone();
252    }
253
254    /**
255     * Gets the weight matrix of the observations.
256     *
257     * @return the weight matrix.
258     * @since 3.1
259     */
260    public RealMatrix getWeight() {
261        return weightMatrix.copy();
262    }
263    /**
264     * Gets the observed values to be matched by the objective vector
265     * function.
266     *
267     * @return the target values.
268     * @since 3.1
269     */
270    public double[] getTarget() {
271        return target.clone();
272    }
273
274    /**
275     * Gets the objective vector function.
276     * Note that this access bypasses the evaluation counter.
277     *
278     * @return the objective vector function.
279     * @since 3.1
280     */
281    protected FUNC getObjectiveFunction() {
282        return function;
283    }
284
285    /**
286     * Perform the bulk of the optimization algorithm.
287     *
288     * @return the point/value pair giving the optimal value for the
289     * objective function.
290     */
291    protected abstract PointVectorValuePair doOptimize();
292
293    /**
294     * @return a reference to the {@link #target array}.
295     * @deprecated As of 3.1.
296     */
297    @Deprecated
298    protected double[] getTargetRef() {
299        return target;
300    }
301    /**
302     * @return a reference to the {@link #weight array}.
303     * @deprecated As of 3.1.
304     */
305    @Deprecated
306    protected double[] getWeightRef() {
307        return weight;
308    }
309
310    /**
311     * Method which a subclass <em>must</em> override whenever its internal
312     * state depend on the {@link OptimizationData input} parsed by this base
313     * class.
314     * It will be called after the parsing step performed in the
315     * {@link #optimize(int,MultivariateVectorFunction,OptimizationData[])
316     * optimize} method and just before {@link #doOptimize()}.
317     *
318     * @since 3.1
319     */
320    protected void setUp() {
321        // XXX Temporary code until the new internal data is used everywhere.
322        final int dim = target.length;
323        weight = new double[dim];
324        for (int i = 0; i < dim; i++) {
325            weight[i] = weightMatrix.getEntry(i, i);
326        }
327    }
328
329    /**
330     * Scans the list of (required and optional) optimization data that
331     * characterize the problem.
332     *
333     * @param optData Optimization data. The following data will be looked for:
334     * <ul>
335     *  <li>{@link Target}</li>
336     *  <li>{@link Weight}</li>
337     *  <li>{@link InitialGuess}</li>
338     * </ul>
339     */
340    private void parseOptimizationData(OptimizationData... optData) {
341        // The existing values (as set by the previous call) are reused if
342        // not provided in the argument list.
343        for (OptimizationData data : optData) {
344            if (data instanceof Target) {
345                target = ((Target) data).getTarget();
346                continue;
347            }
348            if (data instanceof Weight) {
349                weightMatrix = ((Weight) data).getWeight();
350                continue;
351            }
352            if (data instanceof InitialGuess) {
353                start = ((InitialGuess) data).getInitialGuess();
354                continue;
355            }
356        }
357    }
358
359    /**
360     * Check parameters consistency.
361     *
362     * @throws DimensionMismatchException if {@link #target} and
363     * {@link #weightMatrix} have inconsistent dimensions.
364     */
365    private void checkParameters() {
366        if (target.length != weightMatrix.getColumnDimension()) {
367            throw new DimensionMismatchException(target.length,
368                                                 weightMatrix.getColumnDimension());
369        }
370    }
371}