BaseAbstractUnivariateSolver.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.analysis.solvers;

  22. import org.hipparchus.analysis.UnivariateFunction;
  23. import org.hipparchus.exception.MathIllegalArgumentException;
  24. import org.hipparchus.exception.MathIllegalStateException;
  25. import org.hipparchus.exception.NullArgumentException;
  26. import org.hipparchus.util.Incrementor;
  27. import org.hipparchus.util.MathUtils;

  28. /**
  29.  * Provide a default implementation for several functions useful to generic
  30.  * solvers.
  31.  * The default values for relative and function tolerances are 1e-14
  32.  * and 1e-15, respectively. It is however highly recommended to not
  33.  * rely on the default, but rather carefully consider values that match
  34.  * user's expectations, as well as the specifics of each implementation.
  35.  *
  36.  * @param <F> Type of function to solve.
  37.  *
  38.  */
  39. public abstract class BaseAbstractUnivariateSolver<F extends UnivariateFunction>
  40.     implements BaseUnivariateSolver<F> {
  41.     /** Default relative accuracy. */
  42.     private static final double DEFAULT_RELATIVE_ACCURACY = 1e-14;
  43.     /** Default function value accuracy. */
  44.     private static final double DEFAULT_FUNCTION_VALUE_ACCURACY = 1e-15;
  45.     /** Function value accuracy. */
  46.     private final double functionValueAccuracy;
  47.     /** Absolute accuracy. */
  48.     private final double absoluteAccuracy;
  49.     /** Relative accuracy. */
  50.     private final double relativeAccuracy;
  51.     /** Evaluations counter. */
  52.     private Incrementor evaluations;
  53.     /** Lower end of search interval. */
  54.     private double searchMin;
  55.     /** Higher end of search interval. */
  56.     private double searchMax;
  57.     /** Initial guess. */
  58.     private double searchStart;
  59.     /** Function to solve. */
  60.     private F function;

  61.     /**
  62.      * Construct a solver with given absolute accuracy.
  63.      *
  64.      * @param absoluteAccuracy Maximum absolute error.
  65.      */
  66.     protected BaseAbstractUnivariateSolver(final double absoluteAccuracy) {
  67.         this(DEFAULT_RELATIVE_ACCURACY,
  68.              absoluteAccuracy,
  69.              DEFAULT_FUNCTION_VALUE_ACCURACY);
  70.     }

  71.     /**
  72.      * Construct a solver with given accuracies.
  73.      *
  74.      * @param relativeAccuracy Maximum relative error.
  75.      * @param absoluteAccuracy Maximum absolute error.
  76.      */
  77.     protected BaseAbstractUnivariateSolver(final double relativeAccuracy,
  78.                                            final double absoluteAccuracy) {
  79.         this(relativeAccuracy,
  80.              absoluteAccuracy,
  81.              DEFAULT_FUNCTION_VALUE_ACCURACY);
  82.     }

  83.     /**
  84.      * Construct a solver with given accuracies.
  85.      *
  86.      * @param relativeAccuracy Maximum relative error.
  87.      * @param absoluteAccuracy Maximum absolute error.
  88.      * @param functionValueAccuracy Maximum function value error.
  89.      */
  90.     protected BaseAbstractUnivariateSolver(final double relativeAccuracy,
  91.                                            final double absoluteAccuracy,
  92.                                            final double functionValueAccuracy) {
  93.         this.absoluteAccuracy      = absoluteAccuracy;
  94.         this.relativeAccuracy      = relativeAccuracy;
  95.         this.functionValueAccuracy = functionValueAccuracy;
  96.         this.evaluations           = new Incrementor();
  97.     }

  98.     /** {@inheritDoc} */
  99.     @Override
  100.     public int getEvaluations() {
  101.         return evaluations.getCount();
  102.     }
  103.     /** Get lower end of the search interval.
  104.      * @return the lower end of the search interval
  105.      */
  106.     public double getMin() {
  107.         return searchMin;
  108.     }
  109.     /** Get higher end of the search interval.
  110.      * @return the higher end of the search interval
  111.      */
  112.     public double getMax() {
  113.         return searchMax;
  114.     }
  115.     /** Get initial guess.
  116.      * @return the initial guess
  117.      */
  118.     public double getStartValue() {
  119.         return searchStart;
  120.     }
  121.     /**
  122.      * {@inheritDoc}
  123.      */
  124.     @Override
  125.     public double getAbsoluteAccuracy() {
  126.         return absoluteAccuracy;
  127.     }
  128.     /**
  129.      * {@inheritDoc}
  130.      */
  131.     @Override
  132.     public double getRelativeAccuracy() {
  133.         return relativeAccuracy;
  134.     }
  135.     /**
  136.      * {@inheritDoc}
  137.      */
  138.     @Override
  139.     public double getFunctionValueAccuracy() {
  140.         return functionValueAccuracy;
  141.     }

  142.     /**
  143.      * Compute the objective function value.
  144.      *
  145.      * @param point Point at which the objective function must be evaluated.
  146.      * @return the objective function value at specified point.
  147.      * @throws MathIllegalStateException if the maximal number of evaluations
  148.      * is exceeded.
  149.      */
  150.     protected double computeObjectiveValue(double point)
  151.         throws MathIllegalStateException {
  152.         incrementEvaluationCount();
  153.         return function.value(point);
  154.     }

  155.     /**
  156.      * Prepare for computation.
  157.      * Subclasses must call this method if they override any of the
  158.      * {@code solve} methods.
  159.      *
  160.      * @param f Function to solve.
  161.      * @param min Lower bound for the interval.
  162.      * @param max Upper bound for the interval.
  163.      * @param startValue Start value to use.
  164.      * @param maxEval Maximum number of evaluations.
  165.      * @exception NullArgumentException if f is null
  166.      */
  167.     protected void setup(int maxEval,
  168.                          F f,
  169.                          double min, double max,
  170.                          double startValue)
  171.         throws NullArgumentException {
  172.         // Checks.
  173.         MathUtils.checkNotNull(f);

  174.         // Reset.
  175.         searchMin = min;
  176.         searchMax = max;
  177.         searchStart = startValue;
  178.         function = f;
  179.         evaluations = evaluations.withMaximalCount(maxEval);
  180.     }

  181.     /** {@inheritDoc} */
  182.     @Override
  183.     public double solve(int maxEval, F f, double min, double max, double startValue)
  184.         throws MathIllegalArgumentException, MathIllegalStateException {
  185.         // Initialization.
  186.         setup(maxEval, f, min, max, startValue);

  187.         // Perform computation.
  188.         return doSolve();
  189.     }

  190.     /** {@inheritDoc} */
  191.     @Override
  192.     public double solve(int maxEval, F f, double min, double max) {
  193.         return solve(maxEval, f, min, max, min + 0.5 * (max - min));
  194.     }

  195.     /** {@inheritDoc} */
  196.     @Override
  197.     public double solve(int maxEval, F f, double startValue)
  198.         throws MathIllegalArgumentException, MathIllegalStateException {
  199.         return solve(maxEval, f, Double.NaN, Double.NaN, startValue);
  200.     }

  201.     /**
  202.      * Method for implementing actual optimization algorithms in derived
  203.      * classes.
  204.      *
  205.      * @return the root.
  206.      * @throws MathIllegalStateException if the maximal number of evaluations
  207.      * is exceeded.
  208.      * @throws MathIllegalArgumentException if the initial search interval does not bracket
  209.      * a root and the solver requires it.
  210.      */
  211.     protected abstract double doSolve()
  212.         throws MathIllegalArgumentException, MathIllegalStateException;

  213.     /**
  214.      * Check whether the function takes opposite signs at the endpoints.
  215.      *
  216.      * @param lower Lower endpoint.
  217.      * @param upper Upper endpoint.
  218.      * @return {@code true} if the function values have opposite signs at the
  219.      * given points.
  220.      */
  221.     protected boolean isBracketing(final double lower,
  222.                                    final double upper) {
  223.         return UnivariateSolverUtils.isBracketing(function, lower, upper);
  224.     }

  225.     /**
  226.      * Check whether the arguments form a (strictly) increasing sequence.
  227.      *
  228.      * @param start First number.
  229.      * @param mid Second number.
  230.      * @param end Third number.
  231.      * @return {@code true} if the arguments form an increasing sequence.
  232.      */
  233.     protected boolean isSequence(final double start,
  234.                                  final double mid,
  235.                                  final double end) {
  236.         return UnivariateSolverUtils.isSequence(start, mid, end);
  237.     }

  238.     /**
  239.      * Check that the endpoints specify an interval.
  240.      *
  241.      * @param lower Lower endpoint.
  242.      * @param upper Upper endpoint.
  243.      * @throws MathIllegalArgumentException if {@code lower >= upper}.
  244.      */
  245.     protected void verifyInterval(final double lower,
  246.                                   final double upper)
  247.         throws MathIllegalArgumentException {
  248.         UnivariateSolverUtils.verifyInterval(lower, upper);
  249.     }

  250.     /**
  251.      * Check that {@code lower < initial < upper}.
  252.      *
  253.      * @param lower Lower endpoint.
  254.      * @param initial Initial value.
  255.      * @param upper Upper endpoint.
  256.      * @throws MathIllegalArgumentException if {@code lower >= initial} or
  257.      * {@code initial >= upper}.
  258.      */
  259.     protected void verifySequence(final double lower,
  260.                                   final double initial,
  261.                                   final double upper)
  262.         throws MathIllegalArgumentException {
  263.         UnivariateSolverUtils.verifySequence(lower, initial, upper);
  264.     }

  265.     /**
  266.      * Check that the endpoints specify an interval and the function takes
  267.      * opposite signs at the endpoints.
  268.      *
  269.      * @param lower Lower endpoint.
  270.      * @param upper Upper endpoint.
  271.      * @throws NullArgumentException if the function has not been set.
  272.      * @throws MathIllegalArgumentException if the function has the same sign at
  273.      * the endpoints.
  274.      */
  275.     protected void verifyBracketing(final double lower,
  276.                                     final double upper)
  277.         throws MathIllegalArgumentException, NullArgumentException {
  278.         UnivariateSolverUtils.verifyBracketing(function, lower, upper);
  279.     }

  280.     /**
  281.      * Increment the evaluation count by one.
  282.      * Method {@link #computeObjectiveValue(double)} calls this method internally.
  283.      * It is provided for subclasses that do not exclusively use
  284.      * {@code computeObjectiveValue} to solve the function.
  285.      * See e.g. {@link AbstractUnivariateDifferentiableSolver}.
  286.      *
  287.      * @throws MathIllegalStateException when the allowed number of function
  288.      * evaluations has been exhausted.
  289.      */
  290.     protected void incrementEvaluationCount()
  291.         throws MathIllegalStateException {
  292.         evaluations.increment();
  293.     }
  294. }