BracketFinder.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.math3.optim.univariate;

  18. import org.apache.commons.math3.util.FastMath;
  19. import org.apache.commons.math3.util.Incrementor;
  20. import org.apache.commons.math3.exception.NotStrictlyPositiveException;
  21. import org.apache.commons.math3.exception.TooManyEvaluationsException;
  22. import org.apache.commons.math3.exception.MaxCountExceededException;
  23. import org.apache.commons.math3.analysis.UnivariateFunction;
  24. import org.apache.commons.math3.optim.nonlinear.scalar.GoalType;

  25. /**
  26.  * Provide an interval that brackets a local optimum of a function.
  27.  * This code is based on a Python implementation (from <em>SciPy</em>,
  28.  * module {@code optimize.py} v0.5).
  29.  *
  30.  * @since 2.2
  31.  */
  32. public class BracketFinder {
  33.     /** Tolerance to avoid division by zero. */
  34.     private static final double EPS_MIN = 1e-21;
  35.     /**
  36.      * Golden section.
  37.      */
  38.     private static final double GOLD = 1.618034;
  39.     /**
  40.      * Factor for expanding the interval.
  41.      */
  42.     private final double growLimit;
  43.     /**
  44.      * Counter for function evaluations.
  45.      */
  46.     private final Incrementor evaluations = new Incrementor();
  47.     /**
  48.      * Lower bound of the bracket.
  49.      */
  50.     private double lo;
  51.     /**
  52.      * Higher bound of the bracket.
  53.      */
  54.     private double hi;
  55.     /**
  56.      * Point inside the bracket.
  57.      */
  58.     private double mid;
  59.     /**
  60.      * Function value at {@link #lo}.
  61.      */
  62.     private double fLo;
  63.     /**
  64.      * Function value at {@link #hi}.
  65.      */
  66.     private double fHi;
  67.     /**
  68.      * Function value at {@link #mid}.
  69.      */
  70.     private double fMid;

  71.     /**
  72.      * Constructor with default values {@code 100, 50} (see the
  73.      * {@link #BracketFinder(double,int) other constructor}).
  74.      */
  75.     public BracketFinder() {
  76.         this(100, 50);
  77.     }

  78.     /**
  79.      * Create a bracketing interval finder.
  80.      *
  81.      * @param growLimit Expanding factor.
  82.      * @param maxEvaluations Maximum number of evaluations allowed for finding
  83.      * a bracketing interval.
  84.      */
  85.     public BracketFinder(double growLimit,
  86.                          int maxEvaluations) {
  87.         if (growLimit <= 0) {
  88.             throw new NotStrictlyPositiveException(growLimit);
  89.         }
  90.         if (maxEvaluations <= 0) {
  91.             throw new NotStrictlyPositiveException(maxEvaluations);
  92.         }

  93.         this.growLimit = growLimit;
  94.         evaluations.setMaximalCount(maxEvaluations);
  95.     }

  96.     /**
  97.      * Search new points that bracket a local optimum of the function.
  98.      *
  99.      * @param func Function whose optimum should be bracketed.
  100.      * @param goal {@link GoalType Goal type}.
  101.      * @param xA Initial point.
  102.      * @param xB Initial point.
  103.      * @throws TooManyEvaluationsException if the maximum number of evaluations
  104.      * is exceeded.
  105.      */
  106.     public void search(UnivariateFunction func,
  107.                        GoalType goal,
  108.                        double xA,
  109.                        double xB) {
  110.         evaluations.resetCount();
  111.         final boolean isMinim = goal == GoalType.MINIMIZE;

  112.         double fA = eval(func, xA);
  113.         double fB = eval(func, xB);
  114.         if (isMinim ?
  115.             fA < fB :
  116.             fA > fB) {

  117.             double tmp = xA;
  118.             xA = xB;
  119.             xB = tmp;

  120.             tmp = fA;
  121.             fA = fB;
  122.             fB = tmp;
  123.         }

  124.         double xC = xB + GOLD * (xB - xA);
  125.         double fC = eval(func, xC);

  126.         while (isMinim ? fC < fB : fC > fB) {
  127.             double tmp1 = (xB - xA) * (fB - fC);
  128.             double tmp2 = (xB - xC) * (fB - fA);

  129.             double val = tmp2 - tmp1;
  130.             double denom = FastMath.abs(val) < EPS_MIN ? 2 * EPS_MIN : 2 * val;

  131.             double w = xB - ((xB - xC) * tmp2 - (xB - xA) * tmp1) / denom;
  132.             double wLim = xB + growLimit * (xC - xB);

  133.             double fW;
  134.             if ((w - xC) * (xB - w) > 0) {
  135.                 fW = eval(func, w);
  136.                 if (isMinim ?
  137.                     fW < fC :
  138.                     fW > fC) {
  139.                     xA = xB;
  140.                     xB = w;
  141.                     fA = fB;
  142.                     fB = fW;
  143.                     break;
  144.                 } else if (isMinim ?
  145.                            fW > fB :
  146.                            fW < fB) {
  147.                     xC = w;
  148.                     fC = fW;
  149.                     break;
  150.                 }
  151.                 w = xC + GOLD * (xC - xB);
  152.                 fW = eval(func, w);
  153.             } else if ((w - wLim) * (wLim - xC) >= 0) {
  154.                 w = wLim;
  155.                 fW = eval(func, w);
  156.             } else if ((w - wLim) * (xC - w) > 0) {
  157.                 fW = eval(func, w);
  158.                 if (isMinim ?
  159.                     fW < fC :
  160.                     fW > fC) {
  161.                     xB = xC;
  162.                     xC = w;
  163.                     w = xC + GOLD * (xC - xB);
  164.                     fB = fC;
  165.                     fC =fW;
  166.                     fW = eval(func, w);
  167.                 }
  168.             } else {
  169.                 w = xC + GOLD * (xC - xB);
  170.                 fW = eval(func, w);
  171.             }

  172.             xA = xB;
  173.             fA = fB;
  174.             xB = xC;
  175.             fB = fC;
  176.             xC = w;
  177.             fC = fW;
  178.         }

  179.         lo = xA;
  180.         fLo = fA;
  181.         mid = xB;
  182.         fMid = fB;
  183.         hi = xC;
  184.         fHi = fC;

  185.         if (lo > hi) {
  186.             double tmp = lo;
  187.             lo = hi;
  188.             hi = tmp;

  189.             tmp = fLo;
  190.             fLo = fHi;
  191.             fHi = tmp;
  192.         }
  193.     }

  194.     /**
  195.      * @return the number of evalutations.
  196.      */
  197.     public int getMaxEvaluations() {
  198.         return evaluations.getMaximalCount();
  199.     }

  200.     /**
  201.      * @return the number of evalutations.
  202.      */
  203.     public int getEvaluations() {
  204.         return evaluations.getCount();
  205.     }

  206.     /**
  207.      * @return the lower bound of the bracket.
  208.      * @see #getFLo()
  209.      */
  210.     public double getLo() {
  211.         return lo;
  212.     }

  213.     /**
  214.      * Get function value at {@link #getLo()}.
  215.      * @return function value at {@link #getLo()}
  216.      */
  217.     public double getFLo() {
  218.         return fLo;
  219.     }

  220.     /**
  221.      * @return the higher bound of the bracket.
  222.      * @see #getFHi()
  223.      */
  224.     public double getHi() {
  225.         return hi;
  226.     }

  227.     /**
  228.      * Get function value at {@link #getHi()}.
  229.      * @return function value at {@link #getHi()}
  230.      */
  231.     public double getFHi() {
  232.         return fHi;
  233.     }

  234.     /**
  235.      * @return a point in the middle of the bracket.
  236.      * @see #getFMid()
  237.      */
  238.     public double getMid() {
  239.         return mid;
  240.     }

  241.     /**
  242.      * Get function value at {@link #getMid()}.
  243.      * @return function value at {@link #getMid()}
  244.      */
  245.     public double getFMid() {
  246.         return fMid;
  247.     }

  248.     /**
  249.      * @param f Function.
  250.      * @param x Argument.
  251.      * @return {@code f(x)}
  252.      * @throws TooManyEvaluationsException if the maximal number of evaluations is
  253.      * exceeded.
  254.      */
  255.     private double eval(UnivariateFunction f, double x) {
  256.         try {
  257.             evaluations.incrementCount();
  258.         } catch (MaxCountExceededException e) {
  259.             throw new TooManyEvaluationsException(e.getMax());
  260.         }
  261.         return f.value(x);
  262.     }
  263. }