BOBYQAOptimizer.java

  1. // CHECKSTYLE: stop all
  2. /*
  3.  * Licensed to the Apache Software Foundation (ASF) under one or more
  4.  * contributor license agreements.  See the NOTICE file distributed with
  5.  * this work for additional information regarding copyright ownership.
  6.  * The ASF licenses this file to You under the Apache License, Version 2.0
  7.  * (the "License"); you may not use this file except in compliance with
  8.  * the License.  You may obtain a copy of the License at
  9.  *
  10.  *      http://www.apache.org/licenses/LICENSE-2.0
  11.  *
  12.  * Unless required by applicable law or agreed to in writing, software
  13.  * distributed under the License is distributed on an "AS IS" BASIS,
  14.  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  15.  * See the License for the specific language governing permissions and
  16.  * limitations under the License.
  17.  */

  18. package org.apache.commons.math3.optimization.direct;

  19. import org.apache.commons.math3.analysis.MultivariateFunction;
  20. import org.apache.commons.math3.exception.MathIllegalStateException;
  21. import org.apache.commons.math3.exception.NumberIsTooSmallException;
  22. import org.apache.commons.math3.exception.OutOfRangeException;
  23. import org.apache.commons.math3.exception.util.LocalizedFormats;
  24. import org.apache.commons.math3.linear.Array2DRowRealMatrix;
  25. import org.apache.commons.math3.linear.ArrayRealVector;
  26. import org.apache.commons.math3.linear.RealVector;
  27. import org.apache.commons.math3.optimization.GoalType;
  28. import org.apache.commons.math3.optimization.PointValuePair;
  29. import org.apache.commons.math3.optimization.MultivariateOptimizer;
  30. import org.apache.commons.math3.util.FastMath;

  31. /**
  32.  * Powell's BOBYQA algorithm. This implementation is translated and
  33.  * adapted from the Fortran version available
  34.  * <a href="http://plato.asu.edu/ftp/other_software/bobyqa.zip">here</a>.
  35.  * See <a href="http://www.optimization-online.org/DB_HTML/2010/05/2616.html">
  36.  * this paper</a> for an introduction.
  37.  * <br/>
  38.  * BOBYQA is particularly well suited for high dimensional problems
  39.  * where derivatives are not available. In most cases it outperforms the
  40.  * {@link PowellOptimizer} significantly. Stochastic algorithms like
  41.  * {@link CMAESOptimizer} succeed more often than BOBYQA, but are more
  42.  * expensive. BOBYQA could also be considered as a replacement of any
  43.  * derivative-based optimizer when the derivatives are approximated by
  44.  * finite differences.
  45.  *
  46.  * @deprecated As of 3.1 (to be removed in 4.0).
  47.  * @since 3.0
  48.  */
  49. @Deprecated
  50. public class BOBYQAOptimizer
  51.     extends BaseAbstractMultivariateSimpleBoundsOptimizer<MultivariateFunction>
  52.     implements MultivariateOptimizer {
  53.     /** Minimum dimension of the problem: {@value} */
  54.     public static final int MINIMUM_PROBLEM_DIMENSION = 2;
  55.     /** Default value for {@link #initialTrustRegionRadius}: {@value} . */
  56.     public static final double DEFAULT_INITIAL_RADIUS = 10.0;
  57.     /** Default value for {@link #stoppingTrustRegionRadius}: {@value} . */
  58.     public static final double DEFAULT_STOPPING_RADIUS = 1E-8;

  59.     private static final double ZERO = 0d;
  60.     private static final double ONE = 1d;
  61.     private static final double TWO = 2d;
  62.     private static final double TEN = 10d;
  63.     private static final double SIXTEEN = 16d;
  64.     private static final double TWO_HUNDRED_FIFTY = 250d;
  65.     private static final double MINUS_ONE = -ONE;
  66.     private static final double HALF = ONE / 2;
  67.     private static final double ONE_OVER_FOUR = ONE / 4;
  68.     private static final double ONE_OVER_EIGHT = ONE / 8;
  69.     private static final double ONE_OVER_TEN = ONE / 10;
  70.     private static final double ONE_OVER_A_THOUSAND = ONE / 1000;

  71.     /**
  72.      * numberOfInterpolationPoints XXX
  73.      */
  74.     private final int numberOfInterpolationPoints;
  75.     /**
  76.      * initialTrustRegionRadius XXX
  77.      */
  78.     private double initialTrustRegionRadius;
  79.     /**
  80.      * stoppingTrustRegionRadius XXX
  81.      */
  82.     private final double stoppingTrustRegionRadius;
  83.     /** Goal type (minimize or maximize). */
  84.     private boolean isMinimize;
  85.     /**
  86.      * Current best values for the variables to be optimized.
  87.      * The vector will be changed in-place to contain the values of the least
  88.      * calculated objective function values.
  89.      */
  90.     private ArrayRealVector currentBest;
  91.     /** Differences between the upper and lower bounds. */
  92.     private double[] boundDifference;
  93.     /**
  94.      * Index of the interpolation point at the trust region center.
  95.      */
  96.     private int trustRegionCenterInterpolationPointIndex;
  97.     /**
  98.      * Last <em>n</em> columns of matrix H (where <em>n</em> is the dimension
  99.      * of the problem).
  100.      * XXX "bmat" in the original code.
  101.      */
  102.     private Array2DRowRealMatrix bMatrix;
  103.     /**
  104.      * Factorization of the leading <em>npt</em> square submatrix of H, this
  105.      * factorization being Z Z<sup>T</sup>, which provides both the correct
  106.      * rank and positive semi-definiteness.
  107.      * XXX "zmat" in the original code.
  108.      */
  109.     private Array2DRowRealMatrix zMatrix;
  110.     /**
  111.      * Coordinates of the interpolation points relative to {@link #originShift}.
  112.      * XXX "xpt" in the original code.
  113.      */
  114.     private Array2DRowRealMatrix interpolationPoints;
  115.     /**
  116.      * Shift of origin that should reduce the contributions from rounding
  117.      * errors to values of the model and Lagrange functions.
  118.      * XXX "xbase" in the original code.
  119.      */
  120.     private ArrayRealVector originShift;
  121.     /**
  122.      * Values of the objective function at the interpolation points.
  123.      * XXX "fval" in the original code.
  124.      */
  125.     private ArrayRealVector fAtInterpolationPoints;
  126.     /**
  127.      * Displacement from {@link #originShift} of the trust region center.
  128.      * XXX "xopt" in the original code.
  129.      */
  130.     private ArrayRealVector trustRegionCenterOffset;
  131.     /**
  132.      * Gradient of the quadratic model at {@link #originShift} +
  133.      * {@link #trustRegionCenterOffset}.
  134.      * XXX "gopt" in the original code.
  135.      */
  136.     private ArrayRealVector gradientAtTrustRegionCenter;
  137.     /**
  138.      * Differences {@link #getLowerBound()} - {@link #originShift}.
  139.      * All the components of every {@link #trustRegionCenterOffset} are going
  140.      * to satisfy the bounds<br/>
  141.      * {@link #getLowerBound() lowerBound}<sub>i</sub> &le;
  142.      * {@link #trustRegionCenterOffset}<sub>i</sub>,<br/>
  143.      * with appropriate equalities when {@link #trustRegionCenterOffset} is
  144.      * on a constraint boundary.
  145.      * XXX "sl" in the original code.
  146.      */
  147.     private ArrayRealVector lowerDifference;
  148.     /**
  149.      * Differences {@link #getUpperBound()} - {@link #originShift}
  150.      * All the components of every {@link #trustRegionCenterOffset} are going
  151.      * to satisfy the bounds<br/>
  152.      *  {@link #trustRegionCenterOffset}<sub>i</sub> &le;
  153.      *  {@link #getUpperBound() upperBound}<sub>i</sub>,<br/>
  154.      * with appropriate equalities when {@link #trustRegionCenterOffset} is
  155.      * on a constraint boundary.
  156.      * XXX "su" in the original code.
  157.      */
  158.     private ArrayRealVector upperDifference;
  159.     /**
  160.      * Parameters of the implicit second derivatives of the quadratic model.
  161.      * XXX "pq" in the original code.
  162.      */
  163.     private ArrayRealVector modelSecondDerivativesParameters;
  164.     /**
  165.      * Point chosen by function {@link #trsbox(double,ArrayRealVector,
  166.      * ArrayRealVector, ArrayRealVector,ArrayRealVector,ArrayRealVector) trsbox}
  167.      * or {@link #altmov(int,double) altmov}.
  168.      * Usually {@link #originShift} + {@link #newPoint} is the vector of
  169.      * variables for the next evaluation of the objective function.
  170.      * It also satisfies the constraints indicated in {@link #lowerDifference}
  171.      * and {@link #upperDifference}.
  172.      * XXX "xnew" in the original code.
  173.      */
  174.     private ArrayRealVector newPoint;
  175.     /**
  176.      * Alternative to {@link #newPoint}, chosen by
  177.      * {@link #altmov(int,double) altmov}.
  178.      * It may replace {@link #newPoint} in order to increase the denominator
  179.      * in the {@link #update(double, double, int) updating procedure}.
  180.      * XXX "xalt" in the original code.
  181.      */
  182.     private ArrayRealVector alternativeNewPoint;
  183.     /**
  184.      * Trial step from {@link #trustRegionCenterOffset} which is usually
  185.      * {@link #newPoint} - {@link #trustRegionCenterOffset}.
  186.      * XXX "d__" in the original code.
  187.      */
  188.     private ArrayRealVector trialStepPoint;
  189.     /**
  190.      * Values of the Lagrange functions at a new point.
  191.      * XXX "vlag" in the original code.
  192.      */
  193.     private ArrayRealVector lagrangeValuesAtNewPoint;
  194.     /**
  195.      * Explicit second derivatives of the quadratic model.
  196.      * XXX "hq" in the original code.
  197.      */
  198.     private ArrayRealVector modelSecondDerivativesValues;

  199.     /**
  200.      * @param numberOfInterpolationPoints Number of interpolation conditions.
  201.      * For a problem of dimension {@code n}, its value must be in the interval
  202.      * {@code [n+2, (n+1)(n+2)/2]}.
  203.      * Choices that exceed {@code 2n+1} are not recommended.
  204.      */
  205.     public BOBYQAOptimizer(int numberOfInterpolationPoints) {
  206.         this(numberOfInterpolationPoints,
  207.              DEFAULT_INITIAL_RADIUS,
  208.              DEFAULT_STOPPING_RADIUS);
  209.     }

  210.     /**
  211.      * @param numberOfInterpolationPoints Number of interpolation conditions.
  212.      * For a problem of dimension {@code n}, its value must be in the interval
  213.      * {@code [n+2, (n+1)(n+2)/2]}.
  214.      * Choices that exceed {@code 2n+1} are not recommended.
  215.      * @param initialTrustRegionRadius Initial trust region radius.
  216.      * @param stoppingTrustRegionRadius Stopping trust region radius.
  217.      */
  218.     public BOBYQAOptimizer(int numberOfInterpolationPoints,
  219.                            double initialTrustRegionRadius,
  220.                            double stoppingTrustRegionRadius) {
  221.         super(null); // No custom convergence criterion.
  222.         this.numberOfInterpolationPoints = numberOfInterpolationPoints;
  223.         this.initialTrustRegionRadius = initialTrustRegionRadius;
  224.         this.stoppingTrustRegionRadius = stoppingTrustRegionRadius;
  225.     }

  226.     /** {@inheritDoc} */
  227.     @Override
  228.     protected PointValuePair doOptimize() {
  229.         final double[] lowerBound = getLowerBound();
  230.         final double[] upperBound = getUpperBound();

  231.         // Validity checks.
  232.         setup(lowerBound, upperBound);

  233.         isMinimize = (getGoalType() == GoalType.MINIMIZE);
  234.         currentBest = new ArrayRealVector(getStartPoint());

  235.         final double value = bobyqa(lowerBound, upperBound);

  236.         return new PointValuePair(currentBest.getDataRef(),
  237.                                       isMinimize ? value : -value);
  238.     }

  239.     /**
  240.      *     This subroutine seeks the least value of a function of many variables,
  241.      *     by applying a trust region method that forms quadratic models by
  242.      *     interpolation. There is usually some freedom in the interpolation
  243.      *     conditions, which is taken up by minimizing the Frobenius norm of
  244.      *     the change to the second derivative of the model, beginning with the
  245.      *     zero matrix. The values of the variables are constrained by upper and
  246.      *     lower bounds. The arguments of the subroutine are as follows.
  247.      *
  248.      *     N must be set to the number of variables and must be at least two.
  249.      *     NPT is the number of interpolation conditions. Its value must be in
  250.      *       the interval [N+2,(N+1)(N+2)/2]. Choices that exceed 2*N+1 are not
  251.      *       recommended.
  252.      *     Initial values of the variables must be set in X(1),X(2),...,X(N). They
  253.      *       will be changed to the values that give the least calculated F.
  254.      *     For I=1,2,...,N, XL(I) and XU(I) must provide the lower and upper
  255.      *       bounds, respectively, on X(I). The construction of quadratic models
  256.      *       requires XL(I) to be strictly less than XU(I) for each I. Further,
  257.      *       the contribution to a model from changes to the I-th variable is
  258.      *       damaged severely by rounding errors if XU(I)-XL(I) is too small.
  259.      *     RHOBEG and RHOEND must be set to the initial and final values of a trust
  260.      *       region radius, so both must be positive with RHOEND no greater than
  261.      *       RHOBEG. Typically, RHOBEG should be about one tenth of the greatest
  262.      *       expected change to a variable, while RHOEND should indicate the
  263.      *       accuracy that is required in the final values of the variables. An
  264.      *       error return occurs if any of the differences XU(I)-XL(I), I=1,...,N,
  265.      *       is less than 2*RHOBEG.
  266.      *     MAXFUN must be set to an upper bound on the number of calls of CALFUN.
  267.      *     The array W will be used for working space. Its length must be at least
  268.      *       (NPT+5)*(NPT+N)+3*N*(N+5)/2.
  269.      *
  270.      * @param lowerBound Lower bounds.
  271.      * @param upperBound Upper bounds.
  272.      * @return the value of the objective at the optimum.
  273.      */
  274.     private double bobyqa(double[] lowerBound,
  275.                           double[] upperBound) {
  276.         printMethod(); // XXX

  277.         final int n = currentBest.getDimension();

  278.         // Return if there is insufficient space between the bounds. Modify the
  279.         // initial X if necessary in order to avoid conflicts between the bounds
  280.         // and the construction of the first quadratic model. The lower and upper
  281.         // bounds on moves from the updated X are set now, in the ISL and ISU
  282.         // partitions of W, in order to provide useful and exact information about
  283.         // components of X that become within distance RHOBEG from their bounds.

  284.         for (int j = 0; j < n; j++) {
  285.             final double boundDiff = boundDifference[j];
  286.             lowerDifference.setEntry(j, lowerBound[j] - currentBest.getEntry(j));
  287.             upperDifference.setEntry(j, upperBound[j] - currentBest.getEntry(j));
  288.             if (lowerDifference.getEntry(j) >= -initialTrustRegionRadius) {
  289.                 if (lowerDifference.getEntry(j) >= ZERO) {
  290.                     currentBest.setEntry(j, lowerBound[j]);
  291.                     lowerDifference.setEntry(j, ZERO);
  292.                     upperDifference.setEntry(j, boundDiff);
  293.                 } else {
  294.                     currentBest.setEntry(j, lowerBound[j] + initialTrustRegionRadius);
  295.                     lowerDifference.setEntry(j, -initialTrustRegionRadius);
  296.                     // Computing MAX
  297.                     final double deltaOne = upperBound[j] - currentBest.getEntry(j);
  298.                     upperDifference.setEntry(j, FastMath.max(deltaOne, initialTrustRegionRadius));
  299.                 }
  300.             } else if (upperDifference.getEntry(j) <= initialTrustRegionRadius) {
  301.                 if (upperDifference.getEntry(j) <= ZERO) {
  302.                     currentBest.setEntry(j, upperBound[j]);
  303.                     lowerDifference.setEntry(j, -boundDiff);
  304.                     upperDifference.setEntry(j, ZERO);
  305.                 } else {
  306.                     currentBest.setEntry(j, upperBound[j] - initialTrustRegionRadius);
  307.                     // Computing MIN
  308.                     final double deltaOne = lowerBound[j] - currentBest.getEntry(j);
  309.                     final double deltaTwo = -initialTrustRegionRadius;
  310.                     lowerDifference.setEntry(j, FastMath.min(deltaOne, deltaTwo));
  311.                     upperDifference.setEntry(j, initialTrustRegionRadius);
  312.                 }
  313.             }
  314.         }

  315.         // Make the call of BOBYQB.

  316.         return bobyqb(lowerBound, upperBound);
  317.     } // bobyqa

  318.     // ----------------------------------------------------------------------------------------

  319.     /**
  320.      *     The arguments N, NPT, X, XL, XU, RHOBEG, RHOEND, IPRINT and MAXFUN
  321.      *       are identical to the corresponding arguments in SUBROUTINE BOBYQA.
  322.      *     XBASE holds a shift of origin that should reduce the contributions
  323.      *       from rounding errors to values of the model and Lagrange functions.
  324.      *     XPT is a two-dimensional array that holds the coordinates of the
  325.      *       interpolation points relative to XBASE.
  326.      *     FVAL holds the values of F at the interpolation points.
  327.      *     XOPT is set to the displacement from XBASE of the trust region centre.
  328.      *     GOPT holds the gradient of the quadratic model at XBASE+XOPT.
  329.      *     HQ holds the explicit second derivatives of the quadratic model.
  330.      *     PQ contains the parameters of the implicit second derivatives of the
  331.      *       quadratic model.
  332.      *     BMAT holds the last N columns of H.
  333.      *     ZMAT holds the factorization of the leading NPT by NPT submatrix of H,
  334.      *       this factorization being ZMAT times ZMAT^T, which provides both the
  335.      *       correct rank and positive semi-definiteness.
  336.      *     NDIM is the first dimension of BMAT and has the value NPT+N.
  337.      *     SL and SU hold the differences XL-XBASE and XU-XBASE, respectively.
  338.      *       All the components of every XOPT are going to satisfy the bounds
  339.      *       SL(I) .LEQ. XOPT(I) .LEQ. SU(I), with appropriate equalities when
  340.      *       XOPT is on a constraint boundary.
  341.      *     XNEW is chosen by SUBROUTINE TRSBOX or ALTMOV. Usually XBASE+XNEW is the
  342.      *       vector of variables for the next call of CALFUN. XNEW also satisfies
  343.      *       the SL and SU constraints in the way that has just been mentioned.
  344.      *     XALT is an alternative to XNEW, chosen by ALTMOV, that may replace XNEW
  345.      *       in order to increase the denominator in the updating of UPDATE.
  346.      *     D is reserved for a trial step from XOPT, which is usually XNEW-XOPT.
  347.      *     VLAG contains the values of the Lagrange functions at a new point X.
  348.      *       They are part of a product that requires VLAG to be of length NDIM.
  349.      *     W is a one-dimensional array that is used for working space. Its length
  350.      *       must be at least 3*NDIM = 3*(NPT+N).
  351.      *
  352.      * @param lowerBound Lower bounds.
  353.      * @param upperBound Upper bounds.
  354.      * @return the value of the objective at the optimum.
  355.      */
  356.     private double bobyqb(double[] lowerBound,
  357.                           double[] upperBound) {
  358.         printMethod(); // XXX

  359.         final int n = currentBest.getDimension();
  360.         final int npt = numberOfInterpolationPoints;
  361.         final int np = n + 1;
  362.         final int nptm = npt - np;
  363.         final int nh = n * np / 2;

  364.         final ArrayRealVector work1 = new ArrayRealVector(n);
  365.         final ArrayRealVector work2 = new ArrayRealVector(npt);
  366.         final ArrayRealVector work3 = new ArrayRealVector(npt);

  367.         double cauchy = Double.NaN;
  368.         double alpha = Double.NaN;
  369.         double dsq = Double.NaN;
  370.         double crvmin = Double.NaN;

  371.         // Set some constants.
  372.         // Parameter adjustments

  373.         // Function Body

  374.         // The call of PRELIM sets the elements of XBASE, XPT, FVAL, GOPT, HQ, PQ,
  375.         // BMAT and ZMAT for the first iteration, with the corresponding values of
  376.         // of NF and KOPT, which are the number of calls of CALFUN so far and the
  377.         // index of the interpolation point at the trust region centre. Then the
  378.         // initial XOPT is set too. The branch to label 720 occurs if MAXFUN is
  379.         // less than NPT. GOPT will be updated if KOPT is different from KBASE.

  380.         trustRegionCenterInterpolationPointIndex = 0;

  381.         prelim(lowerBound, upperBound);
  382.         double xoptsq = ZERO;
  383.         for (int i = 0; i < n; i++) {
  384.             trustRegionCenterOffset.setEntry(i, interpolationPoints.getEntry(trustRegionCenterInterpolationPointIndex, i));
  385.             // Computing 2nd power
  386.             final double deltaOne = trustRegionCenterOffset.getEntry(i);
  387.             xoptsq += deltaOne * deltaOne;
  388.         }
  389.         double fsave = fAtInterpolationPoints.getEntry(0);
  390.         final int kbase = 0;

  391.         // Complete the settings that are required for the iterative procedure.

  392.         int ntrits = 0;
  393.         int itest = 0;
  394.         int knew = 0;
  395.         int nfsav = getEvaluations();
  396.         double rho = initialTrustRegionRadius;
  397.         double delta = rho;
  398.         double diffa = ZERO;
  399.         double diffb = ZERO;
  400.         double diffc = ZERO;
  401.         double f = ZERO;
  402.         double beta = ZERO;
  403.         double adelt = ZERO;
  404.         double denom = ZERO;
  405.         double ratio = ZERO;
  406.         double dnorm = ZERO;
  407.         double scaden = ZERO;
  408.         double biglsq = ZERO;
  409.         double distsq = ZERO;

  410.         // Update GOPT if necessary before the first iteration and after each
  411.         // call of RESCUE that makes a call of CALFUN.

  412.         int state = 20;
  413.         for(;;) switch (state) {
  414.         case 20: {
  415.             printState(20); // XXX
  416.             if (trustRegionCenterInterpolationPointIndex != kbase) {
  417.                 int ih = 0;
  418.                 for (int j = 0; j < n; j++) {
  419.                     for (int i = 0; i <= j; i++) {
  420.                         if (i < j) {
  421.                             gradientAtTrustRegionCenter.setEntry(j,  gradientAtTrustRegionCenter.getEntry(j) + modelSecondDerivativesValues.getEntry(ih) * trustRegionCenterOffset.getEntry(i));
  422.                         }
  423.                         gradientAtTrustRegionCenter.setEntry(i,  gradientAtTrustRegionCenter.getEntry(i) + modelSecondDerivativesValues.getEntry(ih) * trustRegionCenterOffset.getEntry(j));
  424.                         ih++;
  425.                     }
  426.                 }
  427.                 if (getEvaluations() > npt) {
  428.                     for (int k = 0; k < npt; k++) {
  429.                         double temp = ZERO;
  430.                         for (int j = 0; j < n; j++) {
  431.                             temp += interpolationPoints.getEntry(k, j) * trustRegionCenterOffset.getEntry(j);
  432.                         }
  433.                         temp *= modelSecondDerivativesParameters.getEntry(k);
  434.                         for (int i = 0; i < n; i++) {
  435.                             gradientAtTrustRegionCenter.setEntry(i, gradientAtTrustRegionCenter.getEntry(i) + temp * interpolationPoints.getEntry(k, i));
  436.                         }
  437.                     }
  438.                     // throw new PathIsExploredException(); // XXX
  439.                 }
  440.             }

  441.             // Generate the next point in the trust region that provides a small value
  442.             // of the quadratic model subject to the constraints on the variables.
  443.             // The int NTRITS is set to the number "trust region" iterations that
  444.             // have occurred since the last "alternative" iteration. If the length
  445.             // of XNEW-XOPT is less than HALF*RHO, however, then there is a branch to
  446.             // label 650 or 680 with NTRITS=-1, instead of calculating F at XNEW.

  447.         }
  448.         case 60: {
  449.             printState(60); // XXX
  450.             final ArrayRealVector gnew = new ArrayRealVector(n);
  451.             final ArrayRealVector xbdi = new ArrayRealVector(n);
  452.             final ArrayRealVector s = new ArrayRealVector(n);
  453.             final ArrayRealVector hs = new ArrayRealVector(n);
  454.             final ArrayRealVector hred = new ArrayRealVector(n);

  455.             final double[] dsqCrvmin = trsbox(delta, gnew, xbdi, s,
  456.                                               hs, hred);
  457.             dsq = dsqCrvmin[0];
  458.             crvmin = dsqCrvmin[1];

  459.             // Computing MIN
  460.             double deltaOne = delta;
  461.             double deltaTwo = FastMath.sqrt(dsq);
  462.             dnorm = FastMath.min(deltaOne, deltaTwo);
  463.             if (dnorm < HALF * rho) {
  464.                 ntrits = -1;
  465.                 // Computing 2nd power
  466.                 deltaOne = TEN * rho;
  467.                 distsq = deltaOne * deltaOne;
  468.                 if (getEvaluations() <= nfsav + 2) {
  469.                     state = 650; break;
  470.                 }

  471.                 // The following choice between labels 650 and 680 depends on whether or
  472.                 // not our work with the current RHO seems to be complete. Either RHO is
  473.                 // decreased or termination occurs if the errors in the quadratic model at
  474.                 // the last three interpolation points compare favourably with predictions
  475.                 // of likely improvements to the model within distance HALF*RHO of XOPT.

  476.                 // Computing MAX
  477.                 deltaOne = FastMath.max(diffa, diffb);
  478.                 final double errbig = FastMath.max(deltaOne, diffc);
  479.                 final double frhosq = rho * ONE_OVER_EIGHT * rho;
  480.                 if (crvmin > ZERO &&
  481.                     errbig > frhosq * crvmin) {
  482.                     state = 650; break;
  483.                 }
  484.                 final double bdtol = errbig / rho;
  485.                 for (int j = 0; j < n; j++) {
  486.                     double bdtest = bdtol;
  487.                     if (newPoint.getEntry(j) == lowerDifference.getEntry(j)) {
  488.                         bdtest = work1.getEntry(j);
  489.                     }
  490.                     if (newPoint.getEntry(j) == upperDifference.getEntry(j)) {
  491.                         bdtest = -work1.getEntry(j);
  492.                     }
  493.                     if (bdtest < bdtol) {
  494.                         double curv = modelSecondDerivativesValues.getEntry((j + j * j) / 2);
  495.                         for (int k = 0; k < npt; k++) {
  496.                             // Computing 2nd power
  497.                             final double d1 = interpolationPoints.getEntry(k, j);
  498.                             curv += modelSecondDerivativesParameters.getEntry(k) * (d1 * d1);
  499.                         }
  500.                         bdtest += HALF * curv * rho;
  501.                         if (bdtest < bdtol) {
  502.                             state = 650; break;
  503.                         }
  504.                         // throw new PathIsExploredException(); // XXX
  505.                     }
  506.                 }
  507.                 state = 680; break;
  508.             }
  509.             ++ntrits;

  510.             // Severe cancellation is likely to occur if XOPT is too far from XBASE.
  511.             // If the following test holds, then XBASE is shifted so that XOPT becomes
  512.             // zero. The appropriate changes are made to BMAT and to the second
  513.             // derivatives of the current model, beginning with the changes to BMAT
  514.             // that do not depend on ZMAT. VLAG is used temporarily for working space.

  515.         }
  516.         case 90: {
  517.             printState(90); // XXX
  518.             if (dsq <= xoptsq * ONE_OVER_A_THOUSAND) {
  519.                 final double fracsq = xoptsq * ONE_OVER_FOUR;
  520.                 double sumpq = ZERO;
  521.                 // final RealVector sumVector
  522.                 //     = new ArrayRealVector(npt, -HALF * xoptsq).add(interpolationPoints.operate(trustRegionCenter));
  523.                 for (int k = 0; k < npt; k++) {
  524.                     sumpq += modelSecondDerivativesParameters.getEntry(k);
  525.                     double sum = -HALF * xoptsq;
  526.                     for (int i = 0; i < n; i++) {
  527.                         sum += interpolationPoints.getEntry(k, i) * trustRegionCenterOffset.getEntry(i);
  528.                     }
  529.                     // sum = sumVector.getEntry(k); // XXX "testAckley" and "testDiffPow" fail.
  530.                     work2.setEntry(k, sum);
  531.                     final double temp = fracsq - HALF * sum;
  532.                     for (int i = 0; i < n; i++) {
  533.                         work1.setEntry(i, bMatrix.getEntry(k, i));
  534.                         lagrangeValuesAtNewPoint.setEntry(i, sum * interpolationPoints.getEntry(k, i) + temp * trustRegionCenterOffset.getEntry(i));
  535.                         final int ip = npt + i;
  536.                         for (int j = 0; j <= i; j++) {
  537.                             bMatrix.setEntry(ip, j,
  538.                                           bMatrix.getEntry(ip, j)
  539.                                           + work1.getEntry(i) * lagrangeValuesAtNewPoint.getEntry(j)
  540.                                           + lagrangeValuesAtNewPoint.getEntry(i) * work1.getEntry(j));
  541.                         }
  542.                     }
  543.                 }

  544.                 // Then the revisions of BMAT that depend on ZMAT are calculated.

  545.                 for (int m = 0; m < nptm; m++) {
  546.                     double sumz = ZERO;
  547.                     double sumw = ZERO;
  548.                     for (int k = 0; k < npt; k++) {
  549.                         sumz += zMatrix.getEntry(k, m);
  550.                         lagrangeValuesAtNewPoint.setEntry(k, work2.getEntry(k) * zMatrix.getEntry(k, m));
  551.                         sumw += lagrangeValuesAtNewPoint.getEntry(k);
  552.                     }
  553.                     for (int j = 0; j < n; j++) {
  554.                         double sum = (fracsq * sumz - HALF * sumw) * trustRegionCenterOffset.getEntry(j);
  555.                         for (int k = 0; k < npt; k++) {
  556.                             sum += lagrangeValuesAtNewPoint.getEntry(k) * interpolationPoints.getEntry(k, j);
  557.                         }
  558.                         work1.setEntry(j, sum);
  559.                         for (int k = 0; k < npt; k++) {
  560.                             bMatrix.setEntry(k, j,
  561.                                           bMatrix.getEntry(k, j)
  562.                                           + sum * zMatrix.getEntry(k, m));
  563.                         }
  564.                     }
  565.                     for (int i = 0; i < n; i++) {
  566.                         final int ip = i + npt;
  567.                         final double temp = work1.getEntry(i);
  568.                         for (int j = 0; j <= i; j++) {
  569.                             bMatrix.setEntry(ip, j,
  570.                                           bMatrix.getEntry(ip, j)
  571.                                           + temp * work1.getEntry(j));
  572.                         }
  573.                     }
  574.                 }

  575.                 // The following instructions complete the shift, including the changes
  576.                 // to the second derivative parameters of the quadratic model.

  577.                 int ih = 0;
  578.                 for (int j = 0; j < n; j++) {
  579.                     work1.setEntry(j, -HALF * sumpq * trustRegionCenterOffset.getEntry(j));
  580.                     for (int k = 0; k < npt; k++) {
  581.                         work1.setEntry(j, work1.getEntry(j) + modelSecondDerivativesParameters.getEntry(k) * interpolationPoints.getEntry(k, j));
  582.                         interpolationPoints.setEntry(k, j, interpolationPoints.getEntry(k, j) - trustRegionCenterOffset.getEntry(j));
  583.                     }
  584.                     for (int i = 0; i <= j; i++) {
  585.                          modelSecondDerivativesValues.setEntry(ih,
  586.                                     modelSecondDerivativesValues.getEntry(ih)
  587.                                     + work1.getEntry(i) * trustRegionCenterOffset.getEntry(j)
  588.                                     + trustRegionCenterOffset.getEntry(i) * work1.getEntry(j));
  589.                         bMatrix.setEntry(npt + i, j, bMatrix.getEntry(npt + j, i));
  590.                         ih++;
  591.                     }
  592.                 }
  593.                 for (int i = 0; i < n; i++) {
  594.                     originShift.setEntry(i, originShift.getEntry(i) + trustRegionCenterOffset.getEntry(i));
  595.                     newPoint.setEntry(i, newPoint.getEntry(i) - trustRegionCenterOffset.getEntry(i));
  596.                     lowerDifference.setEntry(i, lowerDifference.getEntry(i) - trustRegionCenterOffset.getEntry(i));
  597.                     upperDifference.setEntry(i, upperDifference.getEntry(i) - trustRegionCenterOffset.getEntry(i));
  598.                     trustRegionCenterOffset.setEntry(i, ZERO);
  599.                 }
  600.                 xoptsq = ZERO;
  601.             }
  602.             if (ntrits == 0) {
  603.                 state = 210; break;
  604.             }
  605.             state = 230; break;

  606.             // XBASE is also moved to XOPT by a call of RESCUE. This calculation is
  607.             // more expensive than the previous shift, because new matrices BMAT and
  608.             // ZMAT are generated from scratch, which may include the replacement of
  609.             // interpolation points whose positions seem to be causing near linear
  610.             // dependence in the interpolation conditions. Therefore RESCUE is called
  611.             // only if rounding errors have reduced by at least a factor of two the
  612.             // denominator of the formula for updating the H matrix. It provides a
  613.             // useful safeguard, but is not invoked in most applications of BOBYQA.

  614.         }
  615.         case 210: {
  616.             printState(210); // XXX
  617.             // Pick two alternative vectors of variables, relative to XBASE, that
  618.             // are suitable as new positions of the KNEW-th interpolation point.
  619.             // Firstly, XNEW is set to the point on a line through XOPT and another
  620.             // interpolation point that minimizes the predicted value of the next
  621.             // denominator, subject to ||XNEW - XOPT|| .LEQ. ADELT and to the SL
  622.             // and SU bounds. Secondly, XALT is set to the best feasible point on
  623.             // a constrained version of the Cauchy step of the KNEW-th Lagrange
  624.             // function, the corresponding value of the square of this function
  625.             // being returned in CAUCHY. The choice between these alternatives is
  626.             // going to be made when the denominator is calculated.

  627.             final double[] alphaCauchy = altmov(knew, adelt);
  628.             alpha = alphaCauchy[0];
  629.             cauchy = alphaCauchy[1];

  630.             for (int i = 0; i < n; i++) {
  631.                 trialStepPoint.setEntry(i, newPoint.getEntry(i) - trustRegionCenterOffset.getEntry(i));
  632.             }

  633.             // Calculate VLAG and BETA for the current choice of D. The scalar
  634.             // product of D with XPT(K,.) is going to be held in W(NPT+K) for
  635.             // use when VQUAD is calculated.

  636.         }
  637.         case 230: {
  638.             printState(230); // XXX
  639.             for (int k = 0; k < npt; k++) {
  640.                 double suma = ZERO;
  641.                 double sumb = ZERO;
  642.                 double sum = ZERO;
  643.                 for (int j = 0; j < n; j++) {
  644.                     suma += interpolationPoints.getEntry(k, j) * trialStepPoint.getEntry(j);
  645.                     sumb += interpolationPoints.getEntry(k, j) * trustRegionCenterOffset.getEntry(j);
  646.                     sum += bMatrix.getEntry(k, j) * trialStepPoint.getEntry(j);
  647.                 }
  648.                 work3.setEntry(k, suma * (HALF * suma + sumb));
  649.                 lagrangeValuesAtNewPoint.setEntry(k, sum);
  650.                 work2.setEntry(k, suma);
  651.             }
  652.             beta = ZERO;
  653.             for (int m = 0; m < nptm; m++) {
  654.                 double sum = ZERO;
  655.                 for (int k = 0; k < npt; k++) {
  656.                     sum += zMatrix.getEntry(k, m) * work3.getEntry(k);
  657.                 }
  658.                 beta -= sum * sum;
  659.                 for (int k = 0; k < npt; k++) {
  660.                     lagrangeValuesAtNewPoint.setEntry(k, lagrangeValuesAtNewPoint.getEntry(k) + sum * zMatrix.getEntry(k, m));
  661.                 }
  662.             }
  663.             dsq = ZERO;
  664.             double bsum = ZERO;
  665.             double dx = ZERO;
  666.             for (int j = 0; j < n; j++) {
  667.                 // Computing 2nd power
  668.                 final double d1 = trialStepPoint.getEntry(j);
  669.                 dsq += d1 * d1;
  670.                 double sum = ZERO;
  671.                 for (int k = 0; k < npt; k++) {
  672.                     sum += work3.getEntry(k) * bMatrix.getEntry(k, j);
  673.                 }
  674.                 bsum += sum * trialStepPoint.getEntry(j);
  675.                 final int jp = npt + j;
  676.                 for (int i = 0; i < n; i++) {
  677.                     sum += bMatrix.getEntry(jp, i) * trialStepPoint.getEntry(i);
  678.                 }
  679.                 lagrangeValuesAtNewPoint.setEntry(jp, sum);
  680.                 bsum += sum * trialStepPoint.getEntry(j);
  681.                 dx += trialStepPoint.getEntry(j) * trustRegionCenterOffset.getEntry(j);
  682.             }

  683.             beta = dx * dx + dsq * (xoptsq + dx + dx + HALF * dsq) + beta - bsum; // Original
  684.             // beta += dx * dx + dsq * (xoptsq + dx + dx + HALF * dsq) - bsum; // XXX "testAckley" and "testDiffPow" fail.
  685.             // beta = dx * dx + dsq * (xoptsq + 2 * dx + HALF * dsq) + beta - bsum; // XXX "testDiffPow" fails.

  686.             lagrangeValuesAtNewPoint.setEntry(trustRegionCenterInterpolationPointIndex,
  687.                           lagrangeValuesAtNewPoint.getEntry(trustRegionCenterInterpolationPointIndex) + ONE);

  688.             // If NTRITS is zero, the denominator may be increased by replacing
  689.             // the step D of ALTMOV by a Cauchy step. Then RESCUE may be called if
  690.             // rounding errors have damaged the chosen denominator.

  691.             if (ntrits == 0) {
  692.                 // Computing 2nd power
  693.                 final double d1 = lagrangeValuesAtNewPoint.getEntry(knew);
  694.                 denom = d1 * d1 + alpha * beta;
  695.                 if (denom < cauchy && cauchy > ZERO) {
  696.                     for (int i = 0; i < n; i++) {
  697.                         newPoint.setEntry(i, alternativeNewPoint.getEntry(i));
  698.                         trialStepPoint.setEntry(i, newPoint.getEntry(i) - trustRegionCenterOffset.getEntry(i));
  699.                     }
  700.                     cauchy = ZERO; // XXX Useful statement?
  701.                     state = 230; break;
  702.                 }
  703.                 // Alternatively, if NTRITS is positive, then set KNEW to the index of
  704.                 // the next interpolation point to be deleted to make room for a trust
  705.                 // region step. Again RESCUE may be called if rounding errors have damaged_
  706.                 // the chosen denominator, which is the reason for attempting to select
  707.                 // KNEW before calculating the next value of the objective function.

  708.             } else {
  709.                 final double delsq = delta * delta;
  710.                 scaden = ZERO;
  711.                 biglsq = ZERO;
  712.                 knew = 0;
  713.                 for (int k = 0; k < npt; k++) {
  714.                     if (k == trustRegionCenterInterpolationPointIndex) {
  715.                         continue;
  716.                     }
  717.                     double hdiag = ZERO;
  718.                     for (int m = 0; m < nptm; m++) {
  719.                         // Computing 2nd power
  720.                         final double d1 = zMatrix.getEntry(k, m);
  721.                         hdiag += d1 * d1;
  722.                     }
  723.                     // Computing 2nd power
  724.                     final double d2 = lagrangeValuesAtNewPoint.getEntry(k);
  725.                     final double den = beta * hdiag + d2 * d2;
  726.                     distsq = ZERO;
  727.                     for (int j = 0; j < n; j++) {
  728.                         // Computing 2nd power
  729.                         final double d3 = interpolationPoints.getEntry(k, j) - trustRegionCenterOffset.getEntry(j);
  730.                         distsq += d3 * d3;
  731.                     }
  732.                     // Computing MAX
  733.                     // Computing 2nd power
  734.                     final double d4 = distsq / delsq;
  735.                     final double temp = FastMath.max(ONE, d4 * d4);
  736.                     if (temp * den > scaden) {
  737.                         scaden = temp * den;
  738.                         knew = k;
  739.                         denom = den;
  740.                     }
  741.                     // Computing MAX
  742.                     // Computing 2nd power
  743.                     final double d5 = lagrangeValuesAtNewPoint.getEntry(k);
  744.                     biglsq = FastMath.max(biglsq, temp * (d5 * d5));
  745.                 }
  746.             }

  747.             // Put the variables for the next calculation of the objective function
  748.             //   in XNEW, with any adjustments for the bounds.

  749.             // Calculate the value of the objective function at XBASE+XNEW, unless
  750.             //   the limit on the number of calculations of F has been reached.

  751.         }
  752.         case 360: {
  753.             printState(360); // XXX
  754.             for (int i = 0; i < n; i++) {
  755.                 // Computing MIN
  756.                 // Computing MAX
  757.                 final double d3 = lowerBound[i];
  758.                 final double d4 = originShift.getEntry(i) + newPoint.getEntry(i);
  759.                 final double d1 = FastMath.max(d3, d4);
  760.                 final double d2 = upperBound[i];
  761.                 currentBest.setEntry(i, FastMath.min(d1, d2));
  762.                 if (newPoint.getEntry(i) == lowerDifference.getEntry(i)) {
  763.                     currentBest.setEntry(i, lowerBound[i]);
  764.                 }
  765.                 if (newPoint.getEntry(i) == upperDifference.getEntry(i)) {
  766.                     currentBest.setEntry(i, upperBound[i]);
  767.                 }
  768.             }

  769.             f = computeObjectiveValue(currentBest.toArray());

  770.             if (!isMinimize)
  771.                 f = -f;
  772.             if (ntrits == -1) {
  773.                 fsave = f;
  774.                 state = 720; break;
  775.             }

  776.             // Use the quadratic model to predict the change in F due to the step D,
  777.             //   and set DIFF to the error of this prediction.

  778.             final double fopt = fAtInterpolationPoints.getEntry(trustRegionCenterInterpolationPointIndex);
  779.             double vquad = ZERO;
  780.             int ih = 0;
  781.             for (int j = 0; j < n; j++) {
  782.                 vquad += trialStepPoint.getEntry(j) * gradientAtTrustRegionCenter.getEntry(j);
  783.                 for (int i = 0; i <= j; i++) {
  784.                     double temp = trialStepPoint.getEntry(i) * trialStepPoint.getEntry(j);
  785.                     if (i == j) {
  786.                         temp *= HALF;
  787.                     }
  788.                     vquad += modelSecondDerivativesValues.getEntry(ih) * temp;
  789.                     ih++;
  790.                }
  791.             }
  792.             for (int k = 0; k < npt; k++) {
  793.                 // Computing 2nd power
  794.                 final double d1 = work2.getEntry(k);
  795.                 final double d2 = d1 * d1; // "d1" must be squared first to prevent test failures.
  796.                 vquad += HALF * modelSecondDerivativesParameters.getEntry(k) * d2;
  797.             }
  798.             final double diff = f - fopt - vquad;
  799.             diffc = diffb;
  800.             diffb = diffa;
  801.             diffa = FastMath.abs(diff);
  802.             if (dnorm > rho) {
  803.                 nfsav = getEvaluations();
  804.             }

  805.             // Pick the next value of DELTA after a trust region step.

  806.             if (ntrits > 0) {
  807.                 if (vquad >= ZERO) {
  808.                     throw new MathIllegalStateException(LocalizedFormats.TRUST_REGION_STEP_FAILED, vquad);
  809.                 }
  810.                 ratio = (f - fopt) / vquad;
  811.                 final double hDelta = HALF * delta;
  812.                 if (ratio <= ONE_OVER_TEN) {
  813.                     // Computing MIN
  814.                     delta = FastMath.min(hDelta, dnorm);
  815.                 } else if (ratio <= .7) {
  816.                     // Computing MAX
  817.                     delta = FastMath.max(hDelta, dnorm);
  818.                 } else {
  819.                     // Computing MAX
  820.                     delta = FastMath.max(hDelta, 2 * dnorm);
  821.                 }
  822.                 if (delta <= rho * 1.5) {
  823.                     delta = rho;
  824.                 }

  825.                 // Recalculate KNEW and DENOM if the new F is less than FOPT.

  826.                 if (f < fopt) {
  827.                     final int ksav = knew;
  828.                     final double densav = denom;
  829.                     final double delsq = delta * delta;
  830.                     scaden = ZERO;
  831.                     biglsq = ZERO;
  832.                     knew = 0;
  833.                     for (int k = 0; k < npt; k++) {
  834.                         double hdiag = ZERO;
  835.                         for (int m = 0; m < nptm; m++) {
  836.                             // Computing 2nd power
  837.                             final double d1 = zMatrix.getEntry(k, m);
  838.                             hdiag += d1 * d1;
  839.                         }
  840.                         // Computing 2nd power
  841.                         final double d1 = lagrangeValuesAtNewPoint.getEntry(k);
  842.                         final double den = beta * hdiag + d1 * d1;
  843.                         distsq = ZERO;
  844.                         for (int j = 0; j < n; j++) {
  845.                             // Computing 2nd power
  846.                             final double d2 = interpolationPoints.getEntry(k, j) - newPoint.getEntry(j);
  847.                             distsq += d2 * d2;
  848.                         }
  849.                         // Computing MAX
  850.                         // Computing 2nd power
  851.                         final double d3 = distsq / delsq;
  852.                         final double temp = FastMath.max(ONE, d3 * d3);
  853.                         if (temp * den > scaden) {
  854.                             scaden = temp * den;
  855.                             knew = k;
  856.                             denom = den;
  857.                         }
  858.                         // Computing MAX
  859.                         // Computing 2nd power
  860.                         final double d4 = lagrangeValuesAtNewPoint.getEntry(k);
  861.                         final double d5 = temp * (d4 * d4);
  862.                         biglsq = FastMath.max(biglsq, d5);
  863.                     }
  864.                     if (scaden <= HALF * biglsq) {
  865.                         knew = ksav;
  866.                         denom = densav;
  867.                     }
  868.                 }
  869.             }

  870.             // Update BMAT and ZMAT, so that the KNEW-th interpolation point can be
  871.             // moved. Also update the second derivative terms of the model.

  872.             update(beta, denom, knew);

  873.             ih = 0;
  874.             final double pqold = modelSecondDerivativesParameters.getEntry(knew);
  875.             modelSecondDerivativesParameters.setEntry(knew, ZERO);
  876.             for (int i = 0; i < n; i++) {
  877.                 final double temp = pqold * interpolationPoints.getEntry(knew, i);
  878.                 for (int j = 0; j <= i; j++) {
  879.                     modelSecondDerivativesValues.setEntry(ih, modelSecondDerivativesValues.getEntry(ih) + temp * interpolationPoints.getEntry(knew, j));
  880.                     ih++;
  881.                 }
  882.             }
  883.             for (int m = 0; m < nptm; m++) {
  884.                 final double temp = diff * zMatrix.getEntry(knew, m);
  885.                 for (int k = 0; k < npt; k++) {
  886.                     modelSecondDerivativesParameters.setEntry(k, modelSecondDerivativesParameters.getEntry(k) + temp * zMatrix.getEntry(k, m));
  887.                 }
  888.             }

  889.             // Include the new interpolation point, and make the changes to GOPT at
  890.             // the old XOPT that are caused by the updating of the quadratic model.

  891.             fAtInterpolationPoints.setEntry(knew,  f);
  892.             for (int i = 0; i < n; i++) {
  893.                 interpolationPoints.setEntry(knew, i, newPoint.getEntry(i));
  894.                 work1.setEntry(i, bMatrix.getEntry(knew, i));
  895.             }
  896.             for (int k = 0; k < npt; k++) {
  897.                 double suma = ZERO;
  898.                 for (int m = 0; m < nptm; m++) {
  899.                     suma += zMatrix.getEntry(knew, m) * zMatrix.getEntry(k, m);
  900.                 }
  901.                 double sumb = ZERO;
  902.                 for (int j = 0; j < n; j++) {
  903.                     sumb += interpolationPoints.getEntry(k, j) * trustRegionCenterOffset.getEntry(j);
  904.                 }
  905.                 final double temp = suma * sumb;
  906.                 for (int i = 0; i < n; i++) {
  907.                     work1.setEntry(i, work1.getEntry(i) + temp * interpolationPoints.getEntry(k, i));
  908.                 }
  909.             }
  910.             for (int i = 0; i < n; i++) {
  911.                 gradientAtTrustRegionCenter.setEntry(i, gradientAtTrustRegionCenter.getEntry(i) + diff * work1.getEntry(i));
  912.             }

  913.             // Update XOPT, GOPT and KOPT if the new calculated F is less than FOPT.

  914.             if (f < fopt) {
  915.                 trustRegionCenterInterpolationPointIndex = knew;
  916.                 xoptsq = ZERO;
  917.                 ih = 0;
  918.                 for (int j = 0; j < n; j++) {
  919.                     trustRegionCenterOffset.setEntry(j, newPoint.getEntry(j));
  920.                     // Computing 2nd power
  921.                     final double d1 = trustRegionCenterOffset.getEntry(j);
  922.                     xoptsq += d1 * d1;
  923.                     for (int i = 0; i <= j; i++) {
  924.                         if (i < j) {
  925.                             gradientAtTrustRegionCenter.setEntry(j, gradientAtTrustRegionCenter.getEntry(j) + modelSecondDerivativesValues.getEntry(ih) * trialStepPoint.getEntry(i));
  926.                         }
  927.                         gradientAtTrustRegionCenter.setEntry(i, gradientAtTrustRegionCenter.getEntry(i) + modelSecondDerivativesValues.getEntry(ih) * trialStepPoint.getEntry(j));
  928.                         ih++;
  929.                     }
  930.                 }
  931.                 for (int k = 0; k < npt; k++) {
  932.                     double temp = ZERO;
  933.                     for (int j = 0; j < n; j++) {
  934.                         temp += interpolationPoints.getEntry(k, j) * trialStepPoint.getEntry(j);
  935.                     }
  936.                     temp *= modelSecondDerivativesParameters.getEntry(k);
  937.                     for (int i = 0; i < n; i++) {
  938.                         gradientAtTrustRegionCenter.setEntry(i, gradientAtTrustRegionCenter.getEntry(i) + temp * interpolationPoints.getEntry(k, i));
  939.                     }
  940.                 }
  941.             }

  942.             // Calculate the parameters of the least Frobenius norm interpolant to
  943.             // the current data, the gradient of this interpolant at XOPT being put
  944.             // into VLAG(NPT+I), I=1,2,...,N.

  945.             if (ntrits > 0) {
  946.                 for (int k = 0; k < npt; k++) {
  947.                     lagrangeValuesAtNewPoint.setEntry(k, fAtInterpolationPoints.getEntry(k) - fAtInterpolationPoints.getEntry(trustRegionCenterInterpolationPointIndex));
  948.                     work3.setEntry(k, ZERO);
  949.                 }
  950.                 for (int j = 0; j < nptm; j++) {
  951.                     double sum = ZERO;
  952.                     for (int k = 0; k < npt; k++) {
  953.                         sum += zMatrix.getEntry(k, j) * lagrangeValuesAtNewPoint.getEntry(k);
  954.                     }
  955.                     for (int k = 0; k < npt; k++) {
  956.                         work3.setEntry(k, work3.getEntry(k) + sum * zMatrix.getEntry(k, j));
  957.                     }
  958.                 }
  959.                 for (int k = 0; k < npt; k++) {
  960.                     double sum = ZERO;
  961.                     for (int j = 0; j < n; j++) {
  962.                         sum += interpolationPoints.getEntry(k, j) * trustRegionCenterOffset.getEntry(j);
  963.                     }
  964.                     work2.setEntry(k, work3.getEntry(k));
  965.                     work3.setEntry(k, sum * work3.getEntry(k));
  966.                 }
  967.                 double gqsq = ZERO;
  968.                 double gisq = ZERO;
  969.                 for (int i = 0; i < n; i++) {
  970.                     double sum = ZERO;
  971.                     for (int k = 0; k < npt; k++) {
  972.                         sum += bMatrix.getEntry(k, i) *
  973.                             lagrangeValuesAtNewPoint.getEntry(k) + interpolationPoints.getEntry(k, i) * work3.getEntry(k);
  974.                     }
  975.                     if (trustRegionCenterOffset.getEntry(i) == lowerDifference.getEntry(i)) {
  976.                         // Computing MIN
  977.                         // Computing 2nd power
  978.                         final double d1 = FastMath.min(ZERO, gradientAtTrustRegionCenter.getEntry(i));
  979.                         gqsq += d1 * d1;
  980.                         // Computing 2nd power
  981.                         final double d2 = FastMath.min(ZERO, sum);
  982.                         gisq += d2 * d2;
  983.                     } else if (trustRegionCenterOffset.getEntry(i) == upperDifference.getEntry(i)) {
  984.                         // Computing MAX
  985.                         // Computing 2nd power
  986.                         final double d1 = FastMath.max(ZERO, gradientAtTrustRegionCenter.getEntry(i));
  987.                         gqsq += d1 * d1;
  988.                         // Computing 2nd power
  989.                         final double d2 = FastMath.max(ZERO, sum);
  990.                         gisq += d2 * d2;
  991.                     } else {
  992.                         // Computing 2nd power
  993.                         final double d1 = gradientAtTrustRegionCenter.getEntry(i);
  994.                         gqsq += d1 * d1;
  995.                         gisq += sum * sum;
  996.                     }
  997.                     lagrangeValuesAtNewPoint.setEntry(npt + i, sum);
  998.                 }

  999.                 // Test whether to replace the new quadratic model by the least Frobenius
  1000.                 // norm interpolant, making the replacement if the test is satisfied.

  1001.                 ++itest;
  1002.                 if (gqsq < TEN * gisq) {
  1003.                     itest = 0;
  1004.                 }
  1005.                 if (itest >= 3) {
  1006.                     for (int i = 0, max = FastMath.max(npt, nh); i < max; i++) {
  1007.                         if (i < n) {
  1008.                             gradientAtTrustRegionCenter.setEntry(i, lagrangeValuesAtNewPoint.getEntry(npt + i));
  1009.                         }
  1010.                         if (i < npt) {
  1011.                             modelSecondDerivativesParameters.setEntry(i, work2.getEntry(i));
  1012.                         }
  1013.                         if (i < nh) {
  1014.                             modelSecondDerivativesValues.setEntry(i, ZERO);
  1015.                         }
  1016.                         itest = 0;
  1017.                     }
  1018.                 }
  1019.             }

  1020.             // If a trust region step has provided a sufficient decrease in F, then
  1021.             // branch for another trust region calculation. The case NTRITS=0 occurs
  1022.             // when the new interpolation point was reached by an alternative step.

  1023.             if (ntrits == 0) {
  1024.                 state = 60; break;
  1025.             }
  1026.             if (f <= fopt + ONE_OVER_TEN * vquad) {
  1027.                 state = 60; break;
  1028.             }

  1029.             // Alternatively, find out if the interpolation points are close enough
  1030.             //   to the best point so far.

  1031.             // Computing MAX
  1032.             // Computing 2nd power
  1033.             final double d1 = TWO * delta;
  1034.             // Computing 2nd power
  1035.             final double d2 = TEN * rho;
  1036.             distsq = FastMath.max(d1 * d1, d2 * d2);
  1037.         }
  1038.         case 650: {
  1039.             printState(650); // XXX
  1040.             knew = -1;
  1041.             for (int k = 0; k < npt; k++) {
  1042.                 double sum = ZERO;
  1043.                 for (int j = 0; j < n; j++) {
  1044.                     // Computing 2nd power
  1045.                     final double d1 = interpolationPoints.getEntry(k, j) - trustRegionCenterOffset.getEntry(j);
  1046.                     sum += d1 * d1;
  1047.                 }
  1048.                 if (sum > distsq) {
  1049.                     knew = k;
  1050.                     distsq = sum;
  1051.                 }
  1052.             }

  1053.             // If KNEW is positive, then ALTMOV finds alternative new positions for
  1054.             // the KNEW-th interpolation point within distance ADELT of XOPT. It is
  1055.             // reached via label 90. Otherwise, there is a branch to label 60 for
  1056.             // another trust region iteration, unless the calculations with the
  1057.             // current RHO are complete.

  1058.             if (knew >= 0) {
  1059.                 final double dist = FastMath.sqrt(distsq);
  1060.                 if (ntrits == -1) {
  1061.                     // Computing MIN
  1062.                     delta = FastMath.min(ONE_OVER_TEN * delta, HALF * dist);
  1063.                     if (delta <= rho * 1.5) {
  1064.                         delta = rho;
  1065.                     }
  1066.                 }
  1067.                 ntrits = 0;
  1068.                 // Computing MAX
  1069.                 // Computing MIN
  1070.                 final double d1 = FastMath.min(ONE_OVER_TEN * dist, delta);
  1071.                 adelt = FastMath.max(d1, rho);
  1072.                 dsq = adelt * adelt;
  1073.                 state = 90; break;
  1074.             }
  1075.             if (ntrits == -1) {
  1076.                 state = 680; break;
  1077.             }
  1078.             if (ratio > ZERO) {
  1079.                 state = 60; break;
  1080.             }
  1081.             if (FastMath.max(delta, dnorm) > rho) {
  1082.                 state = 60; break;
  1083.             }

  1084.             // The calculations with the current value of RHO are complete. Pick the
  1085.             //   next values of RHO and DELTA.
  1086.         }
  1087.         case 680: {
  1088.             printState(680); // XXX
  1089.             if (rho > stoppingTrustRegionRadius) {
  1090.                 delta = HALF * rho;
  1091.                 ratio = rho / stoppingTrustRegionRadius;
  1092.                 if (ratio <= SIXTEEN) {
  1093.                     rho = stoppingTrustRegionRadius;
  1094.                 } else if (ratio <= TWO_HUNDRED_FIFTY) {
  1095.                     rho = FastMath.sqrt(ratio) * stoppingTrustRegionRadius;
  1096.                 } else {
  1097.                     rho *= ONE_OVER_TEN;
  1098.                 }
  1099.                 delta = FastMath.max(delta, rho);
  1100.                 ntrits = 0;
  1101.                 nfsav = getEvaluations();
  1102.                 state = 60; break;
  1103.             }

  1104.             // Return from the calculation, after another Newton-Raphson step, if
  1105.             //   it is too short to have been tried before.

  1106.             if (ntrits == -1) {
  1107.                 state = 360; break;
  1108.             }
  1109.         }
  1110.         case 720: {
  1111.             printState(720); // XXX
  1112.             if (fAtInterpolationPoints.getEntry(trustRegionCenterInterpolationPointIndex) <= fsave) {
  1113.                 for (int i = 0; i < n; i++) {
  1114.                     // Computing MIN
  1115.                     // Computing MAX
  1116.                     final double d3 = lowerBound[i];
  1117.                     final double d4 = originShift.getEntry(i) + trustRegionCenterOffset.getEntry(i);
  1118.                     final double d1 = FastMath.max(d3, d4);
  1119.                     final double d2 = upperBound[i];
  1120.                     currentBest.setEntry(i, FastMath.min(d1, d2));
  1121.                     if (trustRegionCenterOffset.getEntry(i) == lowerDifference.getEntry(i)) {
  1122.                         currentBest.setEntry(i, lowerBound[i]);
  1123.                     }
  1124.                     if (trustRegionCenterOffset.getEntry(i) == upperDifference.getEntry(i)) {
  1125.                         currentBest.setEntry(i, upperBound[i]);
  1126.                     }
  1127.                 }
  1128.                 f = fAtInterpolationPoints.getEntry(trustRegionCenterInterpolationPointIndex);
  1129.             }
  1130.             return f;
  1131.         }
  1132.         default: {
  1133.             throw new MathIllegalStateException(LocalizedFormats.SIMPLE_MESSAGE, "bobyqb");
  1134.         }}
  1135.     } // bobyqb

  1136.     // ----------------------------------------------------------------------------------------

  1137.     /**
  1138.      *     The arguments N, NPT, XPT, XOPT, BMAT, ZMAT, NDIM, SL and SU all have
  1139.      *       the same meanings as the corresponding arguments of BOBYQB.
  1140.      *     KOPT is the index of the optimal interpolation point.
  1141.      *     KNEW is the index of the interpolation point that is going to be moved.
  1142.      *     ADELT is the current trust region bound.
  1143.      *     XNEW will be set to a suitable new position for the interpolation point
  1144.      *       XPT(KNEW,.). Specifically, it satisfies the SL, SU and trust region
  1145.      *       bounds and it should provide a large denominator in the next call of
  1146.      *       UPDATE. The step XNEW-XOPT from XOPT is restricted to moves along the
  1147.      *       straight lines through XOPT and another interpolation point.
  1148.      *     XALT also provides a large value of the modulus of the KNEW-th Lagrange
  1149.      *       function subject to the constraints that have been mentioned, its main
  1150.      *       difference from XNEW being that XALT-XOPT is a constrained version of
  1151.      *       the Cauchy step within the trust region. An exception is that XALT is
  1152.      *       not calculated if all components of GLAG (see below) are zero.
  1153.      *     ALPHA will be set to the KNEW-th diagonal element of the H matrix.
  1154.      *     CAUCHY will be set to the square of the KNEW-th Lagrange function at
  1155.      *       the step XALT-XOPT from XOPT for the vector XALT that is returned,
  1156.      *       except that CAUCHY is set to zero if XALT is not calculated.
  1157.      *     GLAG is a working space vector of length N for the gradient of the
  1158.      *       KNEW-th Lagrange function at XOPT.
  1159.      *     HCOL is a working space vector of length NPT for the second derivative
  1160.      *       coefficients of the KNEW-th Lagrange function.
  1161.      *     W is a working space vector of length 2N that is going to hold the
  1162.      *       constrained Cauchy step from XOPT of the Lagrange function, followed
  1163.      *       by the downhill version of XALT when the uphill step is calculated.
  1164.      *
  1165.      *     Set the first NPT components of W to the leading elements of the
  1166.      *     KNEW-th column of the H matrix.
  1167.      * @param knew
  1168.      * @param adelt
  1169.      */
  1170.     private double[] altmov(
  1171.             int knew,
  1172.             double adelt
  1173.     ) {
  1174.         printMethod(); // XXX

  1175.         final int n = currentBest.getDimension();
  1176.         final int npt = numberOfInterpolationPoints;

  1177.         final ArrayRealVector glag = new ArrayRealVector(n);
  1178.         final ArrayRealVector hcol = new ArrayRealVector(npt);

  1179.         final ArrayRealVector work1 = new ArrayRealVector(n);
  1180.         final ArrayRealVector work2 = new ArrayRealVector(n);

  1181.         for (int k = 0; k < npt; k++) {
  1182.             hcol.setEntry(k, ZERO);
  1183.         }
  1184.         for (int j = 0, max = npt - n - 1; j < max; j++) {
  1185.             final double tmp = zMatrix.getEntry(knew, j);
  1186.             for (int k = 0; k < npt; k++) {
  1187.                 hcol.setEntry(k, hcol.getEntry(k) + tmp * zMatrix.getEntry(k, j));
  1188.             }
  1189.         }
  1190.         final double alpha = hcol.getEntry(knew);
  1191.         final double ha = HALF * alpha;

  1192.         // Calculate the gradient of the KNEW-th Lagrange function at XOPT.

  1193.         for (int i = 0; i < n; i++) {
  1194.             glag.setEntry(i, bMatrix.getEntry(knew, i));
  1195.         }
  1196.         for (int k = 0; k < npt; k++) {
  1197.             double tmp = ZERO;
  1198.             for (int j = 0; j < n; j++) {
  1199.                 tmp += interpolationPoints.getEntry(k, j) * trustRegionCenterOffset.getEntry(j);
  1200.             }
  1201.             tmp *= hcol.getEntry(k);
  1202.             for (int i = 0; i < n; i++) {
  1203.                 glag.setEntry(i, glag.getEntry(i) + tmp * interpolationPoints.getEntry(k, i));
  1204.             }
  1205.         }

  1206.         // Search for a large denominator along the straight lines through XOPT
  1207.         // and another interpolation point. SLBD and SUBD will be lower and upper
  1208.         // bounds on the step along each of these lines in turn. PREDSQ will be
  1209.         // set to the square of the predicted denominator for each line. PRESAV
  1210.         // will be set to the largest admissible value of PREDSQ that occurs.

  1211.         double presav = ZERO;
  1212.         double step = Double.NaN;
  1213.         int ksav = 0;
  1214.         int ibdsav = 0;
  1215.         double stpsav = 0;
  1216.         for (int k = 0; k < npt; k++) {
  1217.             if (k == trustRegionCenterInterpolationPointIndex) {
  1218.                 continue;
  1219.             }
  1220.             double dderiv = ZERO;
  1221.             double distsq = ZERO;
  1222.             for (int i = 0; i < n; i++) {
  1223.                 final double tmp = interpolationPoints.getEntry(k, i) - trustRegionCenterOffset.getEntry(i);
  1224.                 dderiv += glag.getEntry(i) * tmp;
  1225.                 distsq += tmp * tmp;
  1226.             }
  1227.             double subd = adelt / FastMath.sqrt(distsq);
  1228.             double slbd = -subd;
  1229.             int ilbd = 0;
  1230.             int iubd = 0;
  1231.             final double sumin = FastMath.min(ONE, subd);

  1232.             // Revise SLBD and SUBD if necessary because of the bounds in SL and SU.

  1233.             for (int i = 0; i < n; i++) {
  1234.                 final double tmp = interpolationPoints.getEntry(k, i) - trustRegionCenterOffset.getEntry(i);
  1235.                 if (tmp > ZERO) {
  1236.                     if (slbd * tmp < lowerDifference.getEntry(i) - trustRegionCenterOffset.getEntry(i)) {
  1237.                         slbd = (lowerDifference.getEntry(i) - trustRegionCenterOffset.getEntry(i)) / tmp;
  1238.                         ilbd = -i - 1;
  1239.                     }
  1240.                     if (subd * tmp > upperDifference.getEntry(i) - trustRegionCenterOffset.getEntry(i)) {
  1241.                         // Computing MAX
  1242.                         subd = FastMath.max(sumin,
  1243.                                             (upperDifference.getEntry(i) - trustRegionCenterOffset.getEntry(i)) / tmp);
  1244.                         iubd = i + 1;
  1245.                     }
  1246.                 } else if (tmp < ZERO) {
  1247.                     if (slbd * tmp > upperDifference.getEntry(i) - trustRegionCenterOffset.getEntry(i)) {
  1248.                         slbd = (upperDifference.getEntry(i) - trustRegionCenterOffset.getEntry(i)) / tmp;
  1249.                         ilbd = i + 1;
  1250.                     }
  1251.                     if (subd * tmp < lowerDifference.getEntry(i) - trustRegionCenterOffset.getEntry(i)) {
  1252.                         // Computing MAX
  1253.                         subd = FastMath.max(sumin,
  1254.                                             (lowerDifference.getEntry(i) - trustRegionCenterOffset.getEntry(i)) / tmp);
  1255.                         iubd = -i - 1;
  1256.                     }
  1257.                 }
  1258.             }

  1259.             // Seek a large modulus of the KNEW-th Lagrange function when the index
  1260.             // of the other interpolation point on the line through XOPT is KNEW.

  1261.             step = slbd;
  1262.             int isbd = ilbd;
  1263.             double vlag = Double.NaN;
  1264.             if (k == knew) {
  1265.                 final double diff = dderiv - ONE;
  1266.                 vlag = slbd * (dderiv - slbd * diff);
  1267.                 final double d1 = subd * (dderiv - subd * diff);
  1268.                 if (FastMath.abs(d1) > FastMath.abs(vlag)) {
  1269.                     step = subd;
  1270.                     vlag = d1;
  1271.                     isbd = iubd;
  1272.                 }
  1273.                 final double d2 = HALF * dderiv;
  1274.                 final double d3 = d2 - diff * slbd;
  1275.                 final double d4 = d2 - diff * subd;
  1276.                 if (d3 * d4 < ZERO) {
  1277.                     final double d5 = d2 * d2 / diff;
  1278.                     if (FastMath.abs(d5) > FastMath.abs(vlag)) {
  1279.                         step = d2 / diff;
  1280.                         vlag = d5;
  1281.                         isbd = 0;
  1282.                     }
  1283.                 }

  1284.                 // Search along each of the other lines through XOPT and another point.

  1285.             } else {
  1286.                 vlag = slbd * (ONE - slbd);
  1287.                 final double tmp = subd * (ONE - subd);
  1288.                 if (FastMath.abs(tmp) > FastMath.abs(vlag)) {
  1289.                     step = subd;
  1290.                     vlag = tmp;
  1291.                     isbd = iubd;
  1292.                 }
  1293.                 if (subd > HALF && FastMath.abs(vlag) < ONE_OVER_FOUR) {
  1294.                     step = HALF;
  1295.                     vlag = ONE_OVER_FOUR;
  1296.                     isbd = 0;
  1297.                 }
  1298.                 vlag *= dderiv;
  1299.             }

  1300.             // Calculate PREDSQ for the current line search and maintain PRESAV.

  1301.             final double tmp = step * (ONE - step) * distsq;
  1302.             final double predsq = vlag * vlag * (vlag * vlag + ha * tmp * tmp);
  1303.             if (predsq > presav) {
  1304.                 presav = predsq;
  1305.                 ksav = k;
  1306.                 stpsav = step;
  1307.                 ibdsav = isbd;
  1308.             }
  1309.         }

  1310.         // Construct XNEW in a way that satisfies the bound constraints exactly.

  1311.         for (int i = 0; i < n; i++) {
  1312.             final double tmp = trustRegionCenterOffset.getEntry(i) + stpsav * (interpolationPoints.getEntry(ksav, i) - trustRegionCenterOffset.getEntry(i));
  1313.             newPoint.setEntry(i, FastMath.max(lowerDifference.getEntry(i),
  1314.                                               FastMath.min(upperDifference.getEntry(i), tmp)));
  1315.         }
  1316.         if (ibdsav < 0) {
  1317.             newPoint.setEntry(-ibdsav - 1, lowerDifference.getEntry(-ibdsav - 1));
  1318.         }
  1319.         if (ibdsav > 0) {
  1320.             newPoint.setEntry(ibdsav - 1, upperDifference.getEntry(ibdsav - 1));
  1321.         }

  1322.         // Prepare for the iterative method that assembles the constrained Cauchy
  1323.         // step in W. The sum of squares of the fixed components of W is formed in
  1324.         // WFIXSQ, and the free components of W are set to BIGSTP.

  1325.         final double bigstp = adelt + adelt;
  1326.         int iflag = 0;
  1327.         double cauchy = Double.NaN;
  1328.         double csave = ZERO;
  1329.         while (true) {
  1330.             double wfixsq = ZERO;
  1331.             double ggfree = ZERO;
  1332.             for (int i = 0; i < n; i++) {
  1333.                 final double glagValue = glag.getEntry(i);
  1334.                 work1.setEntry(i, ZERO);
  1335.                 if (FastMath.min(trustRegionCenterOffset.getEntry(i) - lowerDifference.getEntry(i), glagValue) > ZERO ||
  1336.                     FastMath.max(trustRegionCenterOffset.getEntry(i) - upperDifference.getEntry(i), glagValue) < ZERO) {
  1337.                     work1.setEntry(i, bigstp);
  1338.                     // Computing 2nd power
  1339.                     ggfree += glagValue * glagValue;
  1340.                 }
  1341.             }
  1342.             if (ggfree == ZERO) {
  1343.                 return new double[] { alpha, ZERO };
  1344.             }

  1345.             // Investigate whether more components of W can be fixed.
  1346.             final double tmp1 = adelt * adelt - wfixsq;
  1347.             if (tmp1 > ZERO) {
  1348.                 step = FastMath.sqrt(tmp1 / ggfree);
  1349.                 ggfree = ZERO;
  1350.                 for (int i = 0; i < n; i++) {
  1351.                     if (work1.getEntry(i) == bigstp) {
  1352.                         final double tmp2 = trustRegionCenterOffset.getEntry(i) - step * glag.getEntry(i);
  1353.                         if (tmp2 <= lowerDifference.getEntry(i)) {
  1354.                             work1.setEntry(i, lowerDifference.getEntry(i) - trustRegionCenterOffset.getEntry(i));
  1355.                             // Computing 2nd power
  1356.                             final double d1 = work1.getEntry(i);
  1357.                             wfixsq += d1 * d1;
  1358.                         } else if (tmp2 >= upperDifference.getEntry(i)) {
  1359.                             work1.setEntry(i, upperDifference.getEntry(i) - trustRegionCenterOffset.getEntry(i));
  1360.                             // Computing 2nd power
  1361.                             final double d1 = work1.getEntry(i);
  1362.                             wfixsq += d1 * d1;
  1363.                         } else {
  1364.                             // Computing 2nd power
  1365.                             final double d1 = glag.getEntry(i);
  1366.                             ggfree += d1 * d1;
  1367.                         }
  1368.                     }
  1369.                 }
  1370.             }

  1371.             // Set the remaining free components of W and all components of XALT,
  1372.             // except that W may be scaled later.

  1373.             double gw = ZERO;
  1374.             for (int i = 0; i < n; i++) {
  1375.                 final double glagValue = glag.getEntry(i);
  1376.                 if (work1.getEntry(i) == bigstp) {
  1377.                     work1.setEntry(i, -step * glagValue);
  1378.                     final double min = FastMath.min(upperDifference.getEntry(i),
  1379.                                                     trustRegionCenterOffset.getEntry(i) + work1.getEntry(i));
  1380.                     alternativeNewPoint.setEntry(i, FastMath.max(lowerDifference.getEntry(i), min));
  1381.                 } else if (work1.getEntry(i) == ZERO) {
  1382.                     alternativeNewPoint.setEntry(i, trustRegionCenterOffset.getEntry(i));
  1383.                 } else if (glagValue > ZERO) {
  1384.                     alternativeNewPoint.setEntry(i, lowerDifference.getEntry(i));
  1385.                 } else {
  1386.                     alternativeNewPoint.setEntry(i, upperDifference.getEntry(i));
  1387.                 }
  1388.                 gw += glagValue * work1.getEntry(i);
  1389.             }

  1390.             // Set CURV to the curvature of the KNEW-th Lagrange function along W.
  1391.             // Scale W by a factor less than one if that can reduce the modulus of
  1392.             // the Lagrange function at XOPT+W. Set CAUCHY to the final value of
  1393.             // the square of this function.

  1394.             double curv = ZERO;
  1395.             for (int k = 0; k < npt; k++) {
  1396.                 double tmp = ZERO;
  1397.                 for (int j = 0; j < n; j++) {
  1398.                     tmp += interpolationPoints.getEntry(k, j) * work1.getEntry(j);
  1399.                 }
  1400.                 curv += hcol.getEntry(k) * tmp * tmp;
  1401.             }
  1402.             if (iflag == 1) {
  1403.                 curv = -curv;
  1404.             }
  1405.             if (curv > -gw &&
  1406.                 curv < -gw * (ONE + FastMath.sqrt(TWO))) {
  1407.                 final double scale = -gw / curv;
  1408.                 for (int i = 0; i < n; i++) {
  1409.                     final double tmp = trustRegionCenterOffset.getEntry(i) + scale * work1.getEntry(i);
  1410.                     alternativeNewPoint.setEntry(i, FastMath.max(lowerDifference.getEntry(i),
  1411.                                                     FastMath.min(upperDifference.getEntry(i), tmp)));
  1412.                 }
  1413.                 // Computing 2nd power
  1414.                 final double d1 = HALF * gw * scale;
  1415.                 cauchy = d1 * d1;
  1416.             } else {
  1417.                 // Computing 2nd power
  1418.                 final double d1 = gw + HALF * curv;
  1419.                 cauchy = d1 * d1;
  1420.             }

  1421.             // If IFLAG is zero, then XALT is calculated as before after reversing
  1422.             // the sign of GLAG. Thus two XALT vectors become available. The one that
  1423.             // is chosen is the one that gives the larger value of CAUCHY.

  1424.             if (iflag == 0) {
  1425.                 for (int i = 0; i < n; i++) {
  1426.                     glag.setEntry(i, -glag.getEntry(i));
  1427.                     work2.setEntry(i, alternativeNewPoint.getEntry(i));
  1428.                 }
  1429.                 csave = cauchy;
  1430.                 iflag = 1;
  1431.             } else {
  1432.                 break;
  1433.             }
  1434.         }
  1435.         if (csave > cauchy) {
  1436.             for (int i = 0; i < n; i++) {
  1437.                 alternativeNewPoint.setEntry(i, work2.getEntry(i));
  1438.             }
  1439.             cauchy = csave;
  1440.         }

  1441.         return new double[] { alpha, cauchy };
  1442.     } // altmov

  1443.     // ----------------------------------------------------------------------------------------

  1444.     /**
  1445.      *     SUBROUTINE PRELIM sets the elements of XBASE, XPT, FVAL, GOPT, HQ, PQ,
  1446.      *     BMAT and ZMAT for the first iteration, and it maintains the values of
  1447.      *     NF and KOPT. The vector X is also changed by PRELIM.
  1448.      *
  1449.      *     The arguments N, NPT, X, XL, XU, RHOBEG, IPRINT and MAXFUN are the
  1450.      *       same as the corresponding arguments in SUBROUTINE BOBYQA.
  1451.      *     The arguments XBASE, XPT, FVAL, HQ, PQ, BMAT, ZMAT, NDIM, SL and SU
  1452.      *       are the same as the corresponding arguments in BOBYQB, the elements
  1453.      *       of SL and SU being set in BOBYQA.
  1454.      *     GOPT is usually the gradient of the quadratic model at XOPT+XBASE, but
  1455.      *       it is set by PRELIM to the gradient of the quadratic model at XBASE.
  1456.      *       If XOPT is nonzero, BOBYQB will change it to its usual value later.
  1457.      *     NF is maintaned as the number of calls of CALFUN so far.
  1458.      *     KOPT will be such that the least calculated value of F so far is at
  1459.      *       the point XPT(KOPT,.)+XBASE in the space of the variables.
  1460.      *
  1461.      * @param lowerBound Lower bounds.
  1462.      * @param upperBound Upper bounds.
  1463.      */
  1464.     private void prelim(double[] lowerBound,
  1465.                         double[] upperBound) {
  1466.         printMethod(); // XXX

  1467.         final int n = currentBest.getDimension();
  1468.         final int npt = numberOfInterpolationPoints;
  1469.         final int ndim = bMatrix.getRowDimension();

  1470.         final double rhosq = initialTrustRegionRadius * initialTrustRegionRadius;
  1471.         final double recip = 1d / rhosq;
  1472.         final int np = n + 1;

  1473.         // Set XBASE to the initial vector of variables, and set the initial
  1474.         // elements of XPT, BMAT, HQ, PQ and ZMAT to zero.

  1475.         for (int j = 0; j < n; j++) {
  1476.             originShift.setEntry(j, currentBest.getEntry(j));
  1477.             for (int k = 0; k < npt; k++) {
  1478.                 interpolationPoints.setEntry(k, j, ZERO);
  1479.             }
  1480.             for (int i = 0; i < ndim; i++) {
  1481.                 bMatrix.setEntry(i, j, ZERO);
  1482.             }
  1483.         }
  1484.         for (int i = 0, max = n * np / 2; i < max; i++) {
  1485.             modelSecondDerivativesValues.setEntry(i, ZERO);
  1486.         }
  1487.         for (int k = 0; k < npt; k++) {
  1488.             modelSecondDerivativesParameters.setEntry(k, ZERO);
  1489.             for (int j = 0, max = npt - np; j < max; j++) {
  1490.                 zMatrix.setEntry(k, j, ZERO);
  1491.             }
  1492.         }

  1493.         // Begin the initialization procedure. NF becomes one more than the number
  1494.         // of function values so far. The coordinates of the displacement of the
  1495.         // next initial interpolation point from XBASE are set in XPT(NF+1,.).

  1496.         int ipt = 0;
  1497.         int jpt = 0;
  1498.         double fbeg = Double.NaN;
  1499.         do {
  1500.             final int nfm = getEvaluations();
  1501.             final int nfx = nfm - n;
  1502.             final int nfmm = nfm - 1;
  1503.             final int nfxm = nfx - 1;
  1504.             double stepa = 0;
  1505.             double stepb = 0;
  1506.             if (nfm <= 2 * n) {
  1507.                 if (nfm >= 1 &&
  1508.                     nfm <= n) {
  1509.                     stepa = initialTrustRegionRadius;
  1510.                     if (upperDifference.getEntry(nfmm) == ZERO) {
  1511.                         stepa = -stepa;
  1512.                         // throw new PathIsExploredException(); // XXX
  1513.                     }
  1514.                     interpolationPoints.setEntry(nfm, nfmm, stepa);
  1515.                 } else if (nfm > n) {
  1516.                     stepa = interpolationPoints.getEntry(nfx, nfxm);
  1517.                     stepb = -initialTrustRegionRadius;
  1518.                     if (lowerDifference.getEntry(nfxm) == ZERO) {
  1519.                         stepb = FastMath.min(TWO * initialTrustRegionRadius, upperDifference.getEntry(nfxm));
  1520.                         // throw new PathIsExploredException(); // XXX
  1521.                     }
  1522.                     if (upperDifference.getEntry(nfxm) == ZERO) {
  1523.                         stepb = FastMath.max(-TWO * initialTrustRegionRadius, lowerDifference.getEntry(nfxm));
  1524.                         // throw new PathIsExploredException(); // XXX
  1525.                     }
  1526.                     interpolationPoints.setEntry(nfm, nfxm, stepb);
  1527.                 }
  1528.             } else {
  1529.                 final int tmp1 = (nfm - np) / n;
  1530.                 jpt = nfm - tmp1 * n - n;
  1531.                 ipt = jpt + tmp1;
  1532.                 if (ipt > n) {
  1533.                     final int tmp2 = jpt;
  1534.                     jpt = ipt - n;
  1535.                     ipt = tmp2;
  1536. //                     throw new PathIsExploredException(); // XXX
  1537.                 }
  1538.                 final int iptMinus1 = ipt - 1;
  1539.                 final int jptMinus1 = jpt - 1;
  1540.                 interpolationPoints.setEntry(nfm, iptMinus1, interpolationPoints.getEntry(ipt, iptMinus1));
  1541.                 interpolationPoints.setEntry(nfm, jptMinus1, interpolationPoints.getEntry(jpt, jptMinus1));
  1542.             }

  1543.             // Calculate the next value of F. The least function value so far and
  1544.             // its index are required.

  1545.             for (int j = 0; j < n; j++) {
  1546.                 currentBest.setEntry(j, FastMath.min(FastMath.max(lowerBound[j],
  1547.                                                                   originShift.getEntry(j) + interpolationPoints.getEntry(nfm, j)),
  1548.                                                      upperBound[j]));
  1549.                 if (interpolationPoints.getEntry(nfm, j) == lowerDifference.getEntry(j)) {
  1550.                     currentBest.setEntry(j, lowerBound[j]);
  1551.                 }
  1552.                 if (interpolationPoints.getEntry(nfm, j) == upperDifference.getEntry(j)) {
  1553.                     currentBest.setEntry(j, upperBound[j]);
  1554.                 }
  1555.             }

  1556.             final double objectiveValue = computeObjectiveValue(currentBest.toArray());
  1557.             final double f = isMinimize ? objectiveValue : -objectiveValue;
  1558.             final int numEval = getEvaluations(); // nfm + 1
  1559.             fAtInterpolationPoints.setEntry(nfm, f);

  1560.             if (numEval == 1) {
  1561.                 fbeg = f;
  1562.                 trustRegionCenterInterpolationPointIndex = 0;
  1563.             } else if (f < fAtInterpolationPoints.getEntry(trustRegionCenterInterpolationPointIndex)) {
  1564.                 trustRegionCenterInterpolationPointIndex = nfm;
  1565.             }

  1566.             // Set the nonzero initial elements of BMAT and the quadratic model in the
  1567.             // cases when NF is at most 2*N+1. If NF exceeds N+1, then the positions
  1568.             // of the NF-th and (NF-N)-th interpolation points may be switched, in
  1569.             // order that the function value at the first of them contributes to the
  1570.             // off-diagonal second derivative terms of the initial quadratic model.

  1571.             if (numEval <= 2 * n + 1) {
  1572.                 if (numEval >= 2 &&
  1573.                     numEval <= n + 1) {
  1574.                     gradientAtTrustRegionCenter.setEntry(nfmm, (f - fbeg) / stepa);
  1575.                     if (npt < numEval + n) {
  1576.                         final double oneOverStepA = ONE / stepa;
  1577.                         bMatrix.setEntry(0, nfmm, -oneOverStepA);
  1578.                         bMatrix.setEntry(nfm, nfmm, oneOverStepA);
  1579.                         bMatrix.setEntry(npt + nfmm, nfmm, -HALF * rhosq);
  1580.                         // throw new PathIsExploredException(); // XXX
  1581.                     }
  1582.                 } else if (numEval >= n + 2) {
  1583.                     final int ih = nfx * (nfx + 1) / 2 - 1;
  1584.                     final double tmp = (f - fbeg) / stepb;
  1585.                     final double diff = stepb - stepa;
  1586.                     modelSecondDerivativesValues.setEntry(ih, TWO * (tmp - gradientAtTrustRegionCenter.getEntry(nfxm)) / diff);
  1587.                     gradientAtTrustRegionCenter.setEntry(nfxm, (gradientAtTrustRegionCenter.getEntry(nfxm) * stepb - tmp * stepa) / diff);
  1588.                     if (stepa * stepb < ZERO && f < fAtInterpolationPoints.getEntry(nfm - n)) {
  1589.                         fAtInterpolationPoints.setEntry(nfm, fAtInterpolationPoints.getEntry(nfm - n));
  1590.                         fAtInterpolationPoints.setEntry(nfm - n, f);
  1591.                         if (trustRegionCenterInterpolationPointIndex == nfm) {
  1592.                             trustRegionCenterInterpolationPointIndex = nfm - n;
  1593.                         }
  1594.                         interpolationPoints.setEntry(nfm - n, nfxm, stepb);
  1595.                         interpolationPoints.setEntry(nfm, nfxm, stepa);
  1596.                     }
  1597.                     bMatrix.setEntry(0, nfxm, -(stepa + stepb) / (stepa * stepb));
  1598.                     bMatrix.setEntry(nfm, nfxm, -HALF / interpolationPoints.getEntry(nfm - n, nfxm));
  1599.                     bMatrix.setEntry(nfm - n, nfxm,
  1600.                                   -bMatrix.getEntry(0, nfxm) - bMatrix.getEntry(nfm, nfxm));
  1601.                     zMatrix.setEntry(0, nfxm, FastMath.sqrt(TWO) / (stepa * stepb));
  1602.                     zMatrix.setEntry(nfm, nfxm, FastMath.sqrt(HALF) / rhosq);
  1603.                     // zMatrix.setEntry(nfm, nfxm, FastMath.sqrt(HALF) * recip); // XXX "testAckley" and "testDiffPow" fail.
  1604.                     zMatrix.setEntry(nfm - n, nfxm,
  1605.                                   -zMatrix.getEntry(0, nfxm) - zMatrix.getEntry(nfm, nfxm));
  1606.                 }

  1607.                 // Set the off-diagonal second derivatives of the Lagrange functions and
  1608.                 // the initial quadratic model.

  1609.             } else {
  1610.                 zMatrix.setEntry(0, nfxm, recip);
  1611.                 zMatrix.setEntry(nfm, nfxm, recip);
  1612.                 zMatrix.setEntry(ipt, nfxm, -recip);
  1613.                 zMatrix.setEntry(jpt, nfxm, -recip);

  1614.                 final int ih = ipt * (ipt - 1) / 2 + jpt - 1;
  1615.                 final double tmp = interpolationPoints.getEntry(nfm, ipt - 1) * interpolationPoints.getEntry(nfm, jpt - 1);
  1616.                 modelSecondDerivativesValues.setEntry(ih, (fbeg - fAtInterpolationPoints.getEntry(ipt) - fAtInterpolationPoints.getEntry(jpt) + f) / tmp);
  1617. //                 throw new PathIsExploredException(); // XXX
  1618.             }
  1619.         } while (getEvaluations() < npt);
  1620.     } // prelim


  1621.     // ----------------------------------------------------------------------------------------

  1622.     /**
  1623.      *     A version of the truncated conjugate gradient is applied. If a line
  1624.      *     search is restricted by a constraint, then the procedure is restarted,
  1625.      *     the values of the variables that are at their bounds being fixed. If
  1626.      *     the trust region boundary is reached, then further changes may be made
  1627.      *     to D, each one being in the two dimensional space that is spanned
  1628.      *     by the current D and the gradient of Q at XOPT+D, staying on the trust
  1629.      *     region boundary. Termination occurs when the reduction in Q seems to
  1630.      *     be close to the greatest reduction that can be achieved.
  1631.      *     The arguments N, NPT, XPT, XOPT, GOPT, HQ, PQ, SL and SU have the same
  1632.      *       meanings as the corresponding arguments of BOBYQB.
  1633.      *     DELTA is the trust region radius for the present calculation, which
  1634.      *       seeks a small value of the quadratic model within distance DELTA of
  1635.      *       XOPT subject to the bounds on the variables.
  1636.      *     XNEW will be set to a new vector of variables that is approximately
  1637.      *       the one that minimizes the quadratic model within the trust region
  1638.      *       subject to the SL and SU constraints on the variables. It satisfies
  1639.      *       as equations the bounds that become active during the calculation.
  1640.      *     D is the calculated trial step from XOPT, generated iteratively from an
  1641.      *       initial value of zero. Thus XNEW is XOPT+D after the final iteration.
  1642.      *     GNEW holds the gradient of the quadratic model at XOPT+D. It is updated
  1643.      *       when D is updated.
  1644.      *     xbdi.get( is a working space vector. For I=1,2,...,N, the element xbdi.get((I) is
  1645.      *       set to -1.0, 0.0, or 1.0, the value being nonzero if and only if the
  1646.      *       I-th variable has become fixed at a bound, the bound being SL(I) or
  1647.      *       SU(I) in the case xbdi.get((I)=-1.0 or xbdi.get((I)=1.0, respectively. This
  1648.      *       information is accumulated during the construction of XNEW.
  1649.      *     The arrays S, HS and HRED are also used for working space. They hold the
  1650.      *       current search direction, and the changes in the gradient of Q along S
  1651.      *       and the reduced D, respectively, where the reduced D is the same as D,
  1652.      *       except that the components of the fixed variables are zero.
  1653.      *     DSQ will be set to the square of the length of XNEW-XOPT.
  1654.      *     CRVMIN is set to zero if D reaches the trust region boundary. Otherwise
  1655.      *       it is set to the least curvature of H that occurs in the conjugate
  1656.      *       gradient searches that are not restricted by any constraints. The
  1657.      *       value CRVMIN=-1.0D0 is set, however, if all of these searches are
  1658.      *       constrained.
  1659.      * @param delta
  1660.      * @param gnew
  1661.      * @param xbdi
  1662.      * @param s
  1663.      * @param hs
  1664.      * @param hred
  1665.      */
  1666.     private double[] trsbox(
  1667.             double delta,
  1668.             ArrayRealVector gnew,
  1669.             ArrayRealVector xbdi,
  1670.             ArrayRealVector s,
  1671.             ArrayRealVector hs,
  1672.             ArrayRealVector hred
  1673.     ) {
  1674.         printMethod(); // XXX

  1675.         final int n = currentBest.getDimension();
  1676.         final int npt = numberOfInterpolationPoints;

  1677.         double dsq = Double.NaN;
  1678.         double crvmin = Double.NaN;

  1679.         // Local variables
  1680.         double ds;
  1681.         int iu;
  1682.         double dhd, dhs, cth, shs, sth, ssq, beta=0, sdec, blen;
  1683.         int iact = -1;
  1684.         int nact = 0;
  1685.         double angt = 0, qred;
  1686.         int isav;
  1687.         double temp = 0, xsav = 0, xsum = 0, angbd = 0, dredg = 0, sredg = 0;
  1688.         int iterc;
  1689.         double resid = 0, delsq = 0, ggsav = 0, tempa = 0, tempb = 0,
  1690.         redmax = 0, dredsq = 0, redsav = 0, gredsq = 0, rednew = 0;
  1691.         int itcsav = 0;
  1692.         double rdprev = 0, rdnext = 0, stplen = 0, stepsq = 0;
  1693.         int itermax = 0;

  1694.         // Set some constants.

  1695.         // Function Body

  1696.         // The sign of GOPT(I) gives the sign of the change to the I-th variable
  1697.         // that will reduce Q from its value at XOPT. Thus xbdi.get((I) shows whether
  1698.         // or not to fix the I-th variable at one of its bounds initially, with
  1699.         // NACT being set to the number of fixed variables. D and GNEW are also
  1700.         // set for the first iteration. DELSQ is the upper bound on the sum of
  1701.         // squares of the free variables. QRED is the reduction in Q so far.

  1702.         iterc = 0;
  1703.         nact = 0;
  1704.         for (int i = 0; i < n; i++) {
  1705.             xbdi.setEntry(i, ZERO);
  1706.             if (trustRegionCenterOffset.getEntry(i) <= lowerDifference.getEntry(i)) {
  1707.                 if (gradientAtTrustRegionCenter.getEntry(i) >= ZERO) {
  1708.                     xbdi.setEntry(i, MINUS_ONE);
  1709.                 }
  1710.             } else if (trustRegionCenterOffset.getEntry(i) >= upperDifference.getEntry(i) &&
  1711.                        gradientAtTrustRegionCenter.getEntry(i) <= ZERO) {
  1712.                 xbdi.setEntry(i, ONE);
  1713.             }
  1714.             if (xbdi.getEntry(i) != ZERO) {
  1715.                 ++nact;
  1716.             }
  1717.             trialStepPoint.setEntry(i, ZERO);
  1718.             gnew.setEntry(i, gradientAtTrustRegionCenter.getEntry(i));
  1719.         }
  1720.         delsq = delta * delta;
  1721.         qred = ZERO;
  1722.         crvmin = MINUS_ONE;

  1723.         // Set the next search direction of the conjugate gradient method. It is
  1724.         // the steepest descent direction initially and when the iterations are
  1725.         // restarted because a variable has just been fixed by a bound, and of
  1726.         // course the components of the fixed variables are zero. ITERMAX is an
  1727.         // upper bound on the indices of the conjugate gradient iterations.

  1728.         int state = 20;
  1729.         for(;;) {
  1730.             switch (state) {
  1731.         case 20: {
  1732.             printState(20); // XXX
  1733.             beta = ZERO;
  1734.         }
  1735.         case 30: {
  1736.             printState(30); // XXX
  1737.             stepsq = ZERO;
  1738.             for (int i = 0; i < n; i++) {
  1739.                 if (xbdi.getEntry(i) != ZERO) {
  1740.                     s.setEntry(i, ZERO);
  1741.                 } else if (beta == ZERO) {
  1742.                     s.setEntry(i, -gnew.getEntry(i));
  1743.                 } else {
  1744.                     s.setEntry(i, beta * s.getEntry(i) - gnew.getEntry(i));
  1745.                 }
  1746.                 // Computing 2nd power
  1747.                 final double d1 = s.getEntry(i);
  1748.                 stepsq += d1 * d1;
  1749.             }
  1750.             if (stepsq == ZERO) {
  1751.                 state = 190; break;
  1752.             }
  1753.             if (beta == ZERO) {
  1754.                 gredsq = stepsq;
  1755.                 itermax = iterc + n - nact;
  1756.             }
  1757.             if (gredsq * delsq <= qred * 1e-4 * qred) {
  1758.                 state = 190; break;
  1759.             }

  1760.             // Multiply the search direction by the second derivative matrix of Q and
  1761.             // calculate some scalars for the choice of steplength. Then set BLEN to
  1762.             // the length of the the step to the trust region boundary and STPLEN to
  1763.             // the steplength, ignoring the simple bounds.

  1764.             state = 210; break;
  1765.         }
  1766.         case 50: {
  1767.             printState(50); // XXX
  1768.             resid = delsq;
  1769.             ds = ZERO;
  1770.             shs = ZERO;
  1771.             for (int i = 0; i < n; i++) {
  1772.                 if (xbdi.getEntry(i) == ZERO) {
  1773.                     // Computing 2nd power
  1774.                     final double d1 = trialStepPoint.getEntry(i);
  1775.                     resid -= d1 * d1;
  1776.                     ds += s.getEntry(i) * trialStepPoint.getEntry(i);
  1777.                     shs += s.getEntry(i) * hs.getEntry(i);
  1778.                 }
  1779.             }
  1780.             if (resid <= ZERO) {
  1781.                 state = 90; break;
  1782.             }
  1783.             temp = FastMath.sqrt(stepsq * resid + ds * ds);
  1784.             if (ds < ZERO) {
  1785.                 blen = (temp - ds) / stepsq;
  1786.             } else {
  1787.                 blen = resid / (temp + ds);
  1788.             }
  1789.             stplen = blen;
  1790.             if (shs > ZERO) {
  1791.                 // Computing MIN
  1792.                 stplen = FastMath.min(blen, gredsq / shs);
  1793.             }

  1794.             // Reduce STPLEN if necessary in order to preserve the simple bounds,
  1795.             // letting IACT be the index of the new constrained variable.

  1796.             iact = -1;
  1797.             for (int i = 0; i < n; i++) {
  1798.                 if (s.getEntry(i) != ZERO) {
  1799.                     xsum = trustRegionCenterOffset.getEntry(i) + trialStepPoint.getEntry(i);
  1800.                     if (s.getEntry(i) > ZERO) {
  1801.                         temp = (upperDifference.getEntry(i) - xsum) / s.getEntry(i);
  1802.                     } else {
  1803.                         temp = (lowerDifference.getEntry(i) - xsum) / s.getEntry(i);
  1804.                     }
  1805.                     if (temp < stplen) {
  1806.                         stplen = temp;
  1807.                         iact = i;
  1808.                     }
  1809.                 }
  1810.             }

  1811.             // Update CRVMIN, GNEW and D. Set SDEC to the decrease that occurs in Q.

  1812.             sdec = ZERO;
  1813.             if (stplen > ZERO) {
  1814.                 ++iterc;
  1815.                 temp = shs / stepsq;
  1816.                 if (iact == -1 && temp > ZERO) {
  1817.                     crvmin = FastMath.min(crvmin,temp);
  1818.                     if (crvmin == MINUS_ONE) {
  1819.                         crvmin = temp;
  1820.                     }
  1821.                 }
  1822.                 ggsav = gredsq;
  1823.                 gredsq = ZERO;
  1824.                 for (int i = 0; i < n; i++) {
  1825.                     gnew.setEntry(i, gnew.getEntry(i) + stplen * hs.getEntry(i));
  1826.                     if (xbdi.getEntry(i) == ZERO) {
  1827.                         // Computing 2nd power
  1828.                         final double d1 = gnew.getEntry(i);
  1829.                         gredsq += d1 * d1;
  1830.                     }
  1831.                     trialStepPoint.setEntry(i, trialStepPoint.getEntry(i) + stplen * s.getEntry(i));
  1832.                 }
  1833.                 // Computing MAX
  1834.                 final double d1 = stplen * (ggsav - HALF * stplen * shs);
  1835.                 sdec = FastMath.max(d1, ZERO);
  1836.                 qred += sdec;
  1837.             }

  1838.             // Restart the conjugate gradient method if it has hit a new bound.

  1839.             if (iact >= 0) {
  1840.                 ++nact;
  1841.                 xbdi.setEntry(iact, ONE);
  1842.                 if (s.getEntry(iact) < ZERO) {
  1843.                     xbdi.setEntry(iact, MINUS_ONE);
  1844.                 }
  1845.                 // Computing 2nd power
  1846.                 final double d1 = trialStepPoint.getEntry(iact);
  1847.                 delsq -= d1 * d1;
  1848.                 if (delsq <= ZERO) {
  1849.                     state = 190; break;
  1850.                 }
  1851.                 state = 20; break;
  1852.             }

  1853.             // If STPLEN is less than BLEN, then either apply another conjugate
  1854.             // gradient iteration or RETURN.

  1855.             if (stplen < blen) {
  1856.                 if (iterc == itermax) {
  1857.                     state = 190; break;
  1858.                 }
  1859.                 if (sdec <= qred * .01) {
  1860.                     state = 190; break;
  1861.                 }
  1862.                 beta = gredsq / ggsav;
  1863.                 state = 30; break;
  1864.             }
  1865.         }
  1866.         case 90: {
  1867.             printState(90); // XXX
  1868.             crvmin = ZERO;

  1869.             // Prepare for the alternative iteration by calculating some scalars
  1870.             // and by multiplying the reduced D by the second derivative matrix of
  1871.             // Q, where S holds the reduced D in the call of GGMULT.

  1872.         }
  1873.         case 100: {
  1874.             printState(100); // XXX
  1875.             if (nact >= n - 1) {
  1876.                 state = 190; break;
  1877.             }
  1878.             dredsq = ZERO;
  1879.             dredg = ZERO;
  1880.             gredsq = ZERO;
  1881.             for (int i = 0; i < n; i++) {
  1882.                 if (xbdi.getEntry(i) == ZERO) {
  1883.                     // Computing 2nd power
  1884.                     double d1 = trialStepPoint.getEntry(i);
  1885.                     dredsq += d1 * d1;
  1886.                     dredg += trialStepPoint.getEntry(i) * gnew.getEntry(i);
  1887.                     // Computing 2nd power
  1888.                     d1 = gnew.getEntry(i);
  1889.                     gredsq += d1 * d1;
  1890.                     s.setEntry(i, trialStepPoint.getEntry(i));
  1891.                 } else {
  1892.                     s.setEntry(i, ZERO);
  1893.                 }
  1894.             }
  1895.             itcsav = iterc;
  1896.             state = 210; break;
  1897.             // Let the search direction S be a linear combination of the reduced D
  1898.             // and the reduced G that is orthogonal to the reduced D.
  1899.         }
  1900.         case 120: {
  1901.             printState(120); // XXX
  1902.             ++iterc;
  1903.             temp = gredsq * dredsq - dredg * dredg;
  1904.             if (temp <= qred * 1e-4 * qred) {
  1905.                 state = 190; break;
  1906.             }
  1907.             temp = FastMath.sqrt(temp);
  1908.             for (int i = 0; i < n; i++) {
  1909.                 if (xbdi.getEntry(i) == ZERO) {
  1910.                     s.setEntry(i, (dredg * trialStepPoint.getEntry(i) - dredsq * gnew.getEntry(i)) / temp);
  1911.                 } else {
  1912.                     s.setEntry(i, ZERO);
  1913.                 }
  1914.             }
  1915.             sredg = -temp;

  1916.             // By considering the simple bounds on the variables, calculate an upper
  1917.             // bound on the tangent of half the angle of the alternative iteration,
  1918.             // namely ANGBD, except that, if already a free variable has reached a
  1919.             // bound, there is a branch back to label 100 after fixing that variable.

  1920.             angbd = ONE;
  1921.             iact = -1;
  1922.             for (int i = 0; i < n; i++) {
  1923.                 if (xbdi.getEntry(i) == ZERO) {
  1924.                     tempa = trustRegionCenterOffset.getEntry(i) + trialStepPoint.getEntry(i) - lowerDifference.getEntry(i);
  1925.                     tempb = upperDifference.getEntry(i) - trustRegionCenterOffset.getEntry(i) - trialStepPoint.getEntry(i);
  1926.                     if (tempa <= ZERO) {
  1927.                         ++nact;
  1928.                         xbdi.setEntry(i, MINUS_ONE);
  1929.                         state = 100; break;
  1930.                     } else if (tempb <= ZERO) {
  1931.                         ++nact;
  1932.                         xbdi.setEntry(i, ONE);
  1933.                         state = 100; break;
  1934.                     }
  1935.                     // Computing 2nd power
  1936.                     double d1 = trialStepPoint.getEntry(i);
  1937.                     // Computing 2nd power
  1938.                     double d2 = s.getEntry(i);
  1939.                     ssq = d1 * d1 + d2 * d2;
  1940.                     // Computing 2nd power
  1941.                     d1 = trustRegionCenterOffset.getEntry(i) - lowerDifference.getEntry(i);
  1942.                     temp = ssq - d1 * d1;
  1943.                     if (temp > ZERO) {
  1944.                         temp = FastMath.sqrt(temp) - s.getEntry(i);
  1945.                         if (angbd * temp > tempa) {
  1946.                             angbd = tempa / temp;
  1947.                             iact = i;
  1948.                             xsav = MINUS_ONE;
  1949.                         }
  1950.                     }
  1951.                     // Computing 2nd power
  1952.                     d1 = upperDifference.getEntry(i) - trustRegionCenterOffset.getEntry(i);
  1953.                     temp = ssq - d1 * d1;
  1954.                     if (temp > ZERO) {
  1955.                         temp = FastMath.sqrt(temp) + s.getEntry(i);
  1956.                         if (angbd * temp > tempb) {
  1957.                             angbd = tempb / temp;
  1958.                             iact = i;
  1959.                             xsav = ONE;
  1960.                         }
  1961.                     }
  1962.                 }
  1963.             }

  1964.             // Calculate HHD and some curvatures for the alternative iteration.

  1965.             state = 210; break;
  1966.         }
  1967.         case 150: {
  1968.             printState(150); // XXX
  1969.             shs = ZERO;
  1970.             dhs = ZERO;
  1971.             dhd = ZERO;
  1972.             for (int i = 0; i < n; i++) {
  1973.                 if (xbdi.getEntry(i) == ZERO) {
  1974.                     shs += s.getEntry(i) * hs.getEntry(i);
  1975.                     dhs += trialStepPoint.getEntry(i) * hs.getEntry(i);
  1976.                     dhd += trialStepPoint.getEntry(i) * hred.getEntry(i);
  1977.                 }
  1978.             }

  1979.             // Seek the greatest reduction in Q for a range of equally spaced values
  1980.             // of ANGT in [0,ANGBD], where ANGT is the tangent of half the angle of
  1981.             // the alternative iteration.

  1982.             redmax = ZERO;
  1983.             isav = -1;
  1984.             redsav = ZERO;
  1985.             iu = (int) (angbd * 17. + 3.1);
  1986.             for (int i = 0; i < iu; i++) {
  1987.                 angt = angbd * i / iu;
  1988.                 sth = (angt + angt) / (ONE + angt * angt);
  1989.                 temp = shs + angt * (angt * dhd - dhs - dhs);
  1990.                 rednew = sth * (angt * dredg - sredg - HALF * sth * temp);
  1991.                 if (rednew > redmax) {
  1992.                     redmax = rednew;
  1993.                     isav = i;
  1994.                     rdprev = redsav;
  1995.                 } else if (i == isav + 1) {
  1996.                     rdnext = rednew;
  1997.                 }
  1998.                 redsav = rednew;
  1999.             }

  2000.             // Return if the reduction is zero. Otherwise, set the sine and cosine
  2001.             // of the angle of the alternative iteration, and calculate SDEC.

  2002.             if (isav < 0) {
  2003.                 state = 190; break;
  2004.             }
  2005.             if (isav < iu) {
  2006.                 temp = (rdnext - rdprev) / (redmax + redmax - rdprev - rdnext);
  2007.                 angt = angbd * (isav + HALF * temp) / iu;
  2008.             }
  2009.             cth = (ONE - angt * angt) / (ONE + angt * angt);
  2010.             sth = (angt + angt) / (ONE + angt * angt);
  2011.             temp = shs + angt * (angt * dhd - dhs - dhs);
  2012.             sdec = sth * (angt * dredg - sredg - HALF * sth * temp);
  2013.             if (sdec <= ZERO) {
  2014.                 state = 190; break;
  2015.             }

  2016.             // Update GNEW, D and HRED. If the angle of the alternative iteration
  2017.             // is restricted by a bound on a free variable, that variable is fixed
  2018.             // at the bound.

  2019.             dredg = ZERO;
  2020.             gredsq = ZERO;
  2021.             for (int i = 0; i < n; i++) {
  2022.                 gnew.setEntry(i, gnew.getEntry(i) + (cth - ONE) * hred.getEntry(i) + sth * hs.getEntry(i));
  2023.                 if (xbdi.getEntry(i) == ZERO) {
  2024.                     trialStepPoint.setEntry(i, cth * trialStepPoint.getEntry(i) + sth * s.getEntry(i));
  2025.                     dredg += trialStepPoint.getEntry(i) * gnew.getEntry(i);
  2026.                     // Computing 2nd power
  2027.                     final double d1 = gnew.getEntry(i);
  2028.                     gredsq += d1 * d1;
  2029.                 }
  2030.                 hred.setEntry(i, cth * hred.getEntry(i) + sth * hs.getEntry(i));
  2031.             }
  2032.             qred += sdec;
  2033.             if (iact >= 0 && isav == iu) {
  2034.                 ++nact;
  2035.                 xbdi.setEntry(iact, xsav);
  2036.                 state = 100; break;
  2037.             }

  2038.             // If SDEC is sufficiently small, then RETURN after setting XNEW to
  2039.             // XOPT+D, giving careful attention to the bounds.

  2040.             if (sdec > qred * .01) {
  2041.                 state = 120; break;
  2042.             }
  2043.         }
  2044.         case 190: {
  2045.             printState(190); // XXX
  2046.             dsq = ZERO;
  2047.             for (int i = 0; i < n; i++) {
  2048.                 // Computing MAX
  2049.                 // Computing MIN
  2050.                 final double min = FastMath.min(trustRegionCenterOffset.getEntry(i) + trialStepPoint.getEntry(i),
  2051.                                                 upperDifference.getEntry(i));
  2052.                 newPoint.setEntry(i, FastMath.max(min, lowerDifference.getEntry(i)));
  2053.                 if (xbdi.getEntry(i) == MINUS_ONE) {
  2054.                     newPoint.setEntry(i, lowerDifference.getEntry(i));
  2055.                 }
  2056.                 if (xbdi.getEntry(i) == ONE) {
  2057.                     newPoint.setEntry(i, upperDifference.getEntry(i));
  2058.                 }
  2059.                 trialStepPoint.setEntry(i, newPoint.getEntry(i) - trustRegionCenterOffset.getEntry(i));
  2060.                 // Computing 2nd power
  2061.                 final double d1 = trialStepPoint.getEntry(i);
  2062.                 dsq += d1 * d1;
  2063.             }
  2064.             return new double[] { dsq, crvmin };
  2065.             // The following instructions multiply the current S-vector by the second
  2066.             // derivative matrix of the quadratic model, putting the product in HS.
  2067.             // They are reached from three different parts of the software above and
  2068.             // they can be regarded as an external subroutine.
  2069.         }
  2070.         case 210: {
  2071.             printState(210); // XXX
  2072.             int ih = 0;
  2073.             for (int j = 0; j < n; j++) {
  2074.                 hs.setEntry(j, ZERO);
  2075.                 for (int i = 0; i <= j; i++) {
  2076.                     if (i < j) {
  2077.                         hs.setEntry(j, hs.getEntry(j) + modelSecondDerivativesValues.getEntry(ih) * s.getEntry(i));
  2078.                     }
  2079.                     hs.setEntry(i, hs.getEntry(i) + modelSecondDerivativesValues.getEntry(ih) * s.getEntry(j));
  2080.                     ih++;
  2081.                 }
  2082.             }
  2083.             final RealVector tmp = interpolationPoints.operate(s).ebeMultiply(modelSecondDerivativesParameters);
  2084.             for (int k = 0; k < npt; k++) {
  2085.                 if (modelSecondDerivativesParameters.getEntry(k) != ZERO) {
  2086.                     for (int i = 0; i < n; i++) {
  2087.                         hs.setEntry(i, hs.getEntry(i) + tmp.getEntry(k) * interpolationPoints.getEntry(k, i));
  2088.                     }
  2089.                 }
  2090.             }
  2091.             if (crvmin != ZERO) {
  2092.                 state = 50; break;
  2093.             }
  2094.             if (iterc > itcsav) {
  2095.                 state = 150; break;
  2096.             }
  2097.             for (int i = 0; i < n; i++) {
  2098.                 hred.setEntry(i, hs.getEntry(i));
  2099.             }
  2100.             state = 120; break;
  2101.         }
  2102.         default: {
  2103.             throw new MathIllegalStateException(LocalizedFormats.SIMPLE_MESSAGE, "trsbox");
  2104.         }}
  2105.         }
  2106.     } // trsbox

  2107.     // ----------------------------------------------------------------------------------------

  2108.     /**
  2109.      *     The arrays BMAT and ZMAT are updated, as required by the new position
  2110.      *     of the interpolation point that has the index KNEW. The vector VLAG has
  2111.      *     N+NPT components, set on entry to the first NPT and last N components
  2112.      *     of the product Hw in equation (4.11) of the Powell (2006) paper on
  2113.      *     NEWUOA. Further, BETA is set on entry to the value of the parameter
  2114.      *     with that name, and DENOM is set to the denominator of the updating
  2115.      *     formula. Elements of ZMAT may be treated as zero if their moduli are
  2116.      *     at most ZTEST. The first NDIM elements of W are used for working space.
  2117.      * @param beta
  2118.      * @param denom
  2119.      * @param knew
  2120.      */
  2121.     private void update(
  2122.             double beta,
  2123.             double denom,
  2124.             int knew
  2125.     ) {
  2126.         printMethod(); // XXX

  2127.         final int n = currentBest.getDimension();
  2128.         final int npt = numberOfInterpolationPoints;
  2129.         final int nptm = npt - n - 1;

  2130.         // XXX Should probably be split into two arrays.
  2131.         final ArrayRealVector work = new ArrayRealVector(npt + n);

  2132.         double ztest = ZERO;
  2133.         for (int k = 0; k < npt; k++) {
  2134.             for (int j = 0; j < nptm; j++) {
  2135.                 // Computing MAX
  2136.                 ztest = FastMath.max(ztest, FastMath.abs(zMatrix.getEntry(k, j)));
  2137.             }
  2138.         }
  2139.         ztest *= 1e-20;

  2140.         // Apply the rotations that put zeros in the KNEW-th row of ZMAT.

  2141.         for (int j = 1; j < nptm; j++) {
  2142.             final double d1 = zMatrix.getEntry(knew, j);
  2143.             if (FastMath.abs(d1) > ztest) {
  2144.                 // Computing 2nd power
  2145.                 final double d2 = zMatrix.getEntry(knew, 0);
  2146.                 // Computing 2nd power
  2147.                 final double d3 = zMatrix.getEntry(knew, j);
  2148.                 final double d4 = FastMath.sqrt(d2 * d2 + d3 * d3);
  2149.                 final double d5 = zMatrix.getEntry(knew, 0) / d4;
  2150.                 final double d6 = zMatrix.getEntry(knew, j) / d4;
  2151.                 for (int i = 0; i < npt; i++) {
  2152.                     final double d7 = d5 * zMatrix.getEntry(i, 0) + d6 * zMatrix.getEntry(i, j);
  2153.                     zMatrix.setEntry(i, j, d5 * zMatrix.getEntry(i, j) - d6 * zMatrix.getEntry(i, 0));
  2154.                     zMatrix.setEntry(i, 0, d7);
  2155.                 }
  2156.             }
  2157.             zMatrix.setEntry(knew, j, ZERO);
  2158.         }

  2159.         // Put the first NPT components of the KNEW-th column of HLAG into W,
  2160.         // and calculate the parameters of the updating formula.

  2161.         for (int i = 0; i < npt; i++) {
  2162.             work.setEntry(i, zMatrix.getEntry(knew, 0) * zMatrix.getEntry(i, 0));
  2163.         }
  2164.         final double alpha = work.getEntry(knew);
  2165.         final double tau = lagrangeValuesAtNewPoint.getEntry(knew);
  2166.         lagrangeValuesAtNewPoint.setEntry(knew, lagrangeValuesAtNewPoint.getEntry(knew) - ONE);

  2167.         // Complete the updating of ZMAT.

  2168.         final double sqrtDenom = FastMath.sqrt(denom);
  2169.         final double d1 = tau / sqrtDenom;
  2170.         final double d2 = zMatrix.getEntry(knew, 0) / sqrtDenom;
  2171.         for (int i = 0; i < npt; i++) {
  2172.             zMatrix.setEntry(i, 0,
  2173.                           d1 * zMatrix.getEntry(i, 0) - d2 * lagrangeValuesAtNewPoint.getEntry(i));
  2174.         }

  2175.         // Finally, update the matrix BMAT.

  2176.         for (int j = 0; j < n; j++) {
  2177.             final int jp = npt + j;
  2178.             work.setEntry(jp, bMatrix.getEntry(knew, j));
  2179.             final double d3 = (alpha * lagrangeValuesAtNewPoint.getEntry(jp) - tau * work.getEntry(jp)) / denom;
  2180.             final double d4 = (-beta * work.getEntry(jp) - tau * lagrangeValuesAtNewPoint.getEntry(jp)) / denom;
  2181.             for (int i = 0; i <= jp; i++) {
  2182.                 bMatrix.setEntry(i, j,
  2183.                               bMatrix.getEntry(i, j) + d3 * lagrangeValuesAtNewPoint.getEntry(i) + d4 * work.getEntry(i));
  2184.                 if (i >= npt) {
  2185.                     bMatrix.setEntry(jp, (i - npt), bMatrix.getEntry(i, j));
  2186.                 }
  2187.             }
  2188.         }
  2189.     } // update

  2190.     /**
  2191.      * Performs validity checks.
  2192.      *
  2193.      * @param lowerBound Lower bounds (constraints) of the objective variables.
  2194.      * @param upperBound Upperer bounds (constraints) of the objective variables.
  2195.      */
  2196.     private void setup(double[] lowerBound,
  2197.                        double[] upperBound) {
  2198.         printMethod(); // XXX

  2199.         double[] init = getStartPoint();
  2200.         final int dimension = init.length;

  2201.         // Check problem dimension.
  2202.         if (dimension < MINIMUM_PROBLEM_DIMENSION) {
  2203.             throw new NumberIsTooSmallException(dimension, MINIMUM_PROBLEM_DIMENSION, true);
  2204.         }
  2205.         // Check number of interpolation points.
  2206.         final int[] nPointsInterval = { dimension + 2, (dimension + 2) * (dimension + 1) / 2 };
  2207.         if (numberOfInterpolationPoints < nPointsInterval[0] ||
  2208.             numberOfInterpolationPoints > nPointsInterval[1]) {
  2209.             throw new OutOfRangeException(LocalizedFormats.NUMBER_OF_INTERPOLATION_POINTS,
  2210.                                           numberOfInterpolationPoints,
  2211.                                           nPointsInterval[0],
  2212.                                           nPointsInterval[1]);
  2213.         }

  2214.         // Initialize bound differences.
  2215.         boundDifference = new double[dimension];

  2216.         double requiredMinDiff = 2 * initialTrustRegionRadius;
  2217.         double minDiff = Double.POSITIVE_INFINITY;
  2218.         for (int i = 0; i < dimension; i++) {
  2219.             boundDifference[i] = upperBound[i] - lowerBound[i];
  2220.             minDiff = FastMath.min(minDiff, boundDifference[i]);
  2221.         }
  2222.         if (minDiff < requiredMinDiff) {
  2223.             initialTrustRegionRadius = minDiff / 3.0;
  2224.         }

  2225.         // Initialize the data structures used by the "bobyqa" method.
  2226.         bMatrix = new Array2DRowRealMatrix(dimension + numberOfInterpolationPoints,
  2227.                                            dimension);
  2228.         zMatrix = new Array2DRowRealMatrix(numberOfInterpolationPoints,
  2229.                                            numberOfInterpolationPoints - dimension - 1);
  2230.         interpolationPoints = new Array2DRowRealMatrix(numberOfInterpolationPoints,
  2231.                                                        dimension);
  2232.         originShift = new ArrayRealVector(dimension);
  2233.         fAtInterpolationPoints = new ArrayRealVector(numberOfInterpolationPoints);
  2234.         trustRegionCenterOffset = new ArrayRealVector(dimension);
  2235.         gradientAtTrustRegionCenter = new ArrayRealVector(dimension);
  2236.         lowerDifference = new ArrayRealVector(dimension);
  2237.         upperDifference = new ArrayRealVector(dimension);
  2238.         modelSecondDerivativesParameters = new ArrayRealVector(numberOfInterpolationPoints);
  2239.         newPoint = new ArrayRealVector(dimension);
  2240.         alternativeNewPoint = new ArrayRealVector(dimension);
  2241.         trialStepPoint = new ArrayRealVector(dimension);
  2242.         lagrangeValuesAtNewPoint = new ArrayRealVector(dimension + numberOfInterpolationPoints);
  2243.         modelSecondDerivativesValues = new ArrayRealVector(dimension * (dimension + 1) / 2);
  2244.     }

  2245.     // XXX utility for figuring out call sequence.
  2246.     private static String caller(int n) {
  2247.         final Throwable t = new Throwable();
  2248.         final StackTraceElement[] elements = t.getStackTrace();
  2249.         final StackTraceElement e = elements[n];
  2250.         return e.getMethodName() + " (at line " + e.getLineNumber() + ")";
  2251.     }
  2252.     // XXX utility for figuring out call sequence.
  2253.     private static void printState(int s) {
  2254.         //        System.out.println(caller(2) + ": state " + s);
  2255.     }
  2256.     // XXX utility for figuring out call sequence.
  2257.     private static void printMethod() {
  2258.         //        System.out.println(caller(2));
  2259.     }

  2260.     /**
  2261.      * Marker for code paths that are not explored with the current unit tests.
  2262.      * If the path becomes explored, it should just be removed from the code.
  2263.      */
  2264.     private static class PathIsExploredException extends RuntimeException {
  2265.         private static final long serialVersionUID = 745350979634801853L;

  2266.         private static final String PATH_IS_EXPLORED
  2267.             = "If this exception is thrown, just remove it from the code";

  2268.         PathIsExploredException() {
  2269.             super(PATH_IS_EXPLORED + " " + BOBYQAOptimizer.caller(3));
  2270.         }
  2271.     }
  2272. }
  2273. //CHECKSTYLE: resume all