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.optim.nonlinear.scalar.noderiv;

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

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

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

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

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

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

  222.     /** {@inheritDoc} */
  223.     @Override
  224.     protected PointValuePair doOptimize() {
  225.         final double[] lowerBound = getLowerBound();
  226.         final double[] upperBound = getUpperBound();

  227.         // Validity checks.
  228.         setup(lowerBound, upperBound);

  229.         isMinimize = (getGoalType() == GoalType.MINIMIZE);
  230.         currentBest = new ArrayRealVector(getStartPoint());

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

  232.         return new PointValuePair(currentBest.getDataRef(),
  233.                                   isMinimize ? value : -value);
  234.     }

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

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

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

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

  311.         // Make the call of BOBYQB.

  312.         return bobyqb(lowerBound, upperBound);
  313.     } // bobyqa

  314.     // ----------------------------------------------------------------------------------------

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

  355.         final int n = currentBest.getDimension();
  356.         final int npt = numberOfInterpolationPoints;
  357.         final int np = n + 1;
  358.         final int nptm = npt - np;
  359.         final int nh = n * np / 2;

  360.         final ArrayRealVector work1 = new ArrayRealVector(n);
  361.         final ArrayRealVector work2 = new ArrayRealVector(npt);
  362.         final ArrayRealVector work3 = new ArrayRealVector(npt);

  363.         double cauchy = Double.NaN;
  364.         double alpha = Double.NaN;
  365.         double dsq = Double.NaN;
  366.         double crvmin = Double.NaN;

  367.         // Set some constants.
  368.         // Parameter adjustments

  369.         // Function Body

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

  376.         trustRegionCenterInterpolationPointIndex = 0;

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

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

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

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

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

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

  443.         }
  444.         case 60: {
  445.             printState(60); // XXX
  446.             final ArrayRealVector gnew = new ArrayRealVector(n);
  447.             final ArrayRealVector xbdi = new ArrayRealVector(n);
  448.             final ArrayRealVector s = new ArrayRealVector(n);
  449.             final ArrayRealVector hs = new ArrayRealVector(n);
  450.             final ArrayRealVector hred = new ArrayRealVector(n);

  451.             final double[] dsqCrvmin = trsbox(delta, gnew, xbdi, s,
  452.                                               hs, hred);
  453.             dsq = dsqCrvmin[0];
  454.             crvmin = dsqCrvmin[1];

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

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

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

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

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

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

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

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

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

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

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

  623.             final double[] alphaCauchy = altmov(knew, adelt);
  624.             alpha = alphaCauchy[0];
  625.             cauchy = alphaCauchy[1];

  626.             for (int i = 0; i < n; i++) {
  627.                 trialStepPoint.setEntry(i, newPoint.getEntry(i) - trustRegionCenterOffset.getEntry(i));
  628.             }

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

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

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

  682.             lagrangeValuesAtNewPoint.setEntry(trustRegionCenterInterpolationPointIndex,
  683.                           lagrangeValuesAtNewPoint.getEntry(trustRegionCenterInterpolationPointIndex) + ONE);

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

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

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

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

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

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

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

  766.             if (!isMinimize)
  767.                 f = -f;
  768.             if (ntrits == -1) {
  769.                 fsave = f;
  770.                 state = 720; break;
  771.             }

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

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

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

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

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

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

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

  868.             update(beta, denom, knew);

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

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

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

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

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

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

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

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

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

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

  1019.             if (ntrits == 0) {
  1020.                 state = 60; break;
  1021.             }
  1022.             if (f <= fopt + ONE_OVER_TEN * vquad) {
  1023.                 state = 60; break;
  1024.             }

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

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

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

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

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

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

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

  1132.     // ----------------------------------------------------------------------------------------

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

  1171.         final int n = currentBest.getDimension();
  1172.         final int npt = numberOfInterpolationPoints;

  1173.         final ArrayRealVector glag = new ArrayRealVector(n);
  1174.         final ArrayRealVector hcol = new ArrayRealVector(npt);

  1175.         final ArrayRealVector work1 = new ArrayRealVector(n);
  1176.         final ArrayRealVector work2 = new ArrayRealVector(n);

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

  1437.         return new double[] { alpha, cauchy };
  1438.     } // altmov

  1439.     // ----------------------------------------------------------------------------------------

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

  1463.         final int n = currentBest.getDimension();
  1464.         final int npt = numberOfInterpolationPoints;
  1465.         final int ndim = bMatrix.getRowDimension();

  1466.         final double rhosq = initialTrustRegionRadius * initialTrustRegionRadius;
  1467.         final double recip = 1d / rhosq;
  1468.         final int np = n + 1;

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

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

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

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

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

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

  1552.             final double objectiveValue = computeObjectiveValue(currentBest.toArray());
  1553.             final double f = isMinimize ? objectiveValue : -objectiveValue;
  1554.             final int numEval = getEvaluations(); // nfm + 1
  1555.             fAtInterpolationPoints.setEntry(nfm, f);

  1556.             if (numEval == 1) {
  1557.                 fbeg = f;
  1558.                 trustRegionCenterInterpolationPointIndex = 0;
  1559.             } else if (f < fAtInterpolationPoints.getEntry(trustRegionCenterInterpolationPointIndex)) {
  1560.                 trustRegionCenterInterpolationPointIndex = nfm;
  1561.             }

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

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

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

  1605.             } else {
  1606.                 zMatrix.setEntry(0, nfxm, recip);
  1607.                 zMatrix.setEntry(nfm, nfxm, recip);
  1608.                 zMatrix.setEntry(ipt, nfxm, -recip);
  1609.                 zMatrix.setEntry(jpt, nfxm, -recip);

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


  1617.     // ----------------------------------------------------------------------------------------

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

  1671.         final int n = currentBest.getDimension();
  1672.         final int npt = numberOfInterpolationPoints;

  1673.         double dsq = Double.NaN;
  1674.         double crvmin = Double.NaN;

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

  1690.         // Set some constants.

  1691.         // Function Body

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

  2103.     // ----------------------------------------------------------------------------------------

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

  2123.         final int n = currentBest.getDimension();
  2124.         final int npt = numberOfInterpolationPoints;
  2125.         final int nptm = npt - n - 1;

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

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

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

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

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

  2157.         for (int i = 0; i < npt; i++) {
  2158.             work.setEntry(i, zMatrix.getEntry(knew, 0) * zMatrix.getEntry(i, 0));
  2159.         }
  2160.         final double alpha = work.getEntry(knew);
  2161.         final double tau = lagrangeValuesAtNewPoint.getEntry(knew);
  2162.         lagrangeValuesAtNewPoint.setEntry(knew, lagrangeValuesAtNewPoint.getEntry(knew) - ONE);

  2163.         // Complete the updating of ZMAT.

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

  2171.         // Finally, update the matrix BMAT.

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

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

  2195.         double[] init = getStartPoint();
  2196.         final int dimension = init.length;

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

  2210.         // Initialize bound differences.
  2211.         boundDifference = new double[dimension];

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

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

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

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

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

  2264.         PathIsExploredException() {
  2265.             super(PATH_IS_EXPLORED + " " + BOBYQAOptimizer.caller(3));
  2266.         }
  2267.     }
  2268. }
  2269. //CHECKSTYLE: resume all