1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
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
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48 public class SQPOptimizerS2 extends AbstractSQPOptimizer2 {
49
50 private enum QPMode {
51
52
53
54 QP_STARDARD,
55
56
57
58 QP_AUGMENTED
59 }
60
61
62 private RealMatrix L;
63
64
65
66
67 private final SQPLogger formatter = SQPLogger.defaultLogger();
68
69
70
71
72 private RealVector eqEval;
73
74
75
76
77 private RealVector ineqEval;
78
79
80
81
82 private RealVector bEval;
83
84
85
86
87 private RealVector J;
88
89
90
91
92 private RealMatrix H;
93
94
95
96
97 private RealMatrix JI;
98
99
100
101
102 private RealMatrix JE;
103
104
105
106
107 private RealMatrix JB;
108
109
110
111
112 private double functionEval;
113
114
115
116
117 private RealVector x;
118
119
120
121
122 private LinearInequalityConstraint BIQ;
123
124
125
126
127 private ArrayRealVector LB;
128
129
130
131
132 private ArrayRealVector UB;
133
134
135
136 public SQPOptimizerS2() {
137
138 }
139
140
141
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
151 if (this.getEqConstraint() != null) {
152 me = getEqConstraint().dimY();
153 }
154
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
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
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
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
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 }
268
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
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
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
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
342 alpha = lineSearch.search(penalty);
343 FUNEVALCOUNT+=lineSearch.getIteration();
344
345 if (m > 0) {
346
347
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
356
357 x.combineToSelf(1.0, alpha, dx);
358
359
360 final double functionEvalOld = functionEval;
361 functionEval = penalty.getObjEval();
362 eqEval = penalty.getEqEval();
363 ineqEval = penalty.getIqEval();
364 bEval = penalty.getBEval();
365
366
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
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
388
389
390
391
392
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
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
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
467
468
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
503
504
505
506
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
537
538
539
540
541 private double rhoUp(double rho) {
542 return rho * 10.0;
543 }
544
545
546
547
548
549
550
551
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
593
594
595
596
597
598
599
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
618 final RealVector g1 = new ArrayRealVector(n + add);
619 g1.setSubVector(0, J);
620
621
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
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
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
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
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
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
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
715
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
725 LinearEqualityConstraint eqc = null;
726 if (me > 0) {
727
728 eqc = new LinearEqualityConstraint(JE, eqEval.mapMultiply(-1.0));
729 }
730
731
732 LinearInequalityConstraint iqc = null;
733 if (mc > 0) {
734
735
736 final RealMatrix combinedAI = MatrixUtils.createRealMatrix(mc, n);
737 final RealVector combinedBI = new ArrayRealVector(mc);
738
739
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
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
767
768 final QuadraticFunction q = new QuadraticFunction(L, J, 0.0);
769
770
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
778 return new LagrangeSolution(sol.getX(),
779 (me + mc > 0) ? sol.getLambda() : new ArrayRealVector(0),
780 0.0);
781 }
782
783
784
785
786
787
788
789
790
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
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
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
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
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
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
968
969
970
971
972
973
974
975
976
977
978
979
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
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
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
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
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
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
1089 double fPlus = getObj().value(xPlus);
1090
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
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
1100 gradF.setEntry(i, (fPlus - fMinus) / (2.0 * h));
1101
1102 if (gradEq != null) {
1103
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
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;
1121
1122
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
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
1133 gradF.setEntry(i, (-3.0 * f0 + 4.0 * f1 - f2) / (2.0 * h));
1134
1135 if (gradEq != null) {
1136
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
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
1158
1159
1160 public void setDebugPrinter(final DebugPrinter printer) {
1161 formatter.setDebugPrinter(printer);
1162 }
1163
1164
1165
1166
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
1222
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
1254
1255
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 }