View Javadoc
1   /*
2    * Licensed to the Hipparchus project 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 Hipparchus project 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  package org.hipparchus.optim.nonlinear.vector.constrained;
18  
19  import org.hipparchus.linear.Array2DRowRealMatrix;
20  import org.hipparchus.linear.ArrayRealVector;
21  import org.hipparchus.linear.MatrixUtils;
22  import org.hipparchus.linear.RealMatrix;
23  import org.hipparchus.linear.RealVector;
24  import org.hipparchus.optim.SimpleBounds;
25  import org.hipparchus.optim.nonlinear.scalar.ObjectiveFunction;
26  import org.hipparchus.util.FastMath;
27  import org.hipparchus.util.Pair;
28  import org.hipparchus.util.Precision;
29  
30  /**
31   * Sequential Quadratic Programming Optimizer (extended version).
32   *
33   * <p>
34   * Minimizes a nonlinear objective function subject to equality, inequality, and
35   * box constraints using a Sequential Quadratic Programming method. This
36   * implementation is inspired by the algorithm described in: "On the convergence
37   * of a sequential quadratic programming method" by Klaus Schittkowski (1982).
38   * </p>
39   *
40   * <p>
41   * Supports: equality constraints, inequality constraints,bounds constraints, penalty function
42   * updates, line search strategies, BFGS Hessian update, and augmented QP
43   * formulation using a relaxation variable.
44   * </p>
45   *
46   * @since 3.1
47   */
48  public class SQPOptimizerS2 extends AbstractSQPOptimizer2 {
49  
50      private enum QPMode {
51          /**
52           * Solving the standard QP subproblem (no slack variable).
53           */
54          QP_STARDARD,
55          /**
56           * Solving the augmented QP subproblem (with slack variable).
57           */
58          QP_AUGMENTED
59      }
60  
61      /** Lower-triangular Cholesky factor. */
62      private RealMatrix L;
63  
64      /**
65       * Logger.
66       */
67      private final SQPLogger formatter = SQPLogger.defaultLogger();
68  
69      /**
70       * Value of the equality constraints (residual v = f(x) - lower).
71       */
72      private RealVector eqEval;
73  
74      /**
75       * Value of the inequality constraints (residual v = f(x) - lower).
76       */
77      private RealVector ineqEval;
78  
79      /**
80       * Value of the bounds (residual v = Ax - lower).
81       */
82      private RealVector bEval;
83  
84      /**
85       * Gradient of the objective function.
86       */
87      private RealVector J;
88  
89      /**
90       * Hessian approximation.
91       */
92      private RealMatrix H;
93  
94      /**
95       * Jacobian of the inequality constraints.
96       */
97      private RealMatrix JI;
98  
99      /**
100      * Jacobian of the equality constraints.
101      */
102     private RealMatrix JE;
103 
104     /**
105      * Jacobian of the bounds.
106      */
107     private RealMatrix JB;
108 
109     /**
110      * Evaluation of the objective function.
111      */
112     private double functionEval;
113 
114     /**
115      * Current point.
116      */
117     private RealVector x;
118 
119     /**
120      * Bounds in form of inequality constraints.
121      */
122     private LinearInequalityConstraint BIQ;
123 
124     /**
125      * Lower bound.
126      */
127     private ArrayRealVector LB;
128 
129     /**
130      * Upper bound.
131      */
132     private ArrayRealVector UB;
133 
134     /** Simple constructor.
135      */
136     public SQPOptimizerS2() {
137         // nothing to do
138     }
139 
140     /**
141      * {@inheritDoc}
142      */
143     @Override
144     public LagrangeSolution doOptimize() {
145         formatter.setEps(getSettings().getEps());
146         formatter.logHeader();
147         int me = 0;
148         int mi = 0;
149 
150         // Equality constraints configuration
151         if (this.getEqConstraint() != null) {
152             me = getEqConstraint().dimY();
153         }
154         // Inequality constraints configuration
155         if (this.getIqConstraint() != null) {
156             mi = getIqConstraint().dimY();
157         }
158 
159         final int mb = buildBoundsAsInequalities();
160 
161         final int m = me + mi + mb;
162 
163         // Get initial value of slack variable from SQPOption
164         double rho = getSettings().getRhoCons();
165         x = (this.getStartPoint() != null) ? new ArrayRealVector(this.getStartPoint()) : initGuess();
166 
167         RealVector y = new ArrayRealVector(me + mi + mb, 0.0);
168 
169         // All the function and constraint evaluations will be performed inside the penalty function
170         MeritFunctionL2 penalty = new MeritFunctionL2(this.getObj(), this.getEqConstraint(), this.getIqConstraint(), this.BIQ, x);
171 
172         LineSearch lineSearch = new LineSearch(getSettings().getAlphaMin(), getSettings().getHistory(), getSettings().getMu(), getSettings().getB(),
173                 getSettings().getMaxLineSearchIteration(), 0);
174 
175         // Initial values evaluation (Penalty function stores residuals v = eval - lower)
176         functionEval = penalty.getObjEval();
177         if (this.getEqConstraint() != null) {
178             eqEval = penalty.getEqEval();
179         }
180         if (this.getIqConstraint() != null) {
181             ineqEval = penalty.getIqEval();
182         }
183         if (this.BIQ != null) {
184             bEval = penalty.getBEval();
185         }
186 
187         double EPS = this.getSettings().getEps();
188         double EPS2 = EPS * EPS;
189         double sqrtEPS = FastMath.sqrt(EPS);
190 
191         computeGradients();
192 
193         double gamma = 1.0;
194         H = MatrixUtils.createRealIdentityMatrix(x.getDimension()).scalarMultiply(FastMath.sqrt(gamma));
195 
196         BFGSUpdater bfgs = new BFGSUpdater(H, EPS, true, getMatrixDecompositionTolerance().getEpsMatrixDecomposition());
197 
198         L = bfgs.getL();
199         RealVector dx = new ArrayRealVector(x.getDimension());
200         RealVector u = new ArrayRealVector(y.getDimension());
201         penalty.update(J, JE, JI, x, y, dx, u);
202 
203         QPMode QPMODE = QPMode.QP_STARDARD;
204 
205         boolean crit0 = false;
206         boolean crit1 = false;
207         boolean crit2 = false;
208         boolean crit3 = false;
209         boolean crit4 = false;
210         boolean crit5 = false;
211         double sigma = 0.0;
212         double alpha = 0.0;
213         RealVector lagOld;
214         RealVector lagNew;
215 
216         LagrangeSolution qpSolution = null;
217 
218         boolean GRADFAIL = false;
219         boolean FALLBACK = false;
220         double VIOLATION = constraintViolation();
221         double COMPLEMENTARY = Double.POSITIVE_INFINITY;
222         double KKT = Double.POSITIVE_INFINITY;
223         double DHD = 0.0;
224         double XNORM = 0.0;
225         double FUNDIFF = 0.0;
226         int BFGSUPDATE;
227         int FUNEVALCOUNT=0;
228         SQPCustomCriterion customCriteria = getSettings().getConvergenceFunction();
229         for (int i = 0; i < getSettings().getMaxIteration(); i++) {
230 
231             sigma = getSettings().getSigmaMax() * 10.0;
232             while ((sigma > getSettings().getSigmaMax() || sigma < 0.0) && rho < 1.0e9 && !FALLBACK) {
233 
234                 qpSolution = (QPMODE == QPMode.QP_AUGMENTED) ? solveAugmentedQP(y, rho) : solveQP();
235                 sigma = (qpSolution == null || qpSolution.getX().getDimension() == 0 || Double.isInfinite(qpSolution.getX().getMaxValue()) ||  Double.isInfinite(qpSolution.getX().getMinValue())) ? getSettings().getSigmaMax() * 10.0 : qpSolution.getValue();
236                 if ((sigma > getSettings().getSigmaMax() || sigma < 0.0)) {
237                      if (QPMODE == QPMode.QP_AUGMENTED) {
238                          rho = rhoUp(rho);
239                      }
240                      QPMODE = QPMode.QP_AUGMENTED;
241                 }
242             }
243 
244             // If sigma > sigma threshold after several attempts, assign direction from penalty gradient
245             if (rho >= 1.0e9 || FALLBACK) {
246                 qpSolution = solveQPFallBack(penalty.gradX());
247 
248                     if (qpSolution == null || qpSolution.getX().getDimension() == 0 ) {
249 
250                         bfgs.resetHessian();
251                         H=bfgs.getHessian();
252                         L=bfgs.getL();
253                         qpSolution = solveQPFallBack(penalty.gradX());
254                         if (qpSolution == null || qpSolution.getX().getDimension() == 0 ) {
255                             penalty.resetRj();
256                             if (m > 0) {
257                                 u.set(0.0);
258                                 y.set(0.0);
259                             }
260                             penalty.update(J, JE, JI, x, y, new ArrayRealVector(x.getDimension()), u);
261                             qpSolution = solveQPFallBack(penalty.gradX());
262 
263                             if (qpSolution == null || qpSolution.getX().getDimension() == 0 ) {
264                                 break;
265                             }
266 
267                         }  // Infeasible
268                     // Estimation of multiplier from penalty grad y
269 
270 
271                     }
272                 if (m > 0 ) {
273                     u = y.subtract(penalty.gradY());
274                 }
275 
276 
277                 dx = qpSolution.getX();
278                 projectDirectionInPlace(x, dx);
279 
280 
281                 QPMODE = QPMode.QP_AUGMENTED;
282                 sigma = 0.0;
283                 rho = getSettings().getRhoCons();
284 
285             } else {
286                 dx = qpSolution.getX();
287                 u = qpSolution.getLambda();
288 
289                 sigma = qpSolution.getValue();
290                 projectDirectionInPlace(x, dx);
291 
292                 penalty.updateRj(H, y, dx, u, sigma, iterations.getCount());
293 
294                 // Switch to normal QP if additional variable is small enough
295                 if (QPMODE == QPMode.QP_AUGMENTED && FastMath.abs(sigma) < getSettings().getEps() && !GRADFAIL) {
296                     QPMODE = QPMode.QP_STARDARD;
297                     rho = getSettings().getRhoCons();
298                 }
299             }
300 
301             penalty.update(J, JE, JI, x, y, dx, u);
302 
303             lagOld= lagrangianGradX(J, JE, JI, x, u);
304             double dlan = lagOld.getNorm();
305 
306             // Convergence check before line search
307             KKT = dlan * dlan;
308             DHD = dx.dotProduct(H.operate(dx));
309             COMPLEMENTARY = complementarySlackness(u, me);
310             XNORM = dx.getNorm();
311 
312             crit0 = KKT <= EPS;
313             crit1 = DHD <= EPS2;
314             crit2 = XNORM <= EPS * (1.0 + x.getNorm());
315             crit3 = VIOLATION <= sqrtEPS;
316             crit5 = COMPLEMENTARY <= EPS;
317 
318             if ((crit0 || crit1) && crit5  && crit3) {
319                 break;
320             }
321 
322 
323 
324             if (penalty.getGradient() >= 0) {
325                 if (QPMODE == QPMode.QP_AUGMENTED) {
326                     rho = rhoUp(rho);
327                 }
328                 QPMODE = QPMode.QP_AUGMENTED;
329                 GRADFAIL = true;
330             }
331             // If penalty gradient is < 0 proceed with line search
332              else  {
333                 iterations.increment();
334                 GRADFAIL = false;
335                 FALLBACK = false;
336 
337                 if (QPMODE == QPMode.QP_AUGMENTED) {
338                     rho = updateRho(dx, u, sigma);
339                 }
340 
341                 // Line Search
342                 alpha = lineSearch.search(penalty);
343                 FUNEVALCOUNT+=lineSearch.getIteration();
344                 //UPDATE MULTIPLIER
345                 if (m > 0) {
346                    // y = y.add(u.subtract(y).mapMultiply(alpha));
347                     //y.combineToSelf(1.0 - alpha, alpha, u);//this is worse
348                     double yk;
349                     for (int k = 0; k < y.getDimension(); ++k) {
350                         yk = y.getEntry(k);
351                         y.setEntry(k, yk + (u.getEntry(k) - yk) * alpha);
352                     }
353 
354                 }
355                 //UPDATE SOLUTION
356                 //x = x.add(dx.mapMultiply(alpha));
357                 x.combineToSelf(1.0, alpha, dx);
358                 // UPDATE FUNCTION AND CONSTRAINT EVAL (Residuals v = eval - lower are stored)
359                 // Old objective function evaluation.
360                 final double functionEvalOld = functionEval;
361                 functionEval = penalty.getObjEval();
362                 eqEval = penalty.getEqEval();
363                 ineqEval = penalty.getIqEval();
364                 bEval = penalty.getBEval();
365 
366                 // Convergence check after line search
367                 COMPLEMENTARY = complementarySlackness(u, me);
368                 VIOLATION = constraintViolation();
369                 lagNew= lagrangianGradX(J, JE, JI, x, u);
370                 dlan = lagNew.getNorm();
371                 KKT = dlan * dlan;
372                 // Step length
373                 if (alpha > 0) {
374                     DHD = DHD * alpha * alpha;
375                     XNORM = alpha * dx.getNorm();
376                 }
377 
378                 FUNDIFF = FastMath.abs(functionEval - functionEvalOld);
379 
380                 crit0 = KKT <= EPS;
381                 crit1 = DHD <= EPS2;
382                 crit2 = XNORM <= EPS * (1.0 + x.getNorm());
383                 crit3 = VIOLATION <= sqrtEPS;
384                 crit4 = FUNDIFF < EPS * (1.0 + FastMath.abs(functionEval));
385                 crit5 = COMPLEMENTARY <= EPS;
386 
387 //                if (!lineSearch.isBadStepDetected() && (crit0 || (crit5 && m > 0) || crit4 || crit2 ) && crit1   && crit3) {
388 //                    break;
389 //                }
390 //                if (manualBreak) {
391 //                    System.out.println("\n[Solver] Manual break triggered by the user.");
392 //                    break; // Exits the loop exactly at this checkpoint
393 //                }
394                 if (customCriteria!=null &&
395                     customCriteria.converged(alpha, XNORM, DHD, COMPLEMENTARY, KKT, VIOLATION,
396                                              FUNDIFF, x.getNorm(), FastMath.abs(functionEval))) {
397                     break;
398                 }
399 
400                  if (!lineSearch.isBadStepDetected() && ((crit0 || crit1) && crit5  && crit3)) {
401                     break;
402                 }
403 //
404                 if (lineSearch.isBadStepDetected() && (crit3 && (crit4 || crit2))) {
405                     break;
406                 }
407 
408                 computeGradients();
409                 RealVector lagnew = lagrangianGradX(J, JE, JI, x, u);
410 
411                 // Hessian update with the logic of line search and internal damping logic
412                 if (lineSearch.isBadStepFailed()) {
413                     FALLBACK = false;
414                     bfgs.resetHessian();
415                     H = bfgs.getHessian();
416                     L = bfgs.getL();
417                     lineSearch.resetBadStepCount();
418                     BFGSUPDATE = -2;
419 
420                } else if (lineSearch.isBadStepDetected()) {
421                     BFGSUPDATE = -1;
422                     L = bfgs.getL();
423                     H = bfgs.getHessian();
424                 } else {
425                     BFGSUPDATE = bfgs.update(dx.mapMultiply(alpha), lagnew.subtract(lagOld));
426                     H = bfgs.getHessian();
427                     L = bfgs.getL();
428                 }
429 
430                 formatter.logRow(iterations.getCount(),
431                         alpha, lineSearch.getIteration(),
432                         XNORM, DHD, COMPLEMENTARY, KKT, VIOLATION, sigma,
433                         penalty.getPenaltyEval(), functionEval, FUNDIFF, BFGSUPDATE);
434             }
435         }
436 
437         formatter.logRow(iterations.getCount(),
438                         alpha, lineSearch.getIteration(),
439                         XNORM, DHD, COMPLEMENTARY, KKT, VIOLATION, sigma,
440                         penalty.getPenaltyEval(), functionEval, FUNDIFF, -99);
441         FUNEVALCOUNT+=iterations.getCount();
442         formatter.logRow(FUNEVALCOUNT,crit2, crit1, crit5, crit0, crit3, crit4);
443 
444         return new LagrangeSolution(x, y, functionEval);
445     }
446 
447     /**
448      * Compute gradients.
449      */
450     private void computeGradients() {
451         switch (getSettings().getGradientMode()) {
452             case EXTERNAL:
453                 externalGradient();
454                 break;
455             case FORWARD:
456                 forwardGradient();
457                 break;
458             default:
459                 centralGradient();
460                 break;
461         }
462     }
463 
464 
465     /**
466      * Compute constraints violations using residuals directly.
467      *
468      * @return constraints violations
469      */
470     private double constraintViolation() {
471         double crit = 0.0;
472 
473         if (this.getEqConstraint() != null) {
474 
475             for (int k = 0; k < eqEval.getDimension(); k++) {
476                 crit += FastMath.abs(eqEval.getEntry(k));
477             }
478         }
479 
480         if (this.getIqConstraint() != null) {
481 
482             for (int k = 0; k < ineqEval.getDimension(); k++) {
483                 if (ineqEval.getEntry(k)< 0.0) {
484                     crit -= ineqEval.getEntry(k);
485                 }
486             }
487         }
488 
489         if (this.BIQ != null) {
490 
491             for (int k = 0; k < bEval.getDimension(); k++) {
492                 if (bEval.getEntry(k) < 0.0) {
493                     crit -= bEval.getEntry(k);
494                 }
495             }
496         }
497 
498         return crit;
499     }
500 
501     /**
502      * Compute complementary slackness using residuals directly.
503      *
504      * @param u  the multiplier vector
505      * @param me the number of equality constraints
506      * @return complementary slackness
507      */
508     private double complementarySlackness(RealVector u, int me) {
509         if (u == null) {
510             return 0.0;
511         }
512 
513         double crit = 0.0;
514         int shift = me;
515 
516 
517         if (this.getIqConstraint() != null) {
518 
519             for (int i = 0; i < ineqEval.getDimension(); i++) {
520                 crit += FastMath.abs(ineqEval.getEntry(i) * u.getEntry(shift + i));
521             }
522             shift += ineqEval.getDimension();
523         }
524 
525         if (this.BIQ != null) {
526 
527             for (int i = 0; i < bEval.getDimension(); i++) {
528                 crit += FastMath.abs(bEval.getEntry(i) * u.getEntry(shift + i));
529             }
530         }
531 
532         return crit;
533     }
534 
535     /**
536      * Increase the rho penalty parameter.
537      *
538      * @param rho current rho
539      * @return increased rho
540      */
541     private double rhoUp(double rho) {
542         return rho * 10.0;
543     }
544 
545     /**
546      * Dynamically update rho based on the current step and multiplier difference.
547      *
548      * @param dx current step
549      * @param dy multiplier step
550      * @param additionalVariable slack/augmented variable
551      * @return new rho value
552      */
553     private double updateRho(final RealVector dx, final RealVector dy, final double additionalVariable) {
554         int me = JE != null ? JE.getRowDimension() : 0;
555         int mi = JI != null ? JI.getRowDimension() : 0;
556         int mb = JB != null ? JB.getRowDimension() : 0;
557 
558         if (me + mi + mb > 0) {
559 
560             RealVector jacPreDy = new ArrayRealVector(x.getDimension());
561             int offset = 0;
562 
563             if (me > 0 && JE != null) {
564                 RealVector dyE = dy.getSubVector(offset, me);
565                 jacPreDy.combineToSelf(1.0, 1.0, JE.preMultiply(dyE));
566                 offset += me;
567             }
568             if (mi > 0 && JI != null) {
569                 RealVector dyI = dy.getSubVector(offset, mi);
570                 jacPreDy.combineToSelf(1.0, 1.0, JI.preMultiply(dyI));
571                 offset += mi;
572             }
573             if (mb > 0 && JB != null) {
574                 RealVector dyB = dy.getSubVector(offset, mb);
575                 jacPreDy.combineToSelf(1.0, 1.0, JB.preMultiply(dyB));
576             }
577 
578 
579             double num = 10.0 * FastMath.pow(dx.dotProduct(jacPreDy), 2);
580             double den = (1.0 - additionalVariable) * (1.0 - additionalVariable) * dx.dotProduct(H.operate(dx));
581 
582             if (den < Precision.SAFE_MIN) {
583                 den = Precision.SAFE_MIN;
584             }
585 
586             return FastMath.max(10.0, num / den);
587         }
588         return 1.0;
589     }
590 
591     /**
592      * Solve augmented problem using residuals.
593      * <p>
594      * Mathematically equivalent to the original version, but optimized to avoid
595      * double[][] allocations and implementation-specific casts.
596      * </p>
597      * @param y Lagrange multipliers
598      * @param rho rho penalty parameter
599      * @return problem solution
600      */
601     private LagrangeSolution solveAugmentedQP(final RealVector y, final double rho) {
602         final int n = x.getDimension();
603         final double eps = getSettings().getEps();
604 
605         final int me = (getEqConstraint() != null) ? getEqConstraint().dimY() : 0;
606         final int mi = (getIqConstraint() != null) ? getIqConstraint().dimY() : 0;
607         final int mb = (BIQ != null) ? BIQ.dimY() : 0;
608         final int mc = mi + mb;
609 
610         boolean violated = false;
611         if (mi > 0) {
612             violated = ineqEval.getMinValue() <= eps || y.getSubVector(me, mi).getMaxValue() > 0;
613         }
614 
615         final int add = (me > 0 || violated) ? 1 : 0;
616 
617         // --- OBJECTIVE ---
618         final RealVector g1 = new ArrayRealVector(n + add);
619         g1.setSubVector(0, J);
620 
621         // L1: [L, 0; 0, sqrt(rho)]
622         final RealMatrix L1 = MatrixUtils.createRealMatrix(n + add, n + add);
623         for (int i = 0; i < n; i++) {
624             for (int j = 0; j < n; j++) {
625                 L1.setEntry(i, j, L.getEntry(i, j));
626             }
627         }
628         if (add == 1) {
629             L1.setEntry(n, n, FastMath.sqrt(rho));
630         }
631 
632         // --- EQUALITIES ---
633         LinearEqualityConstraint eqc = null;
634         if (me > 0) {
635             final RealMatrix Ae = MatrixUtils.createRealMatrix(me, n + add);
636             final RealVector eqRhs = new ArrayRealVector(me);
637             for (int i = 0; i < me; i++) {
638                 final double vi = eqEval.getEntry(i);
639                 eqRhs.setEntry(i, -vi);
640                 if (add == 1) {
641                     Ae.setEntry(i, n, -vi);
642                 }
643                 for (int j = 0; j < n; j++) {
644                     Ae.setEntry(i, j, JE.getEntry(i, j));
645                 }
646             }
647             eqc = new LinearEqualityConstraint(Ae, eqRhs);
648         }
649 
650         // --- INEQUALITIES & BOUNDS ---
651         LinearInequalityConstraint iqc = null;
652         if (mc > 0) {
653             final RealMatrix A = MatrixUtils.createRealMatrix(mc, n + add);
654             final RealVector B = new ArrayRealVector(mc);
655 
656             // Part 1: Inequalities
657             if (mi > 0) {
658                 for (int i = 0; i < mi; i++) {
659                     final double vi = ineqEval.getEntry(i);
660                     B.setEntry(i, -vi);
661                     if (add == 1) {
662                         if (vi <= eps || y.getEntry(me + i) > 0) {
663                             A.setEntry(i, n, -vi);
664                         }
665                     }
666                     for (int j = 0; j < n; j++) {
667                         A.setEntry(i, j, JI.getEntry(i, j));
668                     }
669                 }
670             }
671 
672             // Part 2: Bounds (Stacked below inequalities)
673             if (mb > 0) {
674                 for (int i = 0; i < mb; i++) {
675                     B.setEntry(mi + i, -bEval.getEntry(i));
676                     for (int j = 0; j < n; j++) {
677                         A.setEntry(mi + i, j, JB.getEntry(i, j));
678                     }
679                 }
680             }
681             iqc = new LinearInequalityConstraint(A, B);
682         }
683 
684         // --- SLACK BOUNDS ---
685         LinearBoundedConstraint bc = null;
686         if (add == 1) {
687             final RealMatrix sigmaA = MatrixUtils.createRealMatrix(1, n + 1);
688             sigmaA.setEntry(0, n, 1.0);
689             bc = new LinearBoundedConstraint(sigmaA, new ArrayRealVector(1, 0.0), new ArrayRealVector(1, 1.0));
690         }
691 
692         // Solve
693         QPDualActiveSolverOption optQP=new QPDualActiveSolverOption();
694         optQP.setEps(this.getSettings().getEpsQP());
695         optQP.setEpsRelaxation(this.getSettings().getEpsQP());
696         optQP.setMatrixMode(QPMatrixMode.CHOLESKY);
697         final LagrangeSolution sol = getQPSolver().optimize(optQP,
698                 new ObjectiveFunction(new QuadraticFunction(L1, g1, 0)),
699                 iqc, eqc, bc);
700 
701         if (sol == null || sol.getX().getDimension() == 0) {
702             return sol;
703         }
704 
705         final RealVector fullX = sol.getX();
706         final double sigma = (add == 1) ? fullX.getEntry(n) : 0.0;
707 
708         return new LagrangeSolution(fullX.getSubVector(0, n),
709                                     (me + mc == 0) ? null : sol.getLambda().getSubVector(0, me + mc),
710                                     sigma);
711     }
712 
713    /**
714      * Solves the standard Quadratic Programming (QP) subproblem using residuals.
715      * @return a LagrangeSolution containing primal and dual variables, or null if failed.
716      */
717     private LagrangeSolution solveQP() {
718         final int n = x.getDimension();
719         final int me = (getEqConstraint() != null) ? getEqConstraint().dimY() : 0;
720         final int mi = (getIqConstraint() != null) ? getIqConstraint().dimY() : 0;
721         final int mb = (BIQ != null) ? BIQ.dimY() : 0;
722         final int mc = mi + mb;
723 
724         // --- EQUALITY CONSTRAINTS SETUP ---
725         LinearEqualityConstraint eqc = null;
726         if (me > 0) {
727             // Formulation: JE * d = -eqEval
728             eqc = new LinearEqualityConstraint(JE, eqEval.mapMultiply(-1.0));
729         }
730 
731         // --- INEQUALITY CONSTRAINTS SETUP ---
732         LinearInequalityConstraint iqc = null;
733         if (mc > 0) {
734             // Formulation: [JI; JB] * d >= -[ineqEval; bEval]
735             // Pre-allocate global matrix to avoid BlockRealMatrix fragmentation
736             final RealMatrix combinedAI = MatrixUtils.createRealMatrix(mc, n);
737             final RealVector combinedBI = new ArrayRealVector(mc);
738 
739             // Copy Inequality Jacobian (JI) directly into the combined matrix
740             if (mi > 0) {
741                 for (int i = 0; i < mi; i++) {
742                     combinedBI.setEntry(i, -ineqEval.getEntry(i));
743                     for (int j = 0; j < n; j++) {
744                         combinedAI.setEntry(i, j, JI.getEntry(i, j));
745                     }
746                 }
747             }
748 
749             // Copy Bounds Jacobian (JB) directly into the combined matrix (offset by mi)
750             if (mb > 0) {
751                 for (int i = 0; i < mb; i++) {
752                     combinedBI.setEntry(mi + i, -bEval.getEntry(i));
753                     for (int j = 0; j < n; j++) {
754                         combinedAI.setEntry(mi + i, j, JB.getEntry(i, j));
755                     }
756                 }
757             }
758             iqc = new LinearInequalityConstraint(combinedAI, combinedBI);
759         }
760 
761 
762         QPDualActiveSolverOption optQP=new QPDualActiveSolverOption();
763         optQP.setEps(this.getSettings().getEpsQP());
764         optQP.setEpsRelaxation(this.getSettings().getEpsQP());
765         optQP.setMatrixMode(QPMatrixMode.CHOLESKY);
766         // --- QUADRATIC OBJECTIVE ---
767         // Objective: 0.5 * d^T * L * d + J^T * d
768         final QuadraticFunction q = new QuadraticFunction(L, J, 0.0);
769 
770         // --- SOLVE QP ---
771         final LagrangeSolution sol = getQPSolver().optimize(optQP,new ObjectiveFunction(q), iqc, eqc);
772 
773         if (sol == null || sol.getX().getDimension() == 0) {
774             return null;
775         }
776 
777         // IMPORTANT: Sigma must be 0.0 in standard QP to avoid triggering slack logic in SQP loop
778         return new LagrangeSolution(sol.getX(),
779                                     (me + mc > 0) ? sol.getLambda() : new ArrayRealVector(0),
780                                     0.0);
781     }
782 
783 
784     /**
785      * Solves the Quadratic Programming (QP) subproblem in the current SQP
786      * iteration if penalty gradient is >= 0
787      *
788      * @param penaltyGradx gradient of the penalty function
789      * @return a {@link LagrangeSolution} representing the QP solution, or
790      * {@code null} if the QP failed
791      */
792     private LagrangeSolution solveQPFallBack(RealVector penaltyGradx) {
793 
794         final QuadraticFunction q = new QuadraticFunction(this.H ,penaltyGradx, 0);
795         int mb = 0;
796 
797         LinearInequalityConstraint iqc = null;
798 
799         if (BIQ != null) {
800             mb = BIQ.dimY();
801             RealMatrix A = JB;
802             RealVector B = bEval.mapMultiply(-1.0);
803             iqc = new LinearInequalityConstraint(A, B);
804         }
805         QPDualActiveSolverOption optQP=new QPDualActiveSolverOption();
806         optQP.setEps(this.getSettings().getEpsQP());
807         optQP.setEpsRelaxation(this.getSettings().getEpsQP());
808         optQP.setMatrixMode(QPMatrixMode.FULL);
809         LagrangeSolution sol = getQPSolver().optimize(optQP,new ObjectiveFunction(q), iqc);
810 
811         if (sol == null || sol.getX().getDimension() == 0) {
812             return sol;
813         }
814 
815         RealVector solutionX = sol.getX();
816         RealVector solutionLambda = (mb > 0) ? sol.getLambda() : new ArrayRealVector(0, 0);
817 
818         return new LagrangeSolution(solutionX, solutionLambda, 0.0);
819     }
820 
821     /**
822      * Computes the gradient of the Lagrangian function with respect to the
823      * primal variable {@code x}.
824      * <p>
825      * The Lagrangian is defined as:
826      * </p>
827      * <pre>
828      * L(x, y) = f(x) - yₑᵗ·cₑ(x) - yᵢᵗ·cᵢ(x)
829      * </pre>
830      * <p>
831      * where:
832      * </p>
833      * <ul>
834      * <li>{@code f(x)} is the objective function</li>
835      * <li>{@code cₑ(x)} are the equality constraints</li>
836      * <li>{@code cᵢ(x)} are the inequality constraints</li>
837      * <li>{@code y = [yₑ; yᵢ]} is the vector of Lagrange multipliers</li>
838      * </ul>
839      * <p>
840      * The gradient with respect to {@code x} is given by:
841      * </p>
842      * <pre>
843      * ∇ₓ L(x, y) = ∇f(x) - JEᵗ·yₑ - JIᵗ·yᵢ
844      * </pre>
845      *
846      * @param otherJ the gradient of the objective function {@code ∇f(x)},
847      * length {@code n}
848      * @param otherJE the Jacobian of the equality constraints, shape
849      * {@code [me x n]} (nullable)
850      * @param otherJI the Jacobian of the inequality constraints, shape
851      * {@code [mi x n]} (nullable)
852      * @param ignoredX the current point in the primal space (not used directly,
853      * included for API symmetry)
854      * @param y the stacked Lagrange multipliers {@code [yₑ; yᵢ]}, length
855      * {@code me + mi}
856      * @return the gradient of the Lagrangian with respect to {@code x}, length
857      * {@code n}
858      */
859     public RealVector lagrangianGradX(final RealVector otherJ, final RealMatrix otherJE, final RealMatrix otherJI,
860             final RealVector ignoredX, final RealVector y) {
861 
862         RealVector gradL = new ArrayRealVector(otherJ);
863         int offset = 0;
864 
865         if (otherJE != null) {
866             int me = otherJE.getRowDimension();
867             RealVector yEq = y.getSubVector(0, me);
868             gradL.combineToSelf(1.0, -1.0, otherJE.preMultiply(yEq));
869             offset += me;
870         }
871 
872         if (otherJI != null) {
873             int mi = otherJI.getRowDimension();
874             RealVector yIq = y.getSubVector(offset, mi);
875             gradL.combineToSelf(1.0, -1.0, otherJI.preMultiply(yIq));
876             offset += mi;
877         }
878 
879         if (JB != null) {
880             int mb = JB.getRowDimension();
881             RealVector yB = y.getSubVector(offset, mb);
882             gradL.combineToSelf(1.0, -1.0, JB.preMultiply(yB));
883         }
884 
885         return gradL;
886     }
887 
888     /**
889      * Computes the optimal finite difference step size and direction for a given variable,
890      * strictly respecting its lower and upper bounds.
891      * <p>
892      * To prevent catastrophic cancellation and numerical noise, this method strictly
893      * avoids arbitrary step shrinking. If the remaining room up to the active bound
894      * is strictly less than the required numerical step, the variable is
895      * considered numerically frozen and a zero step is returned.
896      * </p>
897      * <p>
898      * For central differences, if a symmetric step is not feasible, the method attempts
899      * to allocate enough room for an asymmetric 3-point formula step (2 * hBase)
900      * to preserve the <i>O(h^2)</i> truncation error.
901      * </p>
902      *
903      * @param i       the index of the variable
904      * @param xi      the current value of the variable
905      * @param hBase   the theoretical base step size (e.g., square root or cube root of machine epsilon)
906      * @param central if {@code true}, step selection prioritizes central finite differences
907      * @return a {@link Pair} where the first element is the signed step size {@code h},
908      * and the second element is the direction indicator:
909      * <ul>
910      * <li>{@code 0} for true central difference</li>
911      * <li>{@code +1} for forward one-sided difference</li>
912      * <li>{@code -1} for backward one-sided difference</li>
913      * </ul>
914      * Returns {@code (0.0, 0)} if the variable is strictly bounded and cannot be perturbed safely.
915      */
916     private Pair<Double, Integer> chooseStep(final int i,
917                                              final double xi,
918                                              final double hBase,
919                                              final boolean central) {
920 
921         final double lb = LB.getEntry(i);
922         final double ub = UB.getEntry(i);
923 
924         final double roomMinus = FastMath.max(0.0,
925                 Double.isFinite(lb) ? (xi - lb) : Double.POSITIVE_INFINITY);
926         final double roomPlus = FastMath.max(0.0,
927                 Double.isFinite(ub) ? (ub - xi) : Double.POSITIVE_INFINITY);
928 
929         if (!central) {
930             if (roomPlus >= hBase) {
931                 return new Pair<>(hBase, +1);
932             }
933             if (roomMinus >= hBase) {
934                 return new Pair<>(-hBase, -1);
935             }
936             return new Pair<>(0.0, 0);
937         }
938 
939         if (roomPlus >= hBase && roomMinus >= hBase) {
940             return new Pair<>(hBase, 0);
941         }
942 
943         if (roomPlus >= 2.0 * hBase) {
944             return new Pair<>(hBase, +1);
945         }
946         if (roomMinus >= 2.0 * hBase) {
947             return new Pair<>(-hBase, -1);
948         }
949 
950         return new Pair<>(0.0, 0);
951     }
952 
953     /**
954      * Compute gradient directly.
955      */
956     private void externalGradient() {
957         J = this.getObj().gradient(x);
958         if (this.getEqConstraint() != null) {
959             JE = this.getEqConstraint().jacobian(x);
960         }
961         if (this.getIqConstraint() != null) {
962             JI = this.getIqConstraint().jacobian(x);
963         }
964     }
965 
966     /**
967      * Computes the gradient of the objective function and the Jacobians of the
968      * constraints using forward finite differences (first-order accurate).
969      * <p>
970      * Each variable is perturbed independently by a small step size proportional
971      * to the square root of machine precision. Variables tightly bounded are
972      * gracefully ignored (gradient component set to zero) to prevent out-of-bounds
973      * evaluations and Hessian corruption.
974      * </p>
975      * <p>
976      * Deep copies of the working vectors are instantiated within the loop to
977      * strictly prevent side effects and aliasing issues with external black-box
978      * evaluators that may cache object references.
979      * </p>
980      */
981     private void forwardGradient() {
982 
983         int n = x.getDimension();
984         double sqrtEps = FastMath.sqrt(getSettings().getGradientEps());
985         double xi;
986         double h1;
987         double fRef = this.functionEval;
988         RealVector eqRef = this.eqEval;
989         RealVector iqRef = this.ineqEval;
990 
991         RealVector gradF = new ArrayRealVector(n);
992         RealMatrix gradEq = (getEqConstraint() != null) ? MatrixUtils.createRealMatrix(eqRef.getDimension(), n) : null;
993         RealMatrix gradIq = (getIqConstraint() != null) ? MatrixUtils.createRealMatrix(iqRef.getDimension(), n) : null;
994 
995         for (int i = 0; i < n; i++) {
996             xi = x.getEntry(i);
997             h1 = sqrtEps * FastMath.max(1.0, FastMath.abs(xi));
998 
999             Pair<Double, Integer> stepInfo = chooseStep(i, xi, h1, false);
1000             double h = stepInfo.getFirst();
1001 
1002             if (h == 0.0) {
1003                 gradF.setEntry(i, 0.0);
1004                 if (gradEq != null) {
1005                     gradEq.setColumnVector(i, new ArrayRealVector(eqEval.getDimension(), 0.0));
1006                 }
1007                 if (gradIq != null) {
1008                     gradIq.setColumnVector(i, new ArrayRealVector(ineqEval.getDimension(), 0.0));
1009                 }
1010             } else {
1011                 RealVector xPerturbed = x.copy();
1012                 xPerturbed.setEntry(i, xi + h);
1013 
1014                 double fPerturbed = getObj().value(xPerturbed);
1015                 gradF.setEntry(i, (fPerturbed - fRef) / h);
1016 
1017                 if (gradEq != null) {
1018                     // Logica residuo: (valPert - lower) - (valRef - lower) = valPert - valRef
1019                     RealVector eqPerturbed = getEqConstraint().value(xPerturbed).combineToSelf(1.0,-1.0,getEqConstraint().getLowerBound());
1020                     gradEq.setColumnVector(i, eqPerturbed.combineToSelf(1.0,-1.0,eqRef).mapDivideToSelf(h));
1021                 }
1022 
1023                 if (gradIq != null) {
1024                     RealVector iqPerturbed = getIqConstraint().value(xPerturbed).combineToSelf(1.0,-1.0,getIqConstraint().getLowerBound());
1025                     gradIq.setColumnVector(i, iqPerturbed.combineToSelf(1.0,-1.0,iqRef).mapDivideToSelf(h));
1026                 }
1027             }
1028         }
1029 
1030         this.J = gradF;
1031         this.JE = gradEq;
1032         this.JI = gradIq;
1033     }
1034 
1035     /**
1036      * Computes the gradient of the objective function and the Jacobians of the
1037      * constraints using centered finite differences (second-order accurate).
1038      * <p>
1039      * The base step size is proportional to the cube root of machine precision.
1040      * If a symmetric centered difference is not possible due to variable bounds,
1041      * the algorithm falls back to an asymmetric 3-point formula. This industrial-grade
1042      * fallback guarantees that the O(h^2) truncation error is preserved, preventing
1043      * catastrophic shocks to the BFGS Hessian approximation near active bounds.
1044      * </p>
1045      * <p>
1046      * Vectors are explicitly instantiated to prevent aliasing with stateful objective
1047      * functions. Furthermore, evaluations are strictly grouped by the perturbed point
1048      * (e.g., all functions evaluated at x+h, then all at x-h) to maximize cache-hit
1049      * ratios in complex black-box simulators.
1050      * </p>
1051      */
1052     private void centralGradient() {
1053 
1054         int n = x.getDimension();
1055         double hBase = FastMath.cbrt(getSettings().getGradientEps());
1056 
1057         RealVector gradF = new ArrayRealVector(n);
1058         RealMatrix gradEq = (getEqConstraint() != null) ? MatrixUtils.createRealMatrix(eqEval.getDimension(), n) : null;
1059         RealMatrix gradIq = (getIqConstraint() != null) ? MatrixUtils.createRealMatrix(ineqEval.getDimension(), n) : null;
1060 
1061         for (int i = 0; i < n; i++) {
1062             double xi = x.getEntry(i);
1063             double h1 = hBase * FastMath.max(1.0, FastMath.abs(xi));
1064 
1065             Pair<Double, Integer> stepInfo = chooseStep(i, xi, h1, true);
1066             double h = stepInfo.getFirst();
1067             int dir = stepInfo.getSecond();
1068 
1069             if (h == 0.0) {
1070                 // Variable is completely trapped, numerical derivative is unfeasible
1071                 gradF.setEntry(i, 0.0);
1072                 if (gradEq != null) {
1073                     gradEq.setColumnVector(i, new ArrayRealVector(eqEval.getDimension(), 0.0));
1074                 }
1075                 if (gradIq != null) {
1076                     gradIq.setColumnVector(i, new ArrayRealVector(ineqEval.getDimension(), 0.0));
1077                 }
1078 
1079             } else if (dir == 0) {
1080                 // -------------------------------------------------
1081                 // CLASSICAL CENTRAL DIFFERENCE
1082                 // -------------------------------------------------
1083                 RealVector xPlus = new ArrayRealVector(x);
1084                 RealVector xMinus = new ArrayRealVector(x);
1085                 xPlus.addToEntry(i, h);
1086                 xMinus.addToEntry(i, -h);
1087 
1088                 // --- CACHE-FRIENDLY EVALUATION: Everything at xPlus ---
1089                 double fPlus = getObj().value(xPlus);
1090                 // Calcoliamo i residui v = f(x) - lower per la differenza finita
1091                 RealVector eqPlus = (gradEq != null) ? getEqConstraint().value(xPlus).combineToSelf(1.0,-1.0,getEqConstraint().getLowerBound()) : null;
1092                 RealVector iqPlus = (gradIq != null) ? getIqConstraint().value(xPlus).combineToSelf(1.0,-1.0,getIqConstraint().getLowerBound()) : null;
1093 
1094                 // --- CACHE-FRIENDLY EVALUATION: Everything at xMinus ---
1095                 double fMinus = getObj().value(xMinus);
1096                 RealVector eqMinus = (gradEq != null) ? getEqConstraint().value(xMinus).combineToSelf(1.0,-1.0,getEqConstraint().getLowerBound()) : null;
1097                 RealVector iqMinus = (gradIq != null) ? getIqConstraint().value(xMinus).combineToSelf(1.0,-1.0,getIqConstraint().getLowerBound()) : null;
1098 
1099                 // Derivatives Calculation (La differenza tra residui è uguale alla differenza tra valori raw)
1100                 gradF.setEntry(i, (fPlus - fMinus) / (2.0 * h));
1101 
1102                 if (gradEq != null) {
1103                     // Sfrutto eqPlus gia' allocato per la combinazione: (eqPlus - eqMinus) * inv2h
1104                     gradEq.setColumnVector(i, eqPlus.combineToSelf(1.0, -1.0, eqMinus).mapDivideToSelf(2.0*h));
1105                 }
1106 
1107                 if (gradIq != null) {
1108                     gradIq.setColumnVector(i, iqPlus.combineToSelf(1.0, -1.0, iqMinus).mapDivideToSelf(2.0*h));
1109                 }
1110 
1111             } else {
1112                 // -------------------------------------------------
1113                 // ASYMMETRIC 3-POINT FORMULA (O(h^2) preservation)
1114                 // -------------------------------------------------
1115                 RealVector x1 = new ArrayRealVector(x);
1116                 RealVector x2 = new ArrayRealVector(x);
1117                 x1.addToEntry(i, h);
1118                 x2.addToEntry(i, 2.0 * h);
1119 
1120                 double f0 = functionEval; // Already evaluated at current x (residual if applicable)
1121 
1122                 // --- CACHE-FRIENDLY EVALUATION: Everything at x1 ---
1123                 double f1 = getObj().value(x1);
1124                 RealVector eq1 = (gradEq != null) ? getEqConstraint().value(x1).combineToSelf(1.0,-1.0,getEqConstraint().getLowerBound()) : null;
1125                 RealVector iq1 = (gradIq != null) ? getIqConstraint().value(x1).combineToSelf(1.0,-1.0,getIqConstraint().getLowerBound()) : null;
1126 
1127                 // --- CACHE-FRIENDLY EVALUATION: Everything at x2 ---
1128                 double f2 = getObj().value(x2);
1129                 RealVector eq2 = (gradEq != null) ? getEqConstraint().value(x2).combineToSelf(1.0,-1.0,getEqConstraint().getLowerBound()) : null;
1130                 RealVector iq2 = (gradIq != null) ? getIqConstraint().value(x2).combineToSelf(1.0,-1.0,getIqConstraint().getLowerBound()) : null;
1131 
1132                 // Derivatives Calculation
1133                 gradF.setEntry(i, (-3.0 * f0 + 4.0 * f1 - f2) / (2.0 * h));
1134 
1135                 if (gradEq != null) {
1136                     // eqEval è già un residuo (f(x) - L) calcolato in precedenza
1137                     RealVector dEq = eqEval.copy();
1138                     dEq.combineToSelf(-3.0, 4.0, eq1).combineToSelf(1.0, -1, eq2).mapDivideToSelf(2*h);
1139 
1140                     gradEq.setColumnVector(i, dEq);
1141                 }
1142 
1143                 if (gradIq != null) {
1144                     // ineqEval è già un residuo (f(x) - L) calcolato in precedenza
1145                    RealVector dIq = ineqEval.copy();
1146                     dIq.combineToSelf(-3.0, 4.0, iq1).combineToSelf(1.0, -1, iq2).mapDivideToSelf(2*h);
1147                     gradIq.setColumnVector(i, dIq);
1148                 }
1149             }
1150         }
1151 
1152         this.J = gradF;
1153         this.JE = gradEq;
1154         this.JI = gradIq;
1155     }
1156     /**
1157      * Set debug printer.
1158      * @param printer debug printer
1159      */
1160     public void setDebugPrinter(final DebugPrinter printer) {
1161         formatter.setDebugPrinter(printer);
1162     }
1163 
1164     /**
1165      * Build bounds constraint in the form of inequality.
1166      * @return number of bounds
1167      */
1168     private int buildBoundsAsInequalities() {
1169         if (getSimpleBounds() == null) {
1170             int n = getObj().dim();
1171             this.BIQ = null;
1172             LB = new ArrayRealVector(n, Double.NEGATIVE_INFINITY);
1173             UB = new ArrayRealVector(n, Double.POSITIVE_INFINITY);
1174             this.JB = null;
1175             return 0;
1176         }
1177         int n = getObj().dim();
1178         LB = (getSimpleBounds().getLower() != null) ?
1179              new ArrayRealVector(getSimpleBounds().getLower()) :
1180              new ArrayRealVector(n, Double.NEGATIVE_INFINITY);
1181         UB = (getSimpleBounds().getUpper() != null) ?
1182              new ArrayRealVector(getSimpleBounds().getUpper()) :
1183              new ArrayRealVector(n, Double.POSITIVE_INFINITY);
1184 
1185         java.util.ArrayList<double[]> rows = new java.util.ArrayList<>();
1186         java.util.ArrayList<Double> rhs = new java.util.ArrayList<>();
1187 
1188         for (int i = 0; i < n; i++) {
1189             if (Double.isFinite(LB.getEntry(i))) {
1190                 double[] row = new double[n];
1191                 row[i] = 1.0;
1192                 rows.add(row);
1193                 rhs.add(LB.getEntry(i));
1194             }
1195             if (Double.isFinite(UB.getEntry(i))) {
1196                 double[] row = new double[n];
1197                 row[i] = -1.0;
1198                 rows.add(row);
1199                 rhs.add(-UB.getEntry(i));
1200             }
1201         }
1202 
1203         if (rows.isEmpty()) {
1204             this.BIQ = null;
1205             this.JB = null;
1206             return 0;
1207         }
1208 
1209         double[][] amat = rows.toArray(new double[rows.size()][]);
1210         double[] bvec = new double[rhs.size()];
1211         for (int k = 0; k < rhs.size(); k++) {
1212             bvec[k] = rhs.get(k);
1213         }
1214 
1215         this.BIQ = new LinearInequalityConstraint(new Array2DRowRealMatrix(amat, false), new ArrayRealVector(bvec, false));
1216         this.JB = this.BIQ.jacobian(null);
1217         return JB.getRowDimension();
1218     }
1219 
1220     /**
1221      * Build initial guess taking account the bounds.
1222      * @return initial guess
1223      */
1224     private RealVector initGuess() {
1225         int n = this.getObj().dim();
1226         SimpleBounds sb = this.getSimpleBounds();
1227         double[] lbArr = (sb != null) ? sb.getLower() : null;
1228         double[] ubArr = (sb != null) ? sb.getUpper() : null;
1229 
1230         double[] xArr = getStartPoint();
1231         if (xArr == null) {
1232             xArr = new double[n];
1233         }
1234 
1235         for (int i = 0; i < n; i++) {
1236             double li = (lbArr != null && i < lbArr.length && Double.isFinite(lbArr[i])) ? lbArr[i] : Double.NEGATIVE_INFINITY;
1237             double ui = (ubArr != null && i < ubArr.length && Double.isFinite(ubArr[i])) ? ubArr[i] : Double.POSITIVE_INFINITY;
1238 
1239             if (Double.isFinite(li) && Double.isFinite(ui)) {
1240                 xArr[i] = 0.5 * (li + ui);
1241             } else if (Double.isFinite(ui)) {
1242                 xArr[i] = ui - 1.0;
1243             } else if (Double.isFinite(li)) {
1244                 xArr[i] = li + 1.0;
1245             } else {
1246                 xArr[i] = 0.0;
1247             }
1248         }
1249         return new ArrayRealVector(xArr, false);
1250     }
1251 
1252     /**
1253      * Project direction adjust QP solution direction to be sure respect the bounds.
1254      * @param xVec current point
1255      * @param dVec direction
1256      */
1257     private void projectDirectionInPlace(RealVector xVec, RealVector dVec) {
1258         final int n = xVec.getDimension();
1259         for (int i = 0; i < n; i++) {
1260             final double xi      = xVec.getEntry(i);
1261             final double minStep = LB.getEntry(i) - xi;
1262             final double maxStep = UB.getEntry(i) - xi;
1263             final double di      = FastMath.min(FastMath.max(dVec.getEntry(i), minStep), maxStep);
1264             dVec.setEntry(i, di);
1265         }
1266     }
1267 
1268 }