BOBYQAOptimizer.java

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

  17. /*
  18.  * This is not the original file distributed by the Apache Software Foundation
  19.  * It has been modified by the Hipparchus project
  20.  */
  21. // CHECKSTYLE: stop all
  22. package org.hipparchus.optim.nonlinear.scalar.noderiv;

  23. import org.hipparchus.exception.LocalizedCoreFormats;
  24. import org.hipparchus.exception.MathIllegalArgumentException;
  25. import org.hipparchus.exception.MathIllegalStateException;
  26. import org.hipparchus.linear.Array2DRowRealMatrix;
  27. import org.hipparchus.linear.ArrayRealVector;
  28. import org.hipparchus.linear.RealVector;
  29. import org.hipparchus.optim.LocalizedOptimFormats;
  30. import org.hipparchus.optim.PointValuePair;
  31. import org.hipparchus.optim.nonlinear.scalar.GoalType;
  32. import org.hipparchus.optim.nonlinear.scalar.MultivariateOptimizer;
  33. import org.hipparchus.util.FastMath;

  34. /**
  35.  * Powell's BOBYQA algorithm. This implementation is translated and
  36.  * adapted from the Fortran version available
  37.  * <a href="http://plato.asu.edu/ftp/other_software/bobyqa.zip">here</a>.
  38.  * See <a href="http://www.optimization-online.org/DB_HTML/2010/05/2616.html">
  39.  * this paper</a> for an introduction.
  40.  * <br>
  41.  * BOBYQA is particularly well suited for high dimensional problems
  42.  * where derivatives are not available. In most cases it outperforms the
  43.  * {@link PowellOptimizer} significantly. Stochastic algorithms like
  44.  * {@link CMAESOptimizer} succeed more often than BOBYQA, but are more
  45.  * expensive. BOBYQA could also be considered as a replacement of any
  46.  * derivative-based optimizer when the derivatives are approximated by
  47.  * finite differences.
  48.  *
  49.  */
  50. public class BOBYQAOptimizer
  51.     extends MultivariateOptimizer {
  52.     /** Minimum dimension of the problem: {@value} */
  53.     public static final int MINIMUM_PROBLEM_DIMENSION = 2;
  54.     /** Default value for {@link #initialTrustRegionRadius}: {@value} . */
  55.     public static final double DEFAULT_INITIAL_RADIUS = 10.0;
  56.     /** Default value for {@link #stoppingTrustRegionRadius}: {@value} . */
  57.     public static final double DEFAULT_STOPPING_RADIUS = 1E-8;
  58.     /** Constant 0. */
  59.     private static final double ZERO = 0d;
  60.     /** Constant 1. */
  61.     private static final double ONE = 1d;
  62.     /** Constant 2. */
  63.     private static final double TWO = 2d;
  64.     /** Constant 10. */
  65.     private static final double TEN = 10d;
  66.     /** Constant 16. */
  67.     private static final double SIXTEEN = 16d;
  68.     /** Constant 250. */
  69.     private static final double TWO_HUNDRED_FIFTY = 250d;
  70.     /** Constant -1. */
  71.     private static final double MINUS_ONE = -ONE;
  72.     /** Constant 1/2. */
  73.     private static final double HALF = ONE / 2;
  74.     /** Constant 1/4. */
  75.     private static final double ONE_OVER_FOUR = ONE / 4;
  76.     /** Constant 1/8. */
  77.     private static final double ONE_OVER_EIGHT = ONE / 8;
  78.     /** Constant 1/10. */
  79.     private static final double ONE_OVER_TEN = ONE / 10;
  80.     /** Constant 1/1000. */
  81.     private static final double ONE_OVER_A_THOUSAND = ONE / 1000;

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

  210.     /** Simple constructor.
  211.      * @param numberOfInterpolationPoints Number of interpolation conditions.
  212.      * For a problem of dimension {@code n}, its value must be in the interval
  213.      * {@code [n+2, (n+1)(n+2)/2]}.
  214.      * Choices that exceed {@code 2n+1} are not recommended.
  215.      */
  216.     public BOBYQAOptimizer(int numberOfInterpolationPoints) {
  217.         this(numberOfInterpolationPoints,
  218.              DEFAULT_INITIAL_RADIUS,
  219.              DEFAULT_STOPPING_RADIUS);
  220.     }

  221.     /** Simple constructor.
  222.      * @param numberOfInterpolationPoints Number of interpolation conditions.
  223.      * For a problem of dimension {@code n}, its value must be in the interval
  224.      * {@code [n+2, (n+1)(n+2)/2]}.
  225.      * Choices that exceed {@code 2n+1} are not recommended.
  226.      * @param initialTrustRegionRadius Initial trust region radius.
  227.      * @param stoppingTrustRegionRadius Stopping trust region radius.
  228.      */
  229.     public BOBYQAOptimizer(int numberOfInterpolationPoints,
  230.                            double initialTrustRegionRadius,
  231.                            double stoppingTrustRegionRadius) {
  232.         super(null); // No custom convergence criterion.
  233.         this.numberOfInterpolationPoints = numberOfInterpolationPoints;
  234.         this.initialTrustRegionRadius = initialTrustRegionRadius;
  235.         this.stoppingTrustRegionRadius = stoppingTrustRegionRadius;
  236.     }

  237.     /** {@inheritDoc} */
  238.     @Override
  239.     protected PointValuePair doOptimize() {
  240.         final double[] lowerBound = getLowerBound();
  241.         final double[] upperBound = getUpperBound();

  242.         // Validity checks.
  243.         setup(lowerBound, upperBound);

  244.         isMinimize = (getGoalType() == GoalType.MINIMIZE);
  245.         currentBest = new ArrayRealVector(getStartPoint());

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

  247.         return new PointValuePair(currentBest.getDataRef(),
  248.                                   isMinimize ? value : -value);
  249.     }

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

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

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

  294.         for (int j = 0; j < n; j++) {
  295.             final double boundDiff = boundDifference[j];
  296.             lowerDifference.setEntry(j, lowerBound[j] - currentBest.getEntry(j));
  297.             upperDifference.setEntry(j, upperBound[j] - currentBest.getEntry(j));
  298.             if (lowerDifference.getEntry(j) >= -initialTrustRegionRadius) {
  299.                 if (lowerDifference.getEntry(j) >= ZERO) {
  300.                     currentBest.setEntry(j, lowerBound[j]);
  301.                     lowerDifference.setEntry(j, ZERO);
  302.                     upperDifference.setEntry(j, boundDiff);
  303.                 } else {
  304.                     currentBest.setEntry(j, lowerBound[j] + initialTrustRegionRadius);
  305.                     lowerDifference.setEntry(j, -initialTrustRegionRadius);
  306.                     // Computing MAX
  307.                     final double deltaOne = upperBound[j] - currentBest.getEntry(j);
  308.                     upperDifference.setEntry(j, FastMath.max(deltaOne, initialTrustRegionRadius));
  309.                 }
  310.             } else if (upperDifference.getEntry(j) <= initialTrustRegionRadius) {
  311.                 if (upperDifference.getEntry(j) <= ZERO) {
  312.                     currentBest.setEntry(j, upperBound[j]);
  313.                     lowerDifference.setEntry(j, -boundDiff);
  314.                     upperDifference.setEntry(j, ZERO);
  315.                 } else {
  316.                     currentBest.setEntry(j, upperBound[j] - initialTrustRegionRadius);
  317.                     // Computing MIN
  318.                     final double deltaOne = lowerBound[j] - currentBest.getEntry(j);
  319.                     final double deltaTwo = -initialTrustRegionRadius;
  320.                     lowerDifference.setEntry(j, FastMath.min(deltaOne, deltaTwo));
  321.                     upperDifference.setEntry(j, initialTrustRegionRadius);
  322.                 }
  323.             }
  324.         }

  325.         // Make the call of BOBYQB.

  326.         return bobyqb(lowerBound, upperBound);
  327.     } // bobyqa

  328.     // ----------------------------------------------------------------------------------------

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

  368.         final int n = currentBest.getDimension();
  369.         final int npt = numberOfInterpolationPoints;
  370.         final int np = n + 1;
  371.         final int nptm = npt - np;
  372.         final int nh = n * np / 2;

  373.         final ArrayRealVector work1 = new ArrayRealVector(n);
  374.         final ArrayRealVector work2 = new ArrayRealVector(npt);
  375.         final ArrayRealVector work3 = new ArrayRealVector(npt);

  376.         double cauchy = Double.NaN;
  377.         double alpha = Double.NaN;
  378.         double dsq = Double.NaN;
  379.         double crvmin;

  380.         // Set some constants.
  381.         // Parameter adjustments

  382.         // Function Body

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

  389.         trustRegionCenterInterpolationPointIndex = 0;

  390.         prelim(lowerBound, upperBound);
  391.         double xoptsq = ZERO;
  392.         for (int i = 0; i < n; i++) {
  393.             trustRegionCenterOffset.setEntry(i, interpolationPoints.getEntry(trustRegionCenterInterpolationPointIndex, i));
  394.             // Computing 2nd power
  395.             final double deltaOne = trustRegionCenterOffset.getEntry(i);
  396.             xoptsq += deltaOne * deltaOne;
  397.         }
  398.         double fsave = fAtInterpolationPoints.getEntry(0);
  399.         final int kbase = 0;

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

  401.         int ntrits = 0;
  402.         int itest = 0;
  403.         int knew = 0;
  404.         int nfsav = getEvaluations();
  405.         double rho = initialTrustRegionRadius;
  406.         double delta = rho;
  407.         double diffa = ZERO;
  408.         double diffb = ZERO;
  409.         double diffc = ZERO;
  410.         double f = ZERO;
  411.         double beta = ZERO;
  412.         double adelt = ZERO;
  413.         double denom = ZERO;
  414.         double ratio = ZERO;
  415.         double dnorm = ZERO;
  416.         double scaden;
  417.         double biglsq;
  418.         double distsq = ZERO;

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

  421.         int state = 20;
  422.         for(;;) {
  423.         switch (state) { // NOPMD - the reference algorithm is as complex as this, we simply ported it from Fortran with minimal changes
  424.         case 20: {
  425.             if (trustRegionCenterInterpolationPointIndex != kbase) {
  426.                 int ih = 0;
  427.                 for (int j = 0; j < n; j++) {
  428.                     for (int i = 0; i <= j; i++) {
  429.                         if (i < j) {
  430.                             gradientAtTrustRegionCenter.setEntry(j, gradientAtTrustRegionCenter.getEntry(j) + modelSecondDerivativesValues.getEntry(ih) * trustRegionCenterOffset.getEntry(i));
  431.                         }
  432.                         gradientAtTrustRegionCenter.setEntry(i, gradientAtTrustRegionCenter.getEntry(i) + modelSecondDerivativesValues.getEntry(ih) * trustRegionCenterOffset.getEntry(j));
  433.                         ih++;
  434.                     }
  435.                 }
  436.                 if (getEvaluations() > npt) {
  437.                     for (int k = 0; k < npt; k++) {
  438.                         double temp = ZERO;
  439.                         for (int j = 0; j < n; j++) {
  440.                             temp += interpolationPoints.getEntry(k, j) * trustRegionCenterOffset.getEntry(j);
  441.                         }
  442.                         temp *= modelSecondDerivativesParameters.getEntry(k);
  443.                         for (int i = 0; i < n; i++) {
  444.                             gradientAtTrustRegionCenter.setEntry(i, gradientAtTrustRegionCenter.getEntry(i) + temp * interpolationPoints.getEntry(k, i));
  445.                         }
  446.                     }
  447.                     // throw new PathIsExploredException(); // XXX
  448.                 }
  449.             }

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

  456.         }
  457.         case 60: { // NOPMD
  458.             final ArrayRealVector gnew = new ArrayRealVector(n);
  459.             final ArrayRealVector xbdi = new ArrayRealVector(n);
  460.             final ArrayRealVector s = new ArrayRealVector(n);
  461.             final ArrayRealVector hs = new ArrayRealVector(n);
  462.             final ArrayRealVector hred = new ArrayRealVector(n);

  463.             final double[] dsqCrvmin = trsbox(delta, gnew, xbdi, s,
  464.                                               hs, hred);
  465.             dsq = dsqCrvmin[0];
  466.             crvmin = dsqCrvmin[1];

  467.             // Computing MIN
  468.             double deltaOne = delta;
  469.             double deltaTwo = FastMath.sqrt(dsq);
  470.             dnorm = FastMath.min(deltaOne, deltaTwo);
  471.             if (dnorm < HALF * rho) {
  472.                 ntrits = -1;
  473.                 // Computing 2nd power
  474.                 deltaOne = TEN * rho;
  475.                 distsq = deltaOne * deltaOne;
  476.                 if (getEvaluations() <= nfsav + 2) {
  477.                     state = 650; break;
  478.                 }

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

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

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

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

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

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

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

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

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

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

  633.             final double[] alphaCauchy = altmov(knew, adelt);
  634.             alpha = alphaCauchy[0];
  635.             cauchy = alphaCauchy[1];

  636.             for (int i = 0; i < n; i++) {
  637.                 trialStepPoint.setEntry(i, newPoint.getEntry(i) - trustRegionCenterOffset.getEntry(i));
  638.             }

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

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

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

  691.             lagrangeValuesAtNewPoint.setEntry(trustRegionCenterInterpolationPointIndex,
  692.                           lagrangeValuesAtNewPoint.getEntry(trustRegionCenterInterpolationPointIndex) + ONE);

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

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

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

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

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

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

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

  774.             if (!isMinimize) {
  775.                 f = -f;
  776.             }
  777.             if (ntrits == -1) {
  778.                 fsave = f;
  779.                 state = 720; break;
  780.             }

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

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

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

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

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

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

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

  877.             update(beta, denom, knew);

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

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

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

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

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

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

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

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

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

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

  1029.             if (ntrits == 0) {
  1030.                 state = 60; break;
  1031.             }
  1032.             if (f <= fopt + ONE_OVER_TEN * vquad) {
  1033.                 state = 60; break;
  1034.             }

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

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

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

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

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

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

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

  1139.     // ----------------------------------------------------------------------------------------

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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


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

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

  1673.         final int n = currentBest.getDimension();
  1674.         final int npt = numberOfInterpolationPoints;

  1675.         double dsq;
  1676.         double crvmin;

  1677.         // Local variables
  1678.         double dhd;
  1679.         double dhs;
  1680.         double cth;
  1681.         double shs;
  1682.         double sth;
  1683.         double ssq;
  1684.         double beta=0;
  1685.         double sdec;
  1686.         double blen;
  1687.         int iact = -1;
  1688.         double angt = 0;
  1689.         double qred;
  1690.         int isav;
  1691.         double temp;
  1692.         double xsav = 0;
  1693.         double xsum;
  1694.         double angbd = 0;
  1695.         double dredg = 0;
  1696.         double sredg = 0;
  1697.         double resid;
  1698.         double delsq;
  1699.         double ggsav = 0;
  1700.         double tempa;
  1701.         double tempb;
  1702.         double redmax;
  1703.         double dredsq = 0;
  1704.         double redsav;
  1705.         double gredsq = 0;
  1706.         double rednew;
  1707.         int itcsav = 0;
  1708.         double rdprev = 0;
  1709.         double rdnext = 0;
  1710.         double stplen;
  1711.         double stepsq = 0;
  1712.         int itermax = 0;

  1713.         // Set some constants.

  1714.         // Function Body

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

  1721.         int iterc = 0;
  1722.         int nact = 0;
  1723.         for (int i = 0; i < n; i++) {
  1724.             xbdi.setEntry(i, ZERO);
  1725.             if (trustRegionCenterOffset.getEntry(i) <= lowerDifference.getEntry(i)) {
  1726.                 if (gradientAtTrustRegionCenter.getEntry(i) >= ZERO) {
  1727.                     xbdi.setEntry(i, MINUS_ONE);
  1728.                 }
  1729.             } else if (trustRegionCenterOffset.getEntry(i) >= upperDifference.getEntry(i) &&
  1730.                     gradientAtTrustRegionCenter.getEntry(i) <= ZERO) {
  1731.                 xbdi.setEntry(i, ONE);
  1732.             }
  1733.             if (xbdi.getEntry(i) != ZERO) {
  1734.                 ++nact;
  1735.             }
  1736.             trialStepPoint.setEntry(i, ZERO);
  1737.             gnew.setEntry(i, gradientAtTrustRegionCenter.getEntry(i));
  1738.         }
  1739.         delsq = delta * delta;
  1740.         qred = ZERO;
  1741.         crvmin = MINUS_ONE;

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

  1747.         int state = 20;
  1748.         for(;;) {
  1749.             switch (state) { // NOPMD - the reference algorithm is as complex as this, we simply ported it from Fortran with minimal changes
  1750.         case 20: {
  1751.             beta = ZERO;
  1752.         }
  1753.         case 30: { // NOPMD
  1754.             stepsq = ZERO;
  1755.             for (int i = 0; i < n; i++) {
  1756.                 if (xbdi.getEntry(i) != ZERO) {
  1757.                     s.setEntry(i, ZERO);
  1758.                 } else if (beta == ZERO) {
  1759.                     s.setEntry(i, -gnew.getEntry(i));
  1760.                 } else {
  1761.                     s.setEntry(i, beta * s.getEntry(i) - gnew.getEntry(i));
  1762.                 }
  1763.                 // Computing 2nd power
  1764.                 final double d1 = s.getEntry(i);
  1765.                 stepsq += d1 * d1;
  1766.             }
  1767.             if (stepsq == ZERO) {
  1768.                 state = 190; break;
  1769.             }
  1770.             if (beta == ZERO) {
  1771.                 gredsq = stepsq;
  1772.                 itermax = iterc + n - nact;
  1773.             }
  1774.             if (gredsq * delsq <= qred * 1e-4 * qred) {
  1775.                 state = 190; break;
  1776.             }

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

  1781.             state = 210; break;
  1782.         }
  1783.         case 50: {
  1784.             resid = delsq;
  1785.             double ds = ZERO;
  1786.             shs = ZERO;
  1787.             for (int i = 0; i < n; i++) {
  1788.                 if (xbdi.getEntry(i) == ZERO) {
  1789.                     // Computing 2nd power
  1790.                     final double d1 = trialStepPoint.getEntry(i);
  1791.                     resid -= d1 * d1;
  1792.                     ds += s.getEntry(i) * trialStepPoint.getEntry(i);
  1793.                     shs += s.getEntry(i) * hs.getEntry(i);
  1794.                 }
  1795.             }
  1796.             if (resid <= ZERO) {
  1797.                 state = 90; break;
  1798.             }
  1799.             temp = FastMath.sqrt(stepsq * resid + ds * ds);
  1800.             if (ds < ZERO) {
  1801.                 blen = (temp - ds) / stepsq;
  1802.             } else {
  1803.                 blen = resid / (temp + ds);
  1804.             }
  1805.             stplen = blen;
  1806.             if (shs > ZERO) {
  1807.                 // Computing MIN
  1808.                 stplen = FastMath.min(blen, gredsq / shs);
  1809.             }

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

  1812.             iact = -1;
  1813.             for (int i = 0; i < n; i++) {
  1814.                 if (s.getEntry(i) != ZERO) {
  1815.                     xsum = trustRegionCenterOffset.getEntry(i) + trialStepPoint.getEntry(i);
  1816.                     if (s.getEntry(i) > ZERO) {
  1817.                         temp = (upperDifference.getEntry(i) - xsum) / s.getEntry(i);
  1818.                     } else {
  1819.                         temp = (lowerDifference.getEntry(i) - xsum) / s.getEntry(i);
  1820.                     }
  1821.                     if (temp < stplen) {
  1822.                         stplen = temp;
  1823.                         iact = i;
  1824.                     }
  1825.                 }
  1826.             }

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

  1828.             sdec = ZERO;
  1829.             if (stplen > ZERO) {
  1830.                 ++iterc;
  1831.                 temp = shs / stepsq;
  1832.                 if (iact == -1 && temp > ZERO) {
  1833.                     crvmin = FastMath.min(crvmin,temp);
  1834.                     if (crvmin == MINUS_ONE) {
  1835.                         crvmin = temp;
  1836.                     }
  1837.                 }
  1838.                 ggsav = gredsq;
  1839.                 gredsq = ZERO;
  1840.                 for (int i = 0; i < n; i++) {
  1841.                     gnew.setEntry(i, gnew.getEntry(i) + stplen * hs.getEntry(i));
  1842.                     if (xbdi.getEntry(i) == ZERO) {
  1843.                         // Computing 2nd power
  1844.                         final double d1 = gnew.getEntry(i);
  1845.                         gredsq += d1 * d1;
  1846.                     }
  1847.                     trialStepPoint.setEntry(i, trialStepPoint.getEntry(i) + stplen * s.getEntry(i));
  1848.                 }
  1849.                 // Computing MAX
  1850.                 final double d1 = stplen * (ggsav - HALF * stplen * shs);
  1851.                 sdec = FastMath.max(d1, ZERO);
  1852.                 qred += sdec;
  1853.             }

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

  1855.             if (iact >= 0) {
  1856.                 ++nact;
  1857.                 xbdi.setEntry(iact, ONE);
  1858.                 if (s.getEntry(iact) < ZERO) {
  1859.                     xbdi.setEntry(iact, MINUS_ONE);
  1860.                 }
  1861.                 // Computing 2nd power
  1862.                 final double d1 = trialStepPoint.getEntry(iact);
  1863.                 delsq -= d1 * d1;
  1864.                 if (delsq <= ZERO) {
  1865.                     state = 190; break;
  1866.                 }
  1867.                 state = 20; break;
  1868.             }

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

  1871.             if (stplen < blen) {
  1872.                 if (iterc == itermax) {
  1873.                     state = 190; break;
  1874.                 }
  1875.                 if (sdec <= qred * .01) {
  1876.                     state = 190; break;
  1877.                 }
  1878.                 beta = gredsq / ggsav;
  1879.                 state = 30; break;
  1880.             }
  1881.         }
  1882.         case 90: { // NOPMD
  1883.             crvmin = ZERO;

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

  1887.         }
  1888.         case 100: { // NOPMD
  1889.             if (nact >= n - 1) {
  1890.                 state = 190; break;
  1891.             }
  1892.             dredsq = ZERO;
  1893.             dredg = ZERO;
  1894.             gredsq = ZERO;
  1895.             for (int i = 0; i < n; i++) {
  1896.                 if (xbdi.getEntry(i) == ZERO) {
  1897.                     // Computing 2nd power
  1898.                     double d1 = trialStepPoint.getEntry(i);
  1899.                     dredsq += d1 * d1;
  1900.                     dredg += trialStepPoint.getEntry(i) * gnew.getEntry(i);
  1901.                     // Computing 2nd power
  1902.                     d1 = gnew.getEntry(i);
  1903.                     gredsq += d1 * d1;
  1904.                     s.setEntry(i, trialStepPoint.getEntry(i));
  1905.                 } else {
  1906.                     s.setEntry(i, ZERO);
  1907.                 }
  1908.             }
  1909.             itcsav = iterc;
  1910.             state = 210; break;
  1911.             // Let the search direction S be a linear combination of the reduced D
  1912.             // and the reduced G that is orthogonal to the reduced D.
  1913.         }
  1914.         case 120: {
  1915.             ++iterc;
  1916.             temp = gredsq * dredsq - dredg * dredg;
  1917.             if (temp <= qred * 1e-4 * qred) {
  1918.                 state = 190; break;
  1919.             }
  1920.             temp = FastMath.sqrt(temp);
  1921.             for (int i = 0; i < n; i++) {
  1922.                 if (xbdi.getEntry(i) == ZERO) {
  1923.                     s.setEntry(i, (dredg * trialStepPoint.getEntry(i) - dredsq * gnew.getEntry(i)) / temp);
  1924.                 } else {
  1925.                     s.setEntry(i, ZERO);
  1926.                 }
  1927.             }
  1928.             sredg = -temp;

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

  1933.             angbd = ONE;
  1934.             iact = -1;
  1935.             for (int i = 0; i < n; i++) {
  1936.                 if (xbdi.getEntry(i) == ZERO) {
  1937.                     tempa = trustRegionCenterOffset.getEntry(i) + trialStepPoint.getEntry(i) - lowerDifference.getEntry(i);
  1938.                     tempb = upperDifference.getEntry(i) - trustRegionCenterOffset.getEntry(i) - trialStepPoint.getEntry(i);
  1939.                     if (tempa <= ZERO) {
  1940.                         ++nact;
  1941.                         xbdi.setEntry(i, MINUS_ONE);
  1942.                         break;
  1943.                     } else if (tempb <= ZERO) {
  1944.                         ++nact;
  1945.                         xbdi.setEntry(i, ONE);
  1946.                         break;
  1947.                     }
  1948.                     // Computing 2nd power
  1949.                     double d1 = trialStepPoint.getEntry(i);
  1950.                     // Computing 2nd power
  1951.                     double d2 = s.getEntry(i);
  1952.                     ssq = d1 * d1 + d2 * d2;
  1953.                     // Computing 2nd power
  1954.                     d1 = trustRegionCenterOffset.getEntry(i) - lowerDifference.getEntry(i);
  1955.                     temp = ssq - d1 * d1;
  1956.                     if (temp > ZERO) {
  1957.                         temp = FastMath.sqrt(temp) - s.getEntry(i);
  1958.                         if (angbd * temp > tempa) {
  1959.                             angbd = tempa / temp;
  1960.                             iact = i;
  1961.                             xsav = MINUS_ONE;
  1962.                         }
  1963.                     }
  1964.                     // Computing 2nd power
  1965.                     d1 = upperDifference.getEntry(i) - trustRegionCenterOffset.getEntry(i);
  1966.                     temp = ssq - d1 * d1;
  1967.                     if (temp > ZERO) {
  1968.                         temp = FastMath.sqrt(temp) + s.getEntry(i);
  1969.                         if (angbd * temp > tempb) {
  1970.                             angbd = tempb / temp;
  1971.                             iact = i;
  1972.                             xsav = ONE;
  1973.                         }
  1974.                     }
  1975.                 }
  1976.             }

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

  1978.             state = 210; break;
  1979.         }
  1980.         case 150: {
  1981.             shs = ZERO;
  1982.             dhs = ZERO;
  1983.             dhd = ZERO;
  1984.             for (int i = 0; i < n; i++) {
  1985.                 if (xbdi.getEntry(i) == ZERO) {
  1986.                     shs += s.getEntry(i) * hs.getEntry(i);
  1987.                     dhs += trialStepPoint.getEntry(i) * hs.getEntry(i);
  1988.                     dhd += trialStepPoint.getEntry(i) * hred.getEntry(i);
  1989.                 }
  1990.             }

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

  1994.             redmax = ZERO;
  1995.             isav = -1;
  1996.             redsav = ZERO;
  1997.             int iu = (int) (angbd * 17. + 3.1);
  1998.             for (int i = 0; i < iu; i++) {
  1999.                 angt = angbd * i / iu;
  2000.                 sth = (angt + angt) / (ONE + angt * angt);
  2001.                 temp = shs + angt * (angt * dhd - dhs - dhs);
  2002.                 rednew = sth * (angt * dredg - sredg - HALF * sth * temp);
  2003.                 if (rednew > redmax) {
  2004.                     redmax = rednew;
  2005.                     isav = i;
  2006.                     rdprev = redsav;
  2007.                 } else if (i == isav + 1) {
  2008.                     rdnext = rednew;
  2009.                 }
  2010.                 redsav = rednew;
  2011.             }

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

  2014.             if (isav < 0) {
  2015.                 state = 190; break;
  2016.             }
  2017.             if (isav < iu) {
  2018.                 temp = (rdnext - rdprev) / (redmax + redmax - rdprev - rdnext);
  2019.                 angt = angbd * (isav + HALF * temp) / iu;
  2020.             }
  2021.             cth = (ONE - angt * angt) / (ONE + angt * angt);
  2022.             sth = (angt + angt) / (ONE + angt * angt);
  2023.             temp = shs + angt * (angt * dhd - dhs - dhs);
  2024.             sdec = sth * (angt * dredg - sredg - HALF * sth * temp);
  2025.             if (sdec <= ZERO) {
  2026.                 state = 190; break;
  2027.             }

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

  2031.             dredg = ZERO;
  2032.             gredsq = ZERO;
  2033.             for (int i = 0; i < n; i++) {
  2034.                 gnew.setEntry(i, gnew.getEntry(i) + (cth - ONE) * hred.getEntry(i) + sth * hs.getEntry(i));
  2035.                 if (xbdi.getEntry(i) == ZERO) {
  2036.                     trialStepPoint.setEntry(i, cth * trialStepPoint.getEntry(i) + sth * s.getEntry(i));
  2037.                     dredg += trialStepPoint.getEntry(i) * gnew.getEntry(i);
  2038.                     // Computing 2nd power
  2039.                     final double d1 = gnew.getEntry(i);
  2040.                     gredsq += d1 * d1;
  2041.                 }
  2042.                 hred.setEntry(i, cth * hred.getEntry(i) + sth * hs.getEntry(i));
  2043.             }
  2044.             qred += sdec;
  2045.             if (iact >= 0 && isav == iu) {
  2046.                 ++nact;
  2047.                 xbdi.setEntry(iact, xsav);
  2048.                 state = 100; break;
  2049.             }

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

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

  2117.     // ----------------------------------------------------------------------------------------

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

  2135.         final int n = currentBest.getDimension();
  2136.         final int npt = numberOfInterpolationPoints;
  2137.         final int nptm = npt - n - 1;

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

  2140.         double ztest = ZERO;
  2141.         for (int k = 0; k < npt; k++) {
  2142.             for (int j = 0; j < nptm; j++) {
  2143.                 // Computing MAX
  2144.                 ztest = FastMath.max(ztest, FastMath.abs(zMatrix.getEntry(k, j)));
  2145.             }
  2146.         }
  2147.         ztest *= 1e-20;

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

  2149.         for (int j = 1; j < nptm; j++) {
  2150.             final double d1 = zMatrix.getEntry(knew, j);
  2151.             if (FastMath.abs(d1) > ztest) {
  2152.                 // Computing 2nd power
  2153.                 final double d2 = zMatrix.getEntry(knew, 0);
  2154.                 // Computing 2nd power
  2155.                 final double d3 = zMatrix.getEntry(knew, j);
  2156.                 final double d4 = FastMath.sqrt(d2 * d2 + d3 * d3);
  2157.                 final double d5 = zMatrix.getEntry(knew, 0) / d4;
  2158.                 final double d6 = zMatrix.getEntry(knew, j) / d4;
  2159.                 for (int i = 0; i < npt; i++) {
  2160.                     final double d7 = d5 * zMatrix.getEntry(i, 0) + d6 * zMatrix.getEntry(i, j);
  2161.                     zMatrix.setEntry(i, j, d5 * zMatrix.getEntry(i, j) - d6 * zMatrix.getEntry(i, 0));
  2162.                     zMatrix.setEntry(i, 0, d7);
  2163.                 }
  2164.             }
  2165.             zMatrix.setEntry(knew, j, ZERO);
  2166.         }

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

  2169.         for (int i = 0; i < npt; i++) {
  2170.             work.setEntry(i, zMatrix.getEntry(knew, 0) * zMatrix.getEntry(i, 0));
  2171.         }
  2172.         final double alpha = work.getEntry(knew);
  2173.         final double tau = lagrangeValuesAtNewPoint.getEntry(knew);
  2174.         lagrangeValuesAtNewPoint.setEntry(knew, lagrangeValuesAtNewPoint.getEntry(knew) - ONE);

  2175.         // Complete the updating of ZMAT.

  2176.         final double sqrtDenom = FastMath.sqrt(denom);
  2177.         final double d1 = tau / sqrtDenom;
  2178.         final double d2 = zMatrix.getEntry(knew, 0) / sqrtDenom;
  2179.         for (int i = 0; i < npt; i++) {
  2180.             zMatrix.setEntry(i, 0,
  2181.                           d1 * zMatrix.getEntry(i, 0) - d2 * lagrangeValuesAtNewPoint.getEntry(i));
  2182.         }

  2183.         // Finally, update the matrix BMAT.

  2184.         for (int j = 0; j < n; j++) {
  2185.             final int jp = npt + j;
  2186.             work.setEntry(jp, bMatrix.getEntry(knew, j));
  2187.             final double d3 = (alpha * lagrangeValuesAtNewPoint.getEntry(jp) - tau * work.getEntry(jp)) / denom;
  2188.             final double d4 = (-beta * work.getEntry(jp) - tau * lagrangeValuesAtNewPoint.getEntry(jp)) / denom;
  2189.             for (int i = 0; i <= jp; i++) {
  2190.                 bMatrix.setEntry(i, j,
  2191.                               bMatrix.getEntry(i, j) + d3 * lagrangeValuesAtNewPoint.getEntry(i) + d4 * work.getEntry(i));
  2192.                 if (i >= npt) {
  2193.                     bMatrix.setEntry(jp, (i - npt), bMatrix.getEntry(i, j));
  2194.                 }
  2195.             }
  2196.         }
  2197.     } // update

  2198.     /**
  2199.      * Performs validity checks.
  2200.      *
  2201.      * @param lowerBound Lower bounds (constraints) of the objective variables.
  2202.      * @param upperBound Upperer bounds (constraints) of the objective variables.
  2203.      */
  2204.     private void setup(double[] lowerBound,
  2205.                        double[] upperBound) {

  2206.         double[] init = getStartPoint();
  2207.         final int dimension = init.length;

  2208.         // Check problem dimension.
  2209.         if (dimension < MINIMUM_PROBLEM_DIMENSION) {
  2210.             throw new MathIllegalArgumentException(LocalizedCoreFormats.NUMBER_TOO_SMALL,
  2211.                                                    dimension, MINIMUM_PROBLEM_DIMENSION);
  2212.         }
  2213.         // Check number of interpolation points.
  2214.         final int[] nPointsInterval = { dimension + 2, (dimension + 2) * (dimension + 1) / 2 };
  2215.         if (numberOfInterpolationPoints < nPointsInterval[0] ||
  2216.             numberOfInterpolationPoints > nPointsInterval[1]) {
  2217.             throw new MathIllegalArgumentException(LocalizedCoreFormats.NUMBER_OF_INTERPOLATION_POINTS,
  2218.                                           numberOfInterpolationPoints,
  2219.                                           nPointsInterval[0],
  2220.                                           nPointsInterval[1]);
  2221.         }

  2222.         // Initialize bound differences.
  2223.         boundDifference = new double[dimension];

  2224.         double requiredMinDiff = 2 * initialTrustRegionRadius;
  2225.         double minDiff = Double.POSITIVE_INFINITY;
  2226.         for (int i = 0; i < dimension; i++) {
  2227.             boundDifference[i] = upperBound[i] - lowerBound[i];
  2228.             minDiff = FastMath.min(minDiff, boundDifference[i]);
  2229.         }
  2230.         if (minDiff < requiredMinDiff) {
  2231.             initialTrustRegionRadius = minDiff / 3.0;
  2232.         }

  2233.         // Initialize the data structures used by the "bobyqa" method.
  2234.         bMatrix = new Array2DRowRealMatrix(dimension + numberOfInterpolationPoints,
  2235.                                            dimension);
  2236.         zMatrix = new Array2DRowRealMatrix(numberOfInterpolationPoints,
  2237.                                            numberOfInterpolationPoints - dimension - 1);
  2238.         interpolationPoints = new Array2DRowRealMatrix(numberOfInterpolationPoints,
  2239.                                                        dimension);
  2240.         originShift = new ArrayRealVector(dimension);
  2241.         fAtInterpolationPoints = new ArrayRealVector(numberOfInterpolationPoints);
  2242.         trustRegionCenterOffset = new ArrayRealVector(dimension);
  2243.         gradientAtTrustRegionCenter = new ArrayRealVector(dimension);
  2244.         lowerDifference = new ArrayRealVector(dimension);
  2245.         upperDifference = new ArrayRealVector(dimension);
  2246.         modelSecondDerivativesParameters = new ArrayRealVector(numberOfInterpolationPoints);
  2247.         newPoint = new ArrayRealVector(dimension);
  2248.         alternativeNewPoint = new ArrayRealVector(dimension);
  2249.         trialStepPoint = new ArrayRealVector(dimension);
  2250.         lagrangeValuesAtNewPoint = new ArrayRealVector(dimension + numberOfInterpolationPoints);
  2251.         modelSecondDerivativesValues = new ArrayRealVector(dimension * (dimension + 1) / 2);
  2252.     }

  2253. }
  2254. //CHECKSTYLE: resume all