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.ArrayRealVector;
20  import org.hipparchus.linear.RealMatrix;
21  import org.hipparchus.linear.RealVector;
22  import org.hipparchus.util.FastMath;
23  import org.hipparchus.util.Precision;
24  
25  
26  /**
27   * Implementation of the Augmented Lagrangian Merit Function.
28   * <p>
29   * This class implements the penalty function used for the line search procedure in
30   * Sequential Quadratic Programming (SQP), as described by <b>Klaus Schittkowski (1982)</b>.
31   * </p>
32   * <p>
33   * The function, often denoted as \(\Phi(x, v, r)\), combines the objective function
34   * with equality and inequality constraints using an Augmented Lagrangian formulation.
35   * This approach ensures that the search direction \(d\) generated by the QP subproblem
36   * is a descent direction for the merit function, provided the penalty parameters \(r_j\)
37   * are sufficiently large.
38   * </p>
39   * * @see <a href="https://apps.dtic.mil/sti/tr/pdf/ADA115667.pdf">
40   * Schittkowski (1982): On the convergence of a sequential quadratic programming method</a>
41   */
42  public class MeritFunctionL2 {
43  
44      /** Initial value for penalty parameters (typically small, e.g., 1e-2). */
45      private static final double SIGMA_INIT = 1.0e-2;
46  
47      /** Maximum allowed value for penalty parameters to prevent numerical ill-conditioning. */
48      private static final double R_MAX = 1.0e9;
49  
50      /** Objective function \(f(x)\). */
51      private final TwiceDifferentiableFunction objective;
52  
53      /** Equality constraints \(g_j(x) = 0\). */
54      private final Constraint eqConstraint;
55  
56      /** Inequality constraints \(g_j(x) \ge 0\). */
57      private final Constraint iqConstraint;
58  
59      /** Linear bounds constraints treated as inequalities. */
60      private final LinearInequalityConstraint bounds;
61  
62      /** Current point in the primal space \(x\). */
63      private RealVector x;
64  
65      /** Current estimate of Lagrange multipliers \(y\). */
66      private RealVector y;
67  
68      /** Search direction \(d\) (solution of the QP subproblem). */
69      private RealVector       dx;
70  
71      /** Multipliers \(u\) obtained from the solution of the current QP subproblem. */
72      private RealVector u;
73  
74      /** * Penalty parameters vector \(r\).
75       * According to Schittkowski, \(r_j\) must satisfy specific descent conditions.
76       */
77      private final RealVector r;
78  
79      /** Penalty parameters from the previous iteration to maintain stability. */
80      private final RealVector rOld;
81  
82      /** Gradient of the objective function \(\nabla f(x)\). */
83      private RealVector J;
84  
85      /** Directional derivative of the merit function in the direction \(dx\). */
86      private double penaltyGradient;
87  
88      /** Evaluation of the objective function at the current trial point. */
89      private double objEval;
90  
91      /** Residuals of equality constraints \(h(x) = f(x) - L\). */
92      private RealVector eqEval;
93  
94      /** Residuals of inequality constraints \(g(x) = f(x) - L\). */
95      private RealVector iqEval;
96  
97      /** Residuals of box constraints \(b(x) = Ax - L\). */
98      private RealVector bEval;
99  
100     /** Total value of the Augmented Lagrangian penalty function. */
101     private double pEval;
102 
103     /** Jacobian matrix of equality constraints. */
104     private RealMatrix JE;
105 
106     /** Jacobian matrix of inequality constraints. */
107     private RealMatrix JI;
108 
109     /** Jacobian matrix of box constraints. */
110     private RealMatrix JB;
111 
112     /**
113      * Constructor for the Merit Function.
114      *
115      * @param objective Objective function to minimize
116      * @param eqConstraint Equality constraints
117      * @param iqConstraint Inequality constraints
118      * @param bounds Linear box constraints
119      * @param x Initial starting point
120      */
121     public MeritFunctionL2(final TwiceDifferentiableFunction objective,
122                            final Constraint eqConstraint,
123                            final Constraint iqConstraint,
124                            final LinearInequalityConstraint bounds,
125                            final RealVector x) {
126         this.objective = objective;
127         this.eqConstraint = eqConstraint;
128         this.iqConstraint = iqConstraint;
129         this.bounds=bounds;
130         this.x = new ArrayRealVector(x);
131         int me = 0;
132         int mi = 0;
133         int mb = 0;
134         if (this.eqConstraint != null) {
135             me = this.eqConstraint.dimY();
136         }
137         if (this.iqConstraint != null) {
138             mi = this.iqConstraint.dimY();
139         }
140 
141         if (this.bounds != null) {
142             mb = this.bounds.dimY();
143             JB=this.bounds.jacobian(null);
144         }
145 
146 
147         final int m = me + mi + mb;
148         this.dx = new ArrayRealVector(x.getDimension());
149         this.y = new ArrayRealVector(m);
150         this.u = new ArrayRealVector(m);
151         this.r = new ArrayRealVector(m, SIGMA_INIT);
152         this.rOld=new ArrayRealVector(m, SIGMA_INIT);
153         this.J = new ArrayRealVector(x.getDimension());
154         this.eqEval = new ArrayRealVector(me);
155         this.iqEval = new ArrayRealVector(mi);
156         this.bEval = new ArrayRealVector(mb);
157         //this evaluate objective function contraints function and penaly
158         this.value(0);
159     }
160 
161     /** * Updates internal states with the results from the QP subproblem.
162      * <p>
163      * This method must be called before performing a line search to ensure gradients
164      * and search directions are consistent with the current iterate.
165      * </p>
166      * @param newJ Gradient of objective at current x
167      * @param newJE Gradient of equality at current x
168      * @param newJI Gradient of inequality at current x
169      * @param newX Current iterate
170      * @param newY Lagrange multipliers from the previous iteration
171      * @param newDx Search direction solution from the QP subproblem
172      * @param newU Multipliers solution from the QP subproblem
173      */
174     public void update(final RealVector newJ, final RealMatrix newJE, final RealMatrix newJI,
175                        final RealVector newX, final RealVector newY,
176                        final RealVector newDx, final RealVector newU) {
177         this.J                = newJ;
178         this.JE               = newJE;
179         this.JI               = newJI;
180         this.x                = newX;
181         this.y                = newY;
182         this.dx               = newDx;
183         this.u                = newU;
184         this.penaltyGradient = gradient();
185     }
186 
187     /**
188      * Returns the directional derivative of the penalty function.
189      * @return \(\nabla \Phi(x)^T d\)
190      */
191     double getGradient() {
192         return this.penaltyGradient;
193     }
194 
195     /**
196      * Returns the current primal point.
197      * @return current x
198      */
199     RealVector getX() {
200         return this.x;
201     }
202 
203     /**
204      * Returns the value of the objective function at the current iterate.
205      * @return \(f(x)\)
206      */
207     double getObjEval() {
208         return this.objEval;
209     }
210 
211     /**
212      * Returns the residuals of the inequality constraints.
213      * @return \(g(x) - L\)
214      */
215     RealVector getIqEval() {
216         return this.iqEval;
217     }
218 
219      /**
220      * Returns the residuals of the equality constraints.
221      * @return \(h(x) - L\)
222      */
223     RealVector getEqEval() {
224         return this.eqEval;
225     }
226 
227     /**
228      * Returns the residuals of the box constraints.
229      * @return \(Ax - L\)
230      */
231     RealVector getBEval() {
232         return this.bEval;
233     }
234 
235     /**
236      * Returns the total value of the merit function (objective + penalty terms).
237      * @return \(\Phi(x, v, r)\)
238      */
239     double getPenaltyEval() {
240         return this.pEval;
241     }
242 
243     /**
244      * Computes the merit function value at the current point (\(\alpha = 0\)).
245      * Internal helper for initialization and gradient consistency.
246      * @return current penalty value
247      */
248     public double value0() {
249         RealVector xAlpha = x;
250         RealVector yAlpha = null;
251         if (y.getDimension() > 0) {
252             yAlpha = y;
253         }
254 
255 
256         double penalty =objEval;
257 
258         int me = 0;
259         if (eqConstraint != null) {
260             me = eqConstraint.dimY();
261             RealVector re = r.getSubVector(0, me);
262             RealVector ye = yAlpha.getSubVector(0, me);
263 
264             // eqEval already contains (f(x) - lowerBound)
265             RealVector g = this.eqEval;
266 
267             RealVector g2 = g.ebeMultiply(g);
268             penalty -= ye.dotProduct(g) - 0.5 * re.dotProduct(g2);
269         }
270 
271         int mi = 0;
272         if (iqConstraint != null) {
273             mi = iqConstraint.dimY();
274             RealVector ri = r.getSubVector(me, mi);
275             RealVector yi = yAlpha.getSubVector(me, mi);
276 
277             RealVector yk = yAlpha.getSubVector(me, mi);
278 
279 
280             // iqEval already contains (f(x) - lowerBound)
281             RealVector gk = this.iqEval;
282 
283             RealVector g = new ArrayRealVector(gk);
284             RealVector mask = new ArrayRealVector(g.getDimension(), 1.0);
285 
286             for (int i = 0; i < gk.getDimension(); i++) {
287                 if (gk.getEntry(i) > (yk.getEntry(i) / ri.getEntry(i))) {
288                     mask.setEntry(i, 0.0);
289                     penalty -= 0.5 * yi.getEntry(i) * yi.getEntry(i) / ri.getEntry(i);
290                 }
291             }
292 
293             RealVector g2 = g.ebeMultiply(g.ebeMultiply(mask));
294             penalty -= yi.dotProduct(g.ebeMultiply(mask)) - 0.5 * ri.dotProduct(g2);
295         }
296 
297         int mb;
298         if (bounds != null) {
299             mb = bounds.dimY();
300             RealVector ri = r.getSubVector(me+mi, mb);
301             RealVector yi = yAlpha.getSubVector(me+mi, mb);
302 
303             RealVector yk = yAlpha.getSubVector(me+mi, mb);
304 
305 
306             // bEval already contains (Ax - lowerBound)
307             RealVector gk = this.bEval;
308 
309             RealVector g = new ArrayRealVector(gk);
310             RealVector mask = new ArrayRealVector(g.getDimension(), 1.0);
311 
312             for (int i = 0; i < gk.getDimension(); i++) {
313                 if (gk.getEntry(i) > (yk.getEntry(i) / ri.getEntry(i))) {
314                     mask.setEntry(i, 0.0);
315                     penalty -= 0.5 * yi.getEntry(i) * yi.getEntry(i) / ri.getEntry(i);
316                 }
317             }
318 
319             RealVector g2 = g.ebeMultiply(g.ebeMultiply(mask));
320             penalty -= yi.dotProduct(g.ebeMultiply(mask)) - 0.5 * ri.dotProduct(g2);
321         }
322 
323         return penalty;
324     }
325 
326     /**
327      * Evaluate merit function for a given step alpha.
328      * <p>
329      * Optimized version to minimize overhead while maintaining strict numerical
330      * consistency with the original backup summation order to prevent floating-point drift.
331      * </p>
332      * @param alpha line search step length
333      * @return penalty value at x + alpha*dx
334      */
335 
336    public double value(double alpha) {
337         RealVector xAlpha = x.add(dx.mapMultiply(alpha));
338 
339         RealVector yAlpha = null;
340         if (y.getDimension() > 0) {
341             yAlpha = y.add(u.subtract(y).mapMultiply(alpha));
342         }
343 
344         objEval = this.objective.value(xAlpha);
345         double penalty =objEval;
346 
347         int me = 0;
348         if (eqConstraint != null) {
349             me = eqConstraint.dimY();
350             RealVector re = r.getSubVector(0, me);
351             RealVector ye = yAlpha.getSubVector(0, me);
352             // Save evaluation directly as residual (f(x) - lower)
353             eqEval = eqConstraint.value(xAlpha).subtract(eqConstraint.getLowerBound());
354             RealVector g = eqEval;
355 
356             RealVector g2 = g.ebeMultiply(g);
357             penalty -= ye.dotProduct(g) - 0.5 * re.dotProduct(g2);
358         }
359 
360         int mi = 0;
361         if (iqConstraint != null) {
362             mi = iqConstraint.dimY();
363             RealVector ri = r.getSubVector(me, mi);
364             RealVector yi = yAlpha.getSubVector(me, mi);
365 
366             RealVector yk = yAlpha.getSubVector(me, mi);
367 
368             // Save evaluation directly as residual (f(x) - lower)
369             iqEval = iqConstraint.value(xAlpha).subtract(iqConstraint.getLowerBound());
370             RealVector gk = iqEval;
371 
372             RealVector g = new ArrayRealVector(gk);
373             RealVector mask = new ArrayRealVector(g.getDimension(), 1.0);
374 
375             for (int i = 0; i < gk.getDimension(); i++) {
376                 // Logic according to Schittkowski for handling inequality penalty terms
377                 // If g_j > y_j / r_j, the constraint is considered sufficiently satisfied (inactive in penalty)
378                 if (gk.getEntry(i) > (yk.getEntry(i) / ri.getEntry(i))) {
379                     mask.setEntry(i, 0.0);
380                     penalty -= 0.5 * yi.getEntry(i) * yi.getEntry(i) / ri.getEntry(i);
381                 }
382             }
383 
384             RealVector g2 = g.ebeMultiply(g.ebeMultiply(mask));
385             penalty -= yi.dotProduct(g.ebeMultiply(mask)) - 0.5 * ri.dotProduct(g2);
386         }
387 
388         int mb;
389         if (bounds != null) {
390             mb = bounds.dimY();
391             RealVector ri = r.getSubVector(me + mi, mb);
392             RealVector yi = yAlpha.getSubVector(me + mi, mb);
393 
394             RealVector yk = yAlpha.getSubVector(me + mi, mb);
395 
396             // Save evaluation directly as residual (Ax - lower)
397             bEval = bounds.value(xAlpha).subtract(bounds.getLowerBound());
398             RealVector gk = bEval;
399 
400             RealVector g = new ArrayRealVector(gk);
401             RealVector mask = new ArrayRealVector(g.getDimension(), 1.0);
402 
403             for (int i = 0; i < gk.getDimension(); i++) {
404                 if (gk.getEntry(i) > (yk.getEntry(i) / ri.getEntry(i))) {
405                     mask.setEntry(i, 0.0);
406                     penalty -= 0.5 * yi.getEntry(i) * yi.getEntry(i) / ri.getEntry(i);
407                 }
408             }
409 
410             RealVector g2 = g.ebeMultiply(g.ebeMultiply(mask));
411             penalty -= yi.dotProduct(g.ebeMultiply(mask)) - 0.5 * ri.dotProduct(g2);
412         }
413         pEval = penalty;
414         return penalty;
415     }
416 
417     /**
418      * Computes the directional derivative of the Augmented Lagrangian.
419      * <p>
420      * This derivative is used to check the Armijo-like descent condition
421      * during the line search.
422      * </p>
423      * @return the total directional derivative
424      */
425     private double gradient() {
426         if (y.getDimension() > 0) {
427             return gradX().dotProduct(dx) + gradY().dotProduct(u.subtract(y));
428         } else {
429             return gradX().dotProduct(dx);
430         }
431     }
432 
433 
434     /**
435      * Computes the gradient of the merit function with respect to x.
436      * @return \(\nabla_x \Phi(x, v, r)\)
437      */
438      public RealVector gradX() {
439         RealVector partial = J;
440         int me = 0;
441         int mi = 0;
442         int mb = 0;
443 
444         if (eqConstraint != null) {
445             me = eqConstraint.dimY();
446             RealVector re = r.getSubVector(0, me);
447             RealVector ye = y.getSubVector(0, me);
448 
449             // eqEval is already residual
450             RealVector ge = this.eqEval;
451             RealMatrix jacob = JE;
452             RealVector term = jacob.preMultiply(ye.subtract(ge.ebeMultiply(re)));
453             partial = partial.subtract(term);
454         }
455 
456         if (iqConstraint != null) {
457             mi = iqConstraint.dimY();
458 
459             RealVector ri = r.getSubVector(me, mi);
460             RealVector yi = y.getSubVector(me, mi);
461             // iqEval is already residual
462             RealVector gi = this.iqEval;
463             RealMatrix jacob = JI;
464             RealVector mask = new ArrayRealVector(mi, 1.0);
465 
466             for (int i = 0; i < gi.getDimension(); i++) {
467                 if (gi.getEntry(i) > yi.getEntry(i) / ri.getEntry(i)) {
468                     mask.setEntry(i, 0.0);
469                 }
470             }
471 
472             RealVector term=jacob.preMultiply((yi.subtract(gi.ebeMultiply(ri))).ebeMultiply(mask));
473             partial=partial.subtract(term);
474         }
475 
476         if (bounds != null) {
477             mb = bounds.dimY();
478 
479             RealVector rb = r.getSubVector(me+mi, mb);
480 
481             RealVector yb = y.getSubVector(me+mi, mb);
482 
483             // bEval is already residual
484             RealVector gb = this.bEval;
485 
486             RealMatrix jacob = JB;
487             RealVector maskb = new ArrayRealVector(mb, 1.0);
488 
489             for (int i = 0; i < gb.getDimension(); i++) {
490                 if (gb.getEntry(i) > yb.getEntry(i) / rb.getEntry(i)) {
491                     maskb.setEntry(i, 0.0);
492                 }
493             }
494 
495             RealVector termb=jacob.preMultiply((yb.subtract(gb.ebeMultiply(rb))).ebeMultiply(maskb));
496             partial=partial.subtract(termb);
497         }
498 
499         return partial;
500     }
501 
502 
503     /**
504      * Computes the gradient of the merit function with respect to the multipliers y.
505      * @return \(\nabla_y \Phi(x, v, r)\)
506      */
507      public RealVector gradY() {
508 
509         int me = 0;
510         int mi = 0;
511         int mb = 0;
512         RealVector partial = new ArrayRealVector(y.getDimension());
513         if (eqConstraint != null) {
514             me = eqConstraint.dimY();
515             // eqEval is residual
516             RealVector g = this.eqEval;
517             partial.setSubVector(0, g.mapMultiply(-1.0));
518         }
519 
520         if (iqConstraint != null) {
521             mi = iqConstraint.dimY();
522 
523             RealVector ri = r.getSubVector(me, mi);
524             RealVector riOld = rOld.getSubVector(me, mi);
525             RealVector yi = y.getSubVector(me, mi);
526             // iqEval is residual
527             RealVector gi = this.iqEval;
528             RealVector viri = new ArrayRealVector(mi, 0.0);
529             for (int i = 0; i < gi.getDimension(); i++) {
530                 viri.setEntry(i,
531                               gi.getEntry(i) > yi.getEntry(i) / ri.getEntry(i) ?
532                               -yi.getEntry(i)/riOld.getEntry(i) :
533                               -gi.getEntry(i));
534             }
535 
536             partial.setSubVector(me, viri);
537         }
538         if (bounds != null) {
539             mb = bounds.dimY();
540 
541             RealVector rb = r.getSubVector(me+mi, mb);
542             RealVector rbOld = rOld.getSubVector(me+mi, mb);
543             RealVector yb = y.getSubVector(me+mi, mb);
544             // bEval is residual
545             RealVector gb = this.bEval;
546             RealVector viri = new ArrayRealVector(mb, 0.0);
547             for (int i = 0; i < gb.getDimension(); i++) {
548                 viri.setEntry(i,
549                               gb.getEntry(i) > yb.getEntry(i) / rb.getEntry(i) ?
550                               -yb.getEntry(i)/rbOld.getEntry(i) :
551                               -gb.getEntry(i));
552             }
553 
554             partial.setSubVector(me+mi, viri);
555         }
556 
557         return partial;
558     }
559 
560     /**
561      * Update the weight vector \(r_j\) (Penalty Parameters).
562      * <p>
563      * This is a critical step in Schittkowski's algorithm. The penalty parameters \(r_j\)
564      * are updated after solving the QP subproblem but before the line search.
565      * They are chosen such that the search direction \(dx\) is a descent direction for
566      * the merit function: \(\nabla \Phi(x, v, r)^T d_{QP} &lt; 0\).
567      * </p>
568      * @param H Hessian Matrix (or its BFGS approximation)
569      * @param newY last estimate of multipliers
570      * @param newDx primal direction solution from QP
571      * @param newU dual direction (multipliers) from QP
572      * @param sigmaValue value of the additional slack variable in augmented QP
573      * @param iterations current iteration count
574      */
575      public void updateRj(RealMatrix H,
576                      RealVector newY,
577                      RealVector newDx,
578                      RealVector newU,
579                      double sigmaValue,
580                      int iterations) {
581 
582     if (newY == null || newY.getDimension() == 0) {
583         return;
584     }
585     this.rOld.setSubVector(0, r.copy());
586     final int m = r.getDimension();
587     // d^T H d: curvature of the objective function approximation
588     final double dbd = newDx.dotProduct(H.operate(newDx));
589     final int iter=iterations+1;
590 
591 
592     double dbdsigma = R_MAX;
593     if (dbd * (1.0 - sigmaValue)  > Precision.SAFE_MIN) {
594         // Formula to ensure descent: r_j must be proportional to (u_j - y_j)^2 / d^T H d
595         dbdsigma = (2.0 * m) / (dbd * (1.0 - sigmaValue));
596     }
597 
598     for (int j = 0; j < m; j++) {
599         final double rj = r.getEntry(j);
600         final double diff = newU.getEntry(j) - newY.getEntry(j);
601         final double rNew =  Math.min(R_MAX, dbdsigma * diff * diff);
602 
603         // Increase r_j if necessary to maintain descent condition
604         final double rjSigmaj  = Math.min(rj, iter * Math.sqrt(rj));
605         r.setEntry(j, Math.max(rNew, rjSigmaj));
606     }
607 }
608 
609 
610 
611     /** * Resets the penalty parameters vector \(r\) to its initial values.
612      * Useful when the optimizer performs a restart or recovery from a bad step.
613      */
614     public void resetRj() {
615         if (y.getDimension() > 0) {
616             this.r.set(SIGMA_INIT);
617             this.rOld.set(SIGMA_INIT);
618         }
619      }
620 
621     /** * Returns the current search direction.
622      * @return search direction dx
623      */
624     RealVector getDx() {
625        return  this.dx;
626     }
627 
628     /**
629      * Increases the penalty parameters globally.
630      * Used in augmented QP mode when the standard descent conditions are not met.
631      */
632     public void rUp()
633     {
634         if (r != null) {
635             for(int i = 0; i < r.getDimension(); i++) {
636                 r.setEntry(i, FastMath.min(1.0e9, r.getEntry(i) * 10.0));
637             }
638         }
639     }
640 
641     /**
642      * Returns the penalty parameters vector.
643      * @return vector r
644      */
645     public RealVector getR()
646     {
647             return this.r;
648     }
649 
650     /**
651      * Returns the maximum allowed penalty value.
652      * @return rMax
653      */
654     public double getRmax()
655     {
656             return this.R_MAX;
657     }
658 }