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 java.util.ArrayList;
20 import java.util.List;
21
22 import org.hipparchus.exception.MathIllegalArgumentException;
23 import org.hipparchus.linear.ArrayRealVector;
24 import org.hipparchus.linear.DecompositionSolver;
25 import org.hipparchus.linear.MatrixUtils;
26 import org.hipparchus.linear.RealMatrix;
27 import org.hipparchus.linear.RealVector;
28 import org.hipparchus.optim.OptimizationData;
29 import org.hipparchus.optim.nonlinear.scalar.ObjectiveFunction;
30 import org.hipparchus.util.FastMath;
31 import org.hipparchus.util.Pair;
32 import org.hipparchus.util.Precision;
33
34 /**
35 * Implements the dual active-set method by Goldfarb and Idnani (1983) for
36 * solving strictly convex quadratic programs of the form:
37 *
38 * <pre>
39 * minimize (1/2) x^T G x + g0^T x
40 * subject to CE^T x = ce0 (equality constraints)
41 * CI^T x >= ci0 (inequality constraints)
42 * lb <= Ax <= ub (bounded constraints)
43 * </pre>
44 *
45 * <p>
46 * Uses an incremental QR factorization updater (QRUpdater) for managing active
47 * constraints and maintains multipliers for dual and primal steps.
48 * </p>
49 *
50 * @see <a href="https://doi.org/10.1137/0603006">Goldfarb and Idnani (1983)</a>
51 * @since 1.11
52 */
53 public class QPDualActiveSolver extends QPOptimizer {
54
55 /** No-error code. */
56 public static final double ERROR_NONE = 0.0;
57
58 /** Error code reported in lambda[0] when the Hessian decomposition fails. */
59 public static final double ERROR_CHOLESKY_DECOMPOSITION = -1.0;
60
61 /** Error code reported in lambda[0] when equality constraints are dependent. */
62 public static final double ERROR_DEPENDENT_EQUALITIES = -2.0;
63
64 /** Error code reported in lambda[0] when max iterations are reached. */
65 public static final double ERROR_MAX_ITERATIONS = -3.0;
66
67 /** Error code reported when numerical issue occurs. */
68 public static final double ERROR_NUMERICAL = -4.0;
69
70 /** Error code reported when no solution is found (infeasible). */
71 public static final double ERROR_INFEASIBLE = -5.0;
72
73 /** Machine epsilon for tolerance checks. */
74 private static final double EPS = FastMath.ulp(1.0);
75
76 /**
77 * Maximum number of iterations allowed. Will be adjusted based on the problem
78 * dimension.
79 */
80 private int maxIter;
81
82 /** Quadratic function representing 1/2 x^T G x + g0^T x. */
83 private QuadraticFunction function;
84
85 /** Equality constraint data (CE^T x + ce0 = 0). */
86 private LinearEqualityConstraint eqConstraints;
87
88 /** Inequality constraint data (CI^T x + ci0 >= 0). */
89 private LinearInequalityConstraint iqConstraints;
90
91 /** Bounded constraint data (lower <= Ax <= upper). */
92 private LinearBoundedConstraint bConstraints;
93
94 /** QP Settings */
95 private QPDualActiveSolverOption settings;
96
97 /**
98 * Tolerance for symmetric matrix decomposition.
99 *
100 * @since 4.1
101 */
102 private MatrixDecompositionTolerance matrixDecompositionTolerance;
103
104 /** Simple constructor.
105 */
106 public QPDualActiveSolver() {
107 // nothing to do
108 }
109
110 /**
111 * Parses optimization data to extract the objective function and various
112 * constraint sets.
113 *
114 * @param optData optimization data
115 */
116 @Override
117 protected void parseOptimizationData(final OptimizationData... optData) {
118 super.parseOptimizationData(optData);
119 // Reset QP problem to reuse the same instance of the QP solver
120 this.maxIter = 1000;
121 this.function = null;
122 this.eqConstraints = null;
123 this.iqConstraints = null;
124 this.bConstraints = null;
125 this.settings=new QPDualActiveSolverOption();
126 this.matrixDecompositionTolerance = new MatrixDecompositionTolerance(EPS);
127
128
129 for (OptimizationData data : optData) {
130 if (data instanceof ObjectiveFunction) {
131 function = (QuadraticFunction) ((ObjectiveFunction) data).getObjectiveFunction();
132 } else if (data instanceof LinearEqualityConstraint) {
133 eqConstraints = (LinearEqualityConstraint) data;
134 } else if (data instanceof LinearInequalityConstraint) {
135 iqConstraints = (LinearInequalityConstraint) data;
136 } else if (data instanceof LinearBoundedConstraint) {
137 bConstraints = (LinearBoundedConstraint) data;
138 } else if (data instanceof MatrixDecompositionTolerance) {
139 matrixDecompositionTolerance = (MatrixDecompositionTolerance) data;
140 }
141 else if(data instanceof QPDualActiveSolverOption)
142 {
143 settings = (QPDualActiveSolverOption) data;
144 }
145 }
146 }
147
148
149
150 /**
151 * Finds the step length for a primal move toward a violated constraint.
152 * Modern optimized and numerically stable version.
153 *
154 * @param z search direction vector
155 * @param ai constraint row vector
156 * @param sv current violation offset (slack/surplus value)
157 * @param equality true if the constraint is an equality constraint
158 * @return the primal step size, or Double.POSITIVE_INFINITY if the constraint does not block
159 */
160 private double findPrimalStep(final RealVector z,
161 final RealVector ai,
162 final double sv,
163 final boolean equality) {
164
165 double sumA = 0.0;
166 double sumB = 0.0;
167 double aiNormSq = 0.0;
168 double zNormSq = 0.0;
169
170 final int dimension = ai.getDimension();
171
172 for (int i = 0; i < dimension; i++) {
173 final double aiValue = ai.getEntry(i);
174 final double zValue = z.getEntry(i);
175 final double product = aiValue * zValue;
176
177 sumA += product;
178 sumB += FastMath.abs(product);
179 aiNormSq += aiValue * aiValue;
180 zNormSq += zValue * zValue;
181 }
182
183 if (sumB <= Precision.EPSILON) {
184 return Double.POSITIVE_INFINITY;
185 }
186
187 final double absSumA = FastMath.abs(sumA);
188
189 double temp = sumB + 0.1 * absSumA;
190 double tempA = sumB + 0.2 * absSumA;
191
192 if (temp <= sumB || tempA <= temp) {
193 return Double.POSITIVE_INFINITY;
194 }
195
196 final double sumC =
197 FastMath.sqrt(aiNormSq) * FastMath.sqrt(zNormSq);
198
199 temp = sumC + 0.1 * absSumA;
200 tempA = sumC + 0.2 * absSumA;
201
202 if (temp <= sumC || tempA <= temp) {
203 return Double.POSITIVE_INFINITY;
204 }
205
206 final double alpha = -sv / sumA;
207
208 if (!equality && alpha < 0.0) {
209 return Double.POSITIVE_INFINITY;
210 }
211
212 return alpha;
213 }
214
215
216
217
218 /**
219 * Finds the blocking active inequality for the dual move.
220 *
221 * If reverseStep is false, the algorithm moves in the usual positive
222 * direction and an active inequality can block only if r_i > 0.
223 *
224 * If reverseStep is true, the algorithm moves in the opposite direction
225 * and an active inequality can block only if r_i < 0.
226 *
227 * The returned step is always a positive length:
228 *
229 * alpha = u_i / |r_i|
230 *
231 * Active equalities are never removed.
232 *
233 * @param u current active multipliers
234 * @param r dual direction
235 * @param activeSet active-set global constraint indices
236 * @param me number of equality constraints
237 * @param reverseStep true if the primal/dual step is taken in the negative direction
238 * @return pair containing active-set position to drop and positive blocking length;
239 * if no blocker exists, returns (-1, +Infinity)
240 */
241 private Pair<Integer, Double> findDualBlockingConstraint(final RealVector u,
242 final RealVector r,
243 final List<Integer> activeSet,
244 final int me,
245 final boolean reverseStep) {
246 if (activeSet.isEmpty()) {
247 return new Pair<>(-1, Double.POSITIVE_INFINITY);
248 }
249
250 double alpha = Double.POSITIVE_INFINITY;
251 int block = -1;
252
253 for (int i = 0; i < activeSet.size(); i++) {
254
255 /*
256 * Only active inequalities can leave.
257 * Active equalities must never be dropped.
258 */
259 if (activeSet.get(i) < me) {
260 continue;
261 }
262
263 final double ri = r.getEntry(i);
264 final double absRi=FastMath.abs(ri);
265
266 if (!reverseStep) {
267
268 /*
269 * Forward direction:
270 *
271 * u_i(alpha) = u_i - alpha * r_i
272 *
273 * Only r_i > 0 can drive u_i to zero.
274 */
275 if (ri <= 0.0) {
276 continue;
277 }
278
279 } else {
280
281 /*
282 * Reverse direction:
283 *
284 * signedStep = -alpha
285 * u_i(new) = u_i - signedStep * r_i
286 * = u_i + alpha * r_i
287 *
288 * Only r_i < 0 can drive u_i to zero.
289 */
290 if (ri >= 0.0) {
291 continue;
292 }
293 }
294
295
296 final double cand = u.getEntry(i) / FastMath.abs(ri);
297
298
299
300
301
302 if (cand < alpha) {
303 alpha = cand;
304 block = i;
305 }
306 }
307
308 return new Pair<>(block, alpha);
309 }
310
311 /**
312 * Updates multipliers when adding a constraint.
313 *
314 * @param u current multipliers or null
315 * @param r dual direction
316 * @param alpha step length
317 * @param partial new partial multiplier
318 * @return updated multipliers
319 */
320 private RealVector updateMultipliersOnAddition(final RealVector u,
321 final RealVector r,
322 final double alpha,
323 final double partial) {
324 if (u.getDimension() == 0) {
325 RealVector v = new ArrayRealVector(1,partial);
326 return v;
327 }
328
329 // Original: return u.add(r.mapMultiply(-alpha)).append(partial);
330 // Optimized: copy once, combine in-place, then append
331
332 u.combineToSelf(1.0, -alpha, r);
333
334 return u.append(partial);
335
336 }
337
338 /**
339 * Updates multipliers when removing a constraint.
340 *
341 * @param u current multipliers
342 * @param r dual direction
343 * @param alpha step length
344 * @param dropIndex index to remove
345 * @return updated multipliers
346 */
347 private RealVector updateMultipliersOnRemoval(final RealVector u,
348 final RealVector r,
349 final double alpha,
350 final int dropIndex) {
351 if (u.getDimension() == 1) {
352 return new ArrayRealVector(0, 0);
353 }
354
355 // Original: RealVector tmp = u.add(r.mapMultiply(-alpha));
356 // Optimized: copy once, combine in-place
357
358 u.combineToSelf(1.0, -alpha, r);
359
360 int size = u.getDimension();
361
362 if (dropIndex == 0) {
363 return u.getSubVector(1, size - 1);
364 } else if (dropIndex == size - 1) {
365 return u.getSubVector(0, size - 1);
366 }
367
368 RealVector head = u.getSubVector(0, dropIndex);
369 RealVector tail = u.getSubVector(dropIndex + 1, size - dropIndex - 1);
370 RealVector result= head.append(tail);
371 return result;
372 }
373
374
375
376 /**
377 * Removes a multiplier at a specific index.
378 *
379 * @param u the multiplier vector
380 * @param dropIndex the index to drop
381 * @return the vector without the dropped multiplier
382 */
383 private RealVector removeMultiplierAt(final RealVector u, final int dropIndex) {
384 if (u.getDimension() == 1) {
385 return new ArrayRealVector(0, 0);
386 }
387 if (dropIndex == 0) {
388 return u.getSubVector(1, u.getDimension() - 1);
389 }
390 if (dropIndex == u.getDimension() - 1) {
391 return u.getSubVector(0, u.getDimension() - 1);
392 }
393 final RealVector head = u.getSubVector(0, dropIndex);
394 final RealVector tail = u.getSubVector(dropIndex + 1, u.getDimension() - dropIndex - 1);
395 return head.append(tail);
396 }
397
398 /**
399 // * Finds the most violated constraint using normalized violations and an embedded numerical noise filter.
400 // * <p>
401 // * Equality constraints use absolute normalized violation.
402 // * Inequality/bound constraints use one-sided normalized violation.
403 // * The noise filter evaluates the exact numerical floating-point stability of the constraint residual
404 // * relative to the magnitude of the terms involved in its calculation.
405 // * </p>
406 // *
407 // * @param sv current constraint evaluation (residuals)
408 // * @param weights constraint weights
409 // * @param blackList dependent constraints to ignore
410 // * @param activeSet constraints currently in the active set
411 // * @param me number of equality constraints
412 // * @param C the constraint matrix
413 // * @param c0 the constraint constant vector
414 // * @param x the current primal point
415 // * @return a Pair containing the index of the most violated constraint and the maximum violation value
416 // */
417 private Pair<Integer, Double> mostViolatedConstraintNormalized(final RealVector sv,
418 final RealVector weights,
419 final boolean[] active ,
420 final int me,
421 final RealMatrix C,
422 final RealVector c0,
423 final RealVector x) {
424 double cvMax = 0.0;
425 int kViolated = -1;
426
427 for (int k = 0; k < sv.getDimension(); k++) {
428 if (active[k] ) {
429 continue;
430 }
431
432
433
434
435
436 final double residual = sv.getEntry(k);
437 final double absResidual = FastMath.abs(residual);
438
439 // 1. Scaled Violation
440 final double scaledViolation;
441 if (k < me) {
442 scaledViolation = absResidual * weights.getEntry(k);
443 } else {
444 scaledViolation = -residual * weights.getEntry(k);
445 }
446
447 // 2. Convergence Test: skip if not greater than current maximum
448 if (scaledViolation <= cvMax) {
449 continue;
450 }
451
452
453 final RealVector rowC=C.getRowVector(k);
454 // 3. --- NOISE FILTER ---
455 double absSum = FastMath.abs(c0.getEntry(k));
456 for (int i = 0; i < x.getDimension(); i++) {
457 absSum += FastMath.abs(rowC.getEntry(i) * x.getEntry(i));
458 }
459
460 double tempA = absSum + absResidual;
461 if (tempA <= absSum) {
462 continue; // Noise detected
463 }
464
465 double tempB = absSum + 1.5 * absResidual;
466 if (tempB <= tempA) {
467 continue; // Noise detected
468 }
469
470 kViolated = k;
471 cvMax = scaledViolation;
472 }
473
474 return new Pair<>(kViolated, cvMax);
475 }
476
477
478
479
480 /**
481 * Main optimization routine.
482 *
483 * @return the optimal solution or null if infeasible
484 */
485 @Override
486 public LagrangeSolution doOptimize() {
487
488
489
490 RealVector g0 = function.getQ();
491 double g = function.getD();
492 int n = function.getP().getColumnDimension();
493
494
495 int p = (eqConstraints != null) ? eqConstraints.dimY():0;
496 int m1 = (iqConstraints != null) ? iqConstraints.dimY() : 0;
497 int b1 = (bConstraints != null) ? bConstraints.dimY() : 0;
498 int m = m1 + 2 * b1;
499
500 final int mc = p + m;
501 RealMatrix C = null;
502 RealVector c0 = null;
503 RealVector weights = null;
504
505 if (mc > 0) {
506
507 QPConstraintSystem record = buildGlobalConstraints(n);
508 C=record.C;
509 c0=record.c0;
510 weights = record.weights;
511 }
512 RealMatrix G=null;
513 RealVector x=null;
514 RealMatrix L=null;
515 RealMatrix L1=null;
516 QRUpdater qrUpdater=null;
517
518 if (settings.getMatrixMode() == QPMatrixMode.FULL) {
519 G = function.getP();
520 try {
521 final double eps = matrixDecompositionTolerance.getEpsMatrixDecomposition();
522 final RegularizedCholeskyDecomposition cholesky =
523 new RegularizedCholeskyDecomposition(G, settings.getEps(), settings.getEps());
524 DecompositionSolver solver = cholesky.getSolver();
525
526 x = solver.solve(g0).mapMultiply(-1.0);
527 L = cholesky.getL();
528
529 L1 = inverseLowerTriangular(L);
530 qrUpdater = new QRUpdater(L1);
531 } catch (MathIllegalArgumentException ex) {
532 // Matrix is not positive definite, return failure solution
533 return buildFailureSolution(ERROR_CHOLESKY_DECOMPOSITION);
534 }
535 } else if (settings.getMatrixMode() == QPMatrixMode.CHOLESKY) {
536
537 L = function.getP();
538 G = L.multiplyTransposed(L);
539 L1 = inverseLowerTriangular(L);
540
541 x = L1.preMultiply(L1.operate(g0)).mapMultiply(-1.0);
542 qrUpdater = new QRUpdater(L1);
543 } else {
544
545 L1 = function.getP();
546 L = inverseLowerTriangular(L1);
547 G = L.multiplyTransposed(L);
548
549
550 x = L1.preMultiply(L1.operate(g0)).mapMultiply(-1.0);
551 qrUpdater = new QRUpdater(L1);
552 }
553
554
555 if (mc == 0) {
556 double obj = 0.5 * x.dotProduct(G.operate(x)) + g0.dotProduct(x) + g;
557 return new LagrangeSolution(x, new ArrayRealVector(0, 0), obj);
558 }
559
560
561 // Maximum iterations adjusted based on problem dimension
562 this.maxIter = 40 * (n + mc);
563
564 List<Integer> active = new ArrayList<>();
565 final boolean[] activeMask = new boolean[mc];
566 RealVector u = new ArrayRealVector(0, 0);
567 RealVector r = new ArrayRealVector(0, 0);
568 RealVector d = null;
569 RealVector z = null;
570 int iteration = 0;
571 boolean refinementDone = false;
572 // Active-set loop for all constraints
573 while (mc != 0 && iteration++ < maxIter) {
574
575 // Check Dual Feasibility delete constraint with negative multiplier and recalculate solution
576 boolean dualFeasible = false;
577
578 // Continua finché non è dual-fattibile o non svuotiamo il set
579 while (!dualFeasible && !active.isEmpty()) {
580 dualFeasible = true;
581 int dropIndex = -1;
582
583
584 // // 1. Identifica il primo moltiplicatore negativo puro
585 for (int j = 0; j < active.size(); j++) {
586 if (active.get(j) >= p) { // Se è una disuguaglianza
587 if (u.getEntry(j) < 0.0) {
588 dropIndex = j;
589 dualFeasible = false;
590 break; // Esce al primo negativo incontrato
591 }
592 }
593 }
594
595 // 2. Se trovato, effettua il drop e riesegui il KKT da capo
596 if (dropIndex >= 0) {
597 qrUpdater.deleteConstraint(dropIndex);
598 final int removedConstraint = active.remove(dropIndex);
599 activeMask[removedConstraint] = false;
600 u=removeMultiplierAt(u, dropIndex);
601 Pair<RealVector, RealVector> xy = recomputeXY(x, G, g0, C, c0, qrUpdater, active);
602 x = xy.getFirst();
603 u = xy.getSecond();
604
605 }
606 }
607
608
609 RealVector sv;
610 // Evaluate constraints sv = C.preMultiply(x).add(c0);
611 sv = C.operate(x);
612 sv.combineToSelf(1.0, 1.0, c0);
613 // Convergence test: find the most violated NON-active constraint
614 Pair<Integer, Double> violationInfo = mostViolatedConstraintNormalized(sv, weights, activeMask, p, C, c0, x);
615 int kViolated = violationInfo.getKey();
616 double cvMax = violationInfo.getValue();
617
618
619 if (cvMax <= settings.getEps() && refinementDone) {
620 break; // Solution found
621 }
622
623 // Evaluate convergence: no significantly violated NON-active constraint
624 if (cvMax <= settings.getEps() && !refinementDone) {
625
626 kViolated = -1;
627 refinementDone = true;
628
629 Pair<RealVector, RealVector> xy = recomputeXY(x, G, g0, C, c0, qrUpdater, active);
630 x = xy.getFirst();
631 u = xy.getSecond();
632
633
634
635 }
636
637
638
639 // Active loop evaluation
640 while (iteration++ < maxIter) {
641 if (kViolated < 0) {
642 break;
643 }
644
645 double t1;
646 double t2;
647 double t = 0;
648 double signedStep=0;
649 double uPartial = 0;
650 int dropIndex;
651 RealVector np;
652
653 final int constraintIndex = kViolated;
654 final boolean equality = constraintIndex < p;
655
656 // Dual step loop update multiplier and x (if step is also in primal)
657 // until primal step is not done
658 while (iteration++ < maxIter) {
659 np = C.getRowVector(constraintIndex);
660 sv.setEntry(constraintIndex, np.dotProduct(x) + c0.getEntry(constraintIndex));
661 d = qrUpdater.computeD(np);
662 z = qrUpdater.computeZ(d);
663 r = qrUpdater.solveR(d);
664
665 t1 = findPrimalStep(z, np, sv.getEntry(constraintIndex), equality);
666 final boolean reverseStep = equality && sv.getEntry(constraintIndex) > 0.0;
667 t1=FastMath.abs(t1);
668 Pair<Integer, Double> dualStep = findDualBlockingConstraint(u, r, active, p,reverseStep);
669 t2 = dualStep.getValue();
670 dropIndex = dualStep.getKey();
671 t = FastMath.min(t1, t2);
672 signedStep = reverseStep ? -t : t;
673
674 if (!Double.isFinite(t)) {
675 return cvMax < this.settings.getEpsRelaxation() ?
676 buildSolution(x, u, active, G, g0, g, p, m) :
677 buildFailureSolution(ERROR_INFEASIBLE);
678 }
679
680 if (t1 <= t2) {
681 break; // Primal full step (exit from dual step loop)
682 } else {
683 // Manage dual step
684 if (t1 < Double.POSITIVE_INFINITY) {
685 // Step is also in primal x = x.add(z.mapMultiply(t));
686 x.combineToSelf(1.0, signedStep, z);
687 }
688 uPartial += signedStep;
689 u = updateMultipliersOnRemoval(u, r, signedStep, dropIndex);
690
691 qrUpdater.deleteConstraint(dropIndex);
692 final int removedConstraint = active.remove(dropIndex);
693 activeMask[removedConstraint] = false;
694
695 }
696 }
697
698
699 // Manage full step
700 if (active.size() < n && qrUpdater.addConstraint(d)) {
701 active.add(constraintIndex);
702 activeMask[constraintIndex] = true;
703 // Step rimal x = x.add(z.mapMultiply(t));
704 x.combineToSelf(1.0, signedStep, z);
705 uPartial += signedStep;
706 u = updateMultipliersOnAddition(u, r, signedStep, uPartial);
707
708 break; // Re-evaluate convergence
709 } else {
710
711 return buildFailureSolution(ERROR_DEPENDENT_EQUALITIES);
712 }
713 }
714 }
715
716 if (iteration == maxIter) {
717 return buildFailureSolution(ERROR_MAX_ITERATIONS);
718 }
719
720 return buildSolution(x, u, active, G, g0, g, p, m);
721 }
722
723 /**
724 * Builds the final solution object with primal x and multipliers lambda.
725 *
726 * @param x solution
727 * @param u active set multipliers
728 * @param activeSet active set constraints
729 * @param G square matrix of weights for quadratic terms
730 * @param g0 vector of weights for linear terms
731 * @param g constant term
732 * @param p number of equalities
733 * @param m number of inequalities
734 * @return the optimal solution
735 */
736 private LagrangeSolution buildSolution(final RealVector x,
737 final RealVector u,
738 final List<Integer> activeSet,
739 final RealMatrix G,
740 final RealVector g0,
741 final double g,
742 final int p,
743 final int m) {
744 final RealVector lambda = new ArrayRealVector(p + m);
745 if (!activeSet.isEmpty()) {
746 for (int i = 0; i < activeSet.size(); i++) {
747 lambda.setEntry(activeSet.get(i), u.getEntry(i));
748 }
749 }
750 final double value = 0.5 * x.dotProduct(G.operate(x)) + g0.dotProduct(x) + g;
751 return new LagrangeSolution(x, lambda, value);
752 }
753
754 /**
755 * Computes the inverse of a lower-triangular matrix via forward
756 * substitution.
757 *
758 * @param L lower triangular matrix
759 * @return inverse of Lower Triangular Matrix
760 */
761 private RealMatrix inverseLowerTriangular(final RealMatrix L) {
762 final int n = L.getRowDimension();
763 final RealMatrix Linv = MatrixUtils.createRealMatrix(n, n);
764 for (int i = 0; i < n; i++) {
765 final RealVector e = new ArrayRealVector(n);
766 e.setEntry(i, 1.0);
767 MatrixUtils.solveLowerTriangularSystem(L, e);
768 Linv.setColumnVector(i, e);
769 }
770 return Linv;
771 }
772
773 /**
774 * Helper to build a failure solution structure.
775 *
776 * @param errorCode the failure code
777 * @return a LagrangeSolution representing the failure
778 */
779 private LagrangeSolution buildFailureSolution(final double errorCode) {
780 return new LagrangeSolution(
781 new ArrayRealVector(0, 0),
782 new ArrayRealVector(1, errorCode),
783 0
784 );
785 }
786
787 /**
788 * Incremental recomputation of primal x and active multipliers y after a change
789 * in the working set (for example after dropping one negative active multiplier).
790 *
791 * Unlike the absolute KKT reconstruction, this version starts from the current
792 * primal point xCurrent and only applies:
793 *
794 * 1) an active-space correction to reduce the residuals of the current active set,
795 * 2) a free-space correction to improve projected stationarity,
796 * 3) a recomputation of the active multipliers consistent with the corrected x.
797 *
798 * Convention:
799 * - objective: 0.5 * x^T G x + g0^T x, with G = L*L^T
800 * - constraints: C^T x + c0 >= 0
801 *
802 * @param x the current primal point
803 * @param G the quadratic objective matrix
804 * @param g0 the linear objective vector
805 * @param C the constraint matrix
806 * @param c0 the constraint constants
807 * @param qrUpdater the factorization updater
808 * @param active the current active set
809 * @return a Pair containing the corrected primal x and the active multipliers y
810 */
811 private Pair<RealVector, RealVector> recomputeXY(final RealVector x,
812 final RealMatrix G,
813 final RealVector g0,
814 final RealMatrix C,
815 final RealVector c0,
816 final QRUpdater qrUpdater,
817 final List<Integer> active) {
818
819 final int nAct = active.size();
820
821
822 // --------------------------------------------------------------
823 // 1) Active-space correction: reduce active residuals starting from xCurrent
824 // rp_i = -(a_i^T x + c0_i)
825 // --------------------------------------------------------------
826 if (nAct > 0) {
827 final double[] rpData = new double[nAct];
828 for (int i = 0; i < nAct; i++) {
829 final int idx = active.get(i);
830 final RealVector ai = C.getRowVector(idx);
831 rpData[i] = -(ai.dotProduct(x) + c0.getEntry(idx));
832 }
833 final RealVector rp = new ArrayRealVector(rpData, false);
834
835 final RealVector tActive = qrUpdater.solveRT(rp);
836 if (tActive == null) {
837 return null; // singular / numerically unsafe
838 }
839
840 // Original: xRec = xRec.add(qrUpdater.applyJActive(tActive));
841 // Optimized: in-place addition to avoid object allocation
842 x.combineToSelf(1.0, 1.0, qrUpdater.applyJActive(tActive));
843 }
844
845 // --------------------------------------------------------------
846 // 2) Free-space correction: improve projected stationarity
847 // grad = G*x + g0
848 // --------------------------------------------------------------
849
850 // Original: final RealVector gMid = G.operate(xRec).add(g0);
851 // Optimized: allocate once for G.operate(xRec), then combine in-place
852 final RealVector gMid = G.operate(x);
853 gMid.combineToSelf(1.0, 1.0, g0);
854
855 final RealVector dMid = qrUpdater.computeD(gMid);
856
857 // Original: xRec = xRec.subtract(qrUpdater.computeZ(dMid));
858 // Optimized: in-place subtraction (xRec = 1.0 * xRec + (-1.0) * Z)
859 x.combineToSelf(1.0, -1.0, qrUpdater.computeZ(dMid));
860
861 // --------------------------------------------------------------
862 // 3) Recompute active multipliers from corrected xRec
863 // --------------------------------------------------------------
864 if (nAct == 0) {
865 return new Pair<>(x, new ArrayRealVector(0));
866 }
867
868 RealVector yActive = qrUpdater.solveR(dMid);
869
870 if (yActive == null) {
871 return null;
872 }
873
874 if (yActive.getDimension() > nAct) {
875 yActive = yActive.getSubVector(0, nAct);
876 }
877
878 return new Pair<>(x, yActive);
879 }
880
881 /**
882 * Private container for the integrated QP system.
883 * Designed to be stack-allocated.
884 */
885 private static final class QPConstraintSystem {
886 /** Global constraint matrix C (n x mc) where columns are constraint gradients. */
887 private final RealMatrix C;
888 /** Right-hand side vector c0 for the QP problem. */
889 private final RealVector c0;
890 /** Normalization weights based on the 2-norm of each constraint gradient. */
891 private final RealVector weights;
892
893 private QPConstraintSystem(RealMatrix C, RealVector c0, RealVector weights) {
894 this.C = C;
895 this.c0 = c0;
896 this.weights = weights;
897 }
898 }
899
900 /**
901 * Builds the virtual row-oriented QP constraint system.
902 *
903 * <p>The global constraint matrix is represented as:</p>
904 *
905 * <pre>
906 * A = [ Ae ]
907 * [ Ai ]
908 * [ Ab ]
909 * [-Ab ]
910 * </pre>
911 *
912 * <p>No global physical matrix and no transpose are created.</p>
913 *
914 * @param n number of primal variables
915 * @return integrated constraint system
916 */
917 private QPConstraintSystem buildGlobalConstraints(final int n) {
918
919 final int p = eqConstraints != null ? eqConstraints.dimY() : 0;
920
921 final int m1 = iqConstraints != null ? iqConstraints.dimY() : 0;
922
923 final int b1 = bConstraints != null ? bConstraints.dimY() : 0;
924
925 final int mc = p + m1 + 2 * b1;
926
927 /*
928 * Original row-oriented matrices.
929 *
930 * No transpose and no coefficient copy are performed.
931 */
932 final RealMatrix Ae = eqConstraints != null ? eqConstraints.getA() : null;
933
934 final RealMatrix Ai = iqConstraints != null ? iqConstraints.jacobian(null) : null;
935
936 final RealMatrix Ab = bConstraints != null ? bConstraints.jacobian(null) : null;
937
938 /*
939 * Virtual global matrix:
940 *
941 * [ Ae ]
942 * A = [ Ai ]
943 * [ Ab ]
944 * [-Ab ]
945 */
946 final RealMatrix A = new QPConstraintMatrix(n,Ae, Ai, Ab);
947
948 final double[] c0Data = new double[mc];
949 final double[] wData = new double[mc];
950
951 final double safeMin = Precision.EPSILON;
952
953 /*
954 * Equality constraints:
955 *
956 * Ae_j x - be_j = 0
957 */
958 if (p > 0) {
959
960 final RealVector be = eqConstraints.getLowerBound();
961
962 for (int j = 0; j < p; j++) {
963
964 c0Data[j] = -be.getEntry(j);
965
966 double sumSq = 0.0;
967
968 for (int i = 0; i < n; i++) {
969 final double value = Ae.getEntry(j, i);
970 sumSq += value * value;
971 }
972
973 final double norm = FastMath.sqrt(sumSq);
974
975 wData[j] = norm > safeMin ?
976 1.0 / norm : 0.0;
977 }
978 }
979
980 /*
981 * Inequality constraints:
982 *
983 * Ai_j x - bi_j >= 0
984 */
985 if (m1 > 0) {
986
987 final RealVector bi = iqConstraints.getLowerBound();
988
989 for (int j = 0; j < m1; j++) {
990
991 final int globalIndex = p + j;
992
993 c0Data[globalIndex] = -bi.getEntry(j);
994
995 double sumSq = 0.0;
996
997 for (int i = 0; i < n; i++) {
998 final double value = Ai.getEntry(j, i);
999 sumSq += value * value;
1000 }
1001
1002 final double norm = FastMath.sqrt(sumSq);
1003
1004 wData[globalIndex] = norm > safeMin ?
1005 1.0 / norm : 0.0;
1006 }
1007 }
1008
1009 /*
1010 * Bounded constraints:
1011 *
1012 * Lower:
1013 *
1014 * Ab_j x - lb_j >= 0
1015 *
1016 * Upper:
1017 *
1018 * -Ab_j x + ub_j >= 0
1019 *
1020 * Both rows have the same Euclidean norm.
1021 */
1022 if (b1 > 0) {
1023
1024 final RealVector lb = bConstraints.getLowerBound();
1025 final RealVector ub = bConstraints.getUpperBound();
1026
1027 final int lowerOffset = p + m1;
1028 final int upperOffset = lowerOffset + b1;
1029
1030 for (int j = 0; j < b1; j++) {
1031
1032 final int lowerIndex = lowerOffset + j;
1033 final int upperIndex = upperOffset + j;
1034
1035 c0Data[lowerIndex] = -lb.getEntry(j);
1036 c0Data[upperIndex] = ub.getEntry(j);
1037
1038 double sumSq = 0.0;
1039
1040 for (int i = 0; i < n; i++) {
1041 final double value = Ab.getEntry(j, i);
1042 sumSq += value * value;
1043 }
1044
1045 final double norm = FastMath.sqrt(sumSq);
1046
1047 final double inverseNorm = norm > safeMin ?
1048 1.0 / norm : 0.0;
1049
1050 wData[lowerIndex] = inverseNorm;
1051 wData[upperIndex] = inverseNorm;
1052 }
1053 }
1054
1055 return new QPConstraintSystem(
1056 A,
1057 new ArrayRealVector(c0Data, false),
1058 new ArrayRealVector(wData, false));
1059 }
1060
1061 }