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.EigenDecompositionSymmetric;
22  import org.hipparchus.linear.MatrixUtils;
23  import org.hipparchus.linear.RealMatrix;
24  import org.hipparchus.linear.RealVector;
25  import org.hipparchus.optim.nonlinear.scalar.ObjectiveFunction;
26  import org.hipparchus.util.FastMath;
27  
28  /**
29   * Sequential Quadratic Programming Optimizer.
30   * <p>
31   * min f(x)
32   * <p>
33   * q(x)=b1
34   * <p>
35   * h(x)&gt;=b2
36   * <p>
37   * Algorithm based on paper:"Some Theoretical properties of an augmented lagrangian merit function
38   * (Gill,Murray,Sauders,Wriht,April 1986)"
39   * @since 3.1
40   * @deprecated as of 4.1, will be removed in 5.0; use {@link SQPOptimizerS2} instead.
41   * Note that {@link SQPOptimizerS2} has no equivalent of this optimizer's use of the
42   * exact objective Hessian ({@link SQPOption#useFunHessian()}).
43   */
44  @Deprecated
45  public class SQPOptimizerGM extends AbstractSQPOptimizer {
46  
47      /** Jacobian constraint. */
48      private RealMatrix constraintJacob;
49  
50      /** Value of the equality constraint. */
51      private RealVector equalityEval;
52  
53      /** Value of the inequality constraint. */
54      private RealVector inequalityEval;
55  
56      /** Gradient of the objective function. */
57      private RealVector functionGradient;
58  
59      /** Hessian of the objective function. */
60      private RealMatrix hessian;
61  
62      /** Simple constructor.
63       */
64      public SQPOptimizerGM() {
65          // nothing to do
66      }
67  
68      /** {@inheritDoc} */
69      @Override
70      public LagrangeSolution doOptimize() {
71          int me = 0;
72          int mi = 0;
73  
74          //EQUALITY CONSTRAINT
75          if (getEqConstraint() != null) {
76              me = getEqConstraint().dimY();
77          }
78          //INEQUALITY CONSTRAINT
79          if (getIqConstraint() != null) {
80              mi = getIqConstraint().dimY();
81          }
82  
83          double alpha;
84          double rho;
85          RealVector x;
86          if (getStartPoint() != null) {
87              x = new ArrayRealVector(getStartPoint());
88          } else {
89              x = new ArrayRealVector(getObj().dim());
90          }
91  
92          RealVector y = new ArrayRealVector(me + mi, 0.0);
93           //INITIAL VALUES
94          double functionEval = getObj().value(x);
95          functionGradient = getObj().gradient(x);
96          double maxGrad = functionGradient.getLInfNorm();
97  
98          if (getEqConstraint() != null) {
99            equalityEval = getEqConstraint().value(x);
100         }
101         if (getIqConstraint() != null) {
102             inequalityEval = getIqConstraint().value(x);
103         }
104         constraintJacob = computeJacobianConstraint(x);
105 
106         if (getEqConstraint() != null) {
107             maxGrad = FastMath.max(maxGrad, equalityEval.getLInfNorm());
108         }
109         if (getIqConstraint() != null) {
110             maxGrad = FastMath.max(maxGrad, inequalityEval.getLInfNorm());
111         }
112 
113         if (!getSettings().useFunHessian()) {
114             hessian= MatrixUtils.createRealIdentityMatrix(x.getDimension()).scalarMultiply(maxGrad);
115         } else {
116             hessian = getObj().hessian(x);
117         }
118 
119 
120         rho = 0;
121 
122         for (int i = 0; i < getMaxIterations(); i++) {
123 
124             iterations.increment();
125 
126             alpha = 1.0;
127 
128             LagrangeSolution sol1;
129             //SOLVE QP
130             sol1 = solveQP(x);
131             RealVector p = sol1.getX();
132             RealVector e = sol1.getLambda().subtract(y);
133 
134             RealVector s = calculateSvector(y,rho);
135             RealVector se = null;
136             RealMatrix jacobi; // NOPMD - PMD detext a false positive here
137             RealVector q = null;
138             RealVector qe = null;
139 
140             //TEST CON SI SOLO PER INEQUALITY AND Q FOR ALL
141             if (getEqConstraint() != null) {
142                 se = new ArrayRealVector(me);
143                 jacobi = constraintJacob.getSubMatrix(0, me - 1, 0, x.getDimension() - 1); // NOPMD - PMD detect a false positive here
144                 qe = new ArrayRealVector(me);
145             }
146             if (getIqConstraint() != null) {
147                 jacobi = constraintJacob.getSubMatrix(me, me + mi - 1, 0, x.getDimension() - 1);
148                 q = jacobi.operate(p).add(inequalityEval.subtract(getIqConstraint().getLowerBound())).subtract(s);
149             }
150 
151 
152 
153             //CALCULATE PENALTY GRADIENT
154             //
155             double penaltyGradient = penaltyFunctionGrad(p, y, s, e, qe, q, rho);
156             ArrayRealVector g = new ArrayRealVector(me + mi);
157             if (me > 0) {
158                 g.setSubVector(0,equalityEval.subtract(getEqConstraint().getLowerBound()));
159             }
160             if (mi > 0) {
161                 g.setSubVector(me, inequalityEval.subtract(getIqConstraint().getLowerBound()).subtract(s));
162             }
163 
164             double rhoSegnato = 2.0 * e.getNorm() / g.getNorm();
165 
166            // rho = rhoSegnato;
167             //if (!(penaltyGradient<=-0.5 * p.dotProduct(hessian.operate(p))))
168            while (penaltyGradient > -0.5 * p.dotProduct(hessian.operate(p))) {
169 
170                  rho = FastMath.max(rhoSegnato,2.0 * rho);
171 
172                 penaltyGradient = penaltyFunctionGrad(p, y, s, e, qe, q, rho);
173             }
174             //LINE SEARCH
175             double alfaEval = getObj().value(x.add(p.mapMultiply(alpha)));
176 
177             double alphaPenalty;
178             RealVector sineq = null;
179             RealVector seq = null;
180             if (se != null) {
181                 seq = se.add(qe.mapMultiply(alpha));
182             }
183             if (s != null) {
184                 sineq = s.add(q.mapMultiply(alpha));
185             }
186 
187             double currentPenalty = penaltyFunction(functionEval, x, y, se, s, rho);
188             alphaPenalty = penaltyFunction(alfaEval,x.add(p.mapMultiply(alpha)),
189                                            y.add(e.mapMultiply(alpha)),
190                                            seq, sineq, rho);
191 
192 
193 
194             int search = 0;
195             while ((alphaPenalty -currentPenalty) >= getSettings().getMu() * alpha *  penaltyGradient &&
196                    search < getSettings().getMaxLineSearchIteration()) {
197 
198                 double alfaStar = -0.5 * alpha * alpha *  penaltyGradient/ (-alpha *  penaltyGradient + alphaPenalty - currentPenalty);
199 
200                 alpha =  FastMath.max(getSettings().getB() * alpha, FastMath.min(1.0,alfaStar));
201                 alfaEval = getObj().value(x.add(p.mapMultiply(alpha)));
202                 if (se != null) {
203                     seq = se.add(qe.mapMultiply(alpha));
204                 }
205                 if (s != null) {
206                     sineq = s.add(q.mapMultiply(alpha));
207                 }
208                 alphaPenalty = penaltyFunction(alfaEval,x.add(p.mapMultiply(alpha)),y.add(e.mapMultiply(alpha)),seq,sineq,rho);
209 
210                 search = search + 1;
211 
212             }
213 
214 
215             if (getSettings().getConvCriteria() == 0) {
216                 if (p.mapMultiply(alpha).dotProduct(hessian.operate(p.mapMultiply(alpha))) < getSettings().getEps() * getSettings().getEps()) {
217                     break;
218                 }
219             } else {
220                 if (alpha * p.getNorm() <FastMath.sqrt(getSettings().getEps()) * (1 + x.getNorm())) {
221                     break;
222                 }
223 
224             }
225 
226             //UPDATE ALL FUNCTION
227             RealVector oldGradient = functionGradient;
228             RealMatrix oldJacob = constraintJacob;
229             RealVector old1 = lagrangianGradX(oldGradient,oldJacob,x,y.add(e.mapMultiply(alpha)));
230             functionEval = alfaEval;
231             functionGradient = getObj().gradient(x.add(p.mapMultiply(alpha)));
232             constraintJacob = computeJacobianConstraint(x.add(p.mapMultiply(alpha)));
233             RealVector new1 = lagrangianGradX(functionGradient,constraintJacob,x.add(p.mapMultiply(alpha)),y.add(e.mapMultiply(alpha)));
234             hessian = BFGSFormula(hessian, p, alpha, new1, old1);
235 
236             if (getEqConstraint() != null) {
237                 equalityEval = getEqConstraint().value(x.add(p.mapMultiply(alpha)));
238             }
239             if (getIqConstraint() != null) {
240                 inequalityEval = getIqConstraint().value(x.add(p.mapMultiply(alpha)));
241             }
242 
243             x = x.add(p.mapMultiply(alpha));
244             y = y.add(e.mapMultiply(alpha));
245         }
246 
247         functionEval = getObj().value(x);
248         functionGradient = getObj().gradient(x);
249 
250         constraintJacob = computeJacobianConstraint(x);
251         return new LagrangeSolution(x, y, functionEval);
252     }
253 
254     private RealVector calculateSvector(RealVector y, double rho) {
255         int me = 0;
256         int mi;
257         RealVector si = null;
258         if (getEqConstraint() != null) {
259             me = getEqConstraint().dimY();
260         }
261         if (getIqConstraint() != null) {
262             mi = getIqConstraint().dimY();
263             si = new ArrayRealVector(mi);
264             RealVector yi = y.getSubVector(me, mi);
265             for (int i = 0; i < inequalityEval.getDimension(); i++) {
266                 if (rho == 0) {
267                     si.setEntry(i, FastMath.max(0, inequalityEval.getEntry(i)));
268                 } else {
269                     si.setEntry(i, FastMath.max(0, inequalityEval.getEntry(i) - yi.getEntry(i) / rho));
270                 }
271             }
272         }
273         return si;
274     }
275 
276     private double penaltyFunction(double currentF, RealVector x, RealVector y, RealVector se, RealVector s, double rho) {
277         // the set of constraints is the same as the previous one but they must be evaluated with the increment
278 
279         int me = 0;
280         int mi;
281         double partial = currentF;
282 
283         if (getEqConstraint() != null) {
284             me = getEqConstraint().dimY();
285 
286             RealVector ye = y.getSubVector(0, me);
287             RealVector g = getEqConstraint().value(x).subtract(getEqConstraint().getLowerBound());
288             partial += -ye.dotProduct(g.subtract(se)) + 0.5 * rho * (g.subtract(se)).dotProduct(g.subtract(se));
289         }
290 
291         if (getIqConstraint() != null) {
292             mi = getIqConstraint().dimY();
293 
294             RealVector yi = y.getSubVector(me, mi);
295 
296             RealVector g = getIqConstraint().value(x).subtract(getIqConstraint().getLowerBound());
297 
298 
299 
300 
301 
302             partial+= -yi.dotProduct(g.subtract(s)) +0.5 * rho*(g.subtract(s)).dotProduct(g.subtract(s));
303 
304         }
305 
306         return partial;
307     }
308 
309     private double penaltyFunctionGrad(RealVector p, RealVector y,RealVector s,RealVector e,RealVector qe, RealVector q,double rho) {
310 
311         int me = 0;
312         int mi;
313         double partial = functionGradient.dotProduct(p);
314         if (getEqConstraint() != null) {
315             me = getEqConstraint().dimY();
316 
317             RealVector ye = y.getSubVector(0, me);
318             RealVector ee = e.getSubVector(0, me);
319           //  RealVector qe = q.getSubVector(0, me);
320 
321 
322             RealVector ge = equalityEval.subtract(getEqConstraint().getLowerBound());
323             RealMatrix jacob = constraintJacob.getSubMatrix(0, me - 1, 0, p.getDimension() - 1);
324             double term2 = p.dotProduct(jacob.transpose().operate(ye));
325             double term3 = p.dotProduct(jacob.transpose().operate(ge))*rho;
326             double term4 = ge.dotProduct(ee);
327             double term5 = ye.dotProduct(qe);
328             double term6 = qe.dotProduct(ge)*rho;
329             partial +=-term2 + term3-term4 + term5-term6;
330         }
331 
332         if (getIqConstraint() != null) {
333             mi = getIqConstraint().dimY();
334 
335             RealVector yi = y.getSubVector(me, mi);
336             RealVector ei = e.getSubVector(me, mi);
337 
338             RealVector gi = inequalityEval.subtract(getIqConstraint().getLowerBound());
339             RealMatrix jacob = constraintJacob.getSubMatrix(me, me + mi - 1, 0, p.getDimension() - 1);
340             double term2 = p.dotProduct(jacob.transpose().operate(yi));
341             double term3 = p.dotProduct(jacob.transpose().operate(gi.subtract(s)))*rho;
342             double term4 = (gi.subtract(s)).dotProduct(ei);
343             double term5 = yi.dotProduct(q);
344             double term6 = q.dotProduct(gi.subtract(s))*rho;
345 
346             partial +=-term2 + term3-term4 + term5-term6;
347         }
348 
349         return partial;
350     }
351 
352     private LagrangeSolution solveQP(RealVector x) {
353 
354         RealMatrix H = hessian;
355         RealVector g = functionGradient;
356 
357         int me = 0;
358         int mi = 0;
359         if (getEqConstraint() != null) {
360             me = getEqConstraint().dimY();
361         }
362         if (getIqConstraint() != null) {
363 
364             mi = getIqConstraint().dimY();
365 
366         }
367 
368         RealMatrix H1 = new Array2DRowRealMatrix(H.getRowDimension() , H.getRowDimension() );
369         H1.setSubMatrix(H.getData(), 0, 0);
370         RealVector g1 = new ArrayRealVector(g.getDimension() );
371         g1.setSubVector(0, g);
372 
373         LinearEqualityConstraint eqc = null;
374         if (getEqConstraint() != null) {
375             RealMatrix eqJacob = constraintJacob.getSubMatrix(0,me-1,0,x.getDimension()-1);
376 
377             RealMatrix Ae = new Array2DRowRealMatrix(me, x.getDimension() );
378             RealVector be = new ArrayRealVector(me);
379             Ae.setSubMatrix(eqJacob.getData(), 0, 0);
380 
381 
382 
383             be.setSubVector(0, getEqConstraint().getLowerBound().subtract(equalityEval));
384             eqc = new LinearEqualityConstraint(Ae, be);
385 
386         }
387         LinearInequalityConstraint iqc = null;
388 
389         if (getIqConstraint() != null) {
390 
391             RealMatrix iqJacob = constraintJacob.getSubMatrix(me,me + mi-1,0,x.getDimension()-1);
392 
393             RealMatrix Ai = new Array2DRowRealMatrix(mi, x.getDimension());
394             RealVector bi = new ArrayRealVector(mi);
395             Ai.setSubMatrix(iqJacob.getData(), 0, 0);
396 
397             bi.setSubVector(0, getIqConstraint().getLowerBound().subtract(inequalityEval));
398 
399             iqc = new LinearInequalityConstraint(Ai, bi);
400 
401         }
402 
403         QuadraticFunction q = new QuadraticFunction(H1, g1, 0);
404         LagrangeSolution sol;
405 
406         ADMMQPOptimizer solver = new ADMMQPOptimizer();
407         sol = solver.optimize(new ObjectiveFunction(q), iqc, eqc);
408 
409         return new LagrangeSolution(sol.getX(), sol.getLambda(),0.0);
410 
411     }
412 
413     private RealMatrix computeJacobianConstraint(RealVector x) {
414         int me = 0;
415         int mi = 0;
416         RealMatrix je = null;
417         RealMatrix ji = null;
418         if (getEqConstraint() != null) {
419             me = getEqConstraint().dimY();
420             je = getEqConstraint().jacobian(x);
421         }
422 
423         if (getIqConstraint() != null) {
424             mi = getIqConstraint().dimY();
425             ji = getIqConstraint().jacobian(x);
426         }
427 
428         RealMatrix jacobian = new Array2DRowRealMatrix(me + mi, x.getDimension());
429         if (me > 0) {
430             jacobian.setSubMatrix(je.getData(), 0, 0);
431         }
432         if (mi > 0) {
433             jacobian.setSubMatrix(ji.getData(), me, 0);
434         }
435 
436         return jacobian;
437     }
438     /*
439      *DAMPED BFGS FORMULA
440      */
441 
442     private RealMatrix BFGSFormula(RealMatrix oldH, RealVector dx, double alfa, RealVector newGrad, RealVector oldGrad) {
443 
444         RealMatrix oldH1 = oldH;
445         RealVector y1 = newGrad.subtract(oldGrad);
446         RealVector s = dx.mapMultiply(alfa);
447 
448         double theta = 1.0;
449         if (s.dotProduct(y1) <= 0.2 * s.dotProduct(oldH.operate(s))) {
450             theta = 0.8 * s.dotProduct(oldH.operate(s)) / (s.dotProduct(oldH.operate(s)) - s.dotProduct(y1));
451         }
452 
453         RealVector y = y1.mapMultiply(theta).add(oldH.operate(s).mapMultiply(1.0 - theta));
454 
455         RealMatrix firstTerm = y.outerProduct(y).scalarMultiply(1.0 / s.dotProduct(y));
456         RealMatrix secondTerm = oldH1.multiply(s.outerProduct(s)).multiply(oldH);
457         double thirtTerm = s.dotProduct(oldH1.operate(s));
458         RealMatrix Hnew = oldH1.add(firstTerm).subtract(secondTerm.scalarMultiply(1.0 / thirtTerm));
459         //RESET HESSIAN IF NOT POSITIVE DEFINITE
460         EigenDecompositionSymmetric dsX = new EigenDecompositionSymmetric(Hnew);
461         double min = new ArrayRealVector(dsX.getEigenvalues()).getMinValue();
462         if (new ArrayRealVector(dsX.getEigenvalues()).getMinValue() < 0) {
463 
464             RealMatrix diag = dsX.getD().
465                               add(MatrixUtils.createRealIdentityMatrix(dx.getDimension()).
466                                   scalarMultiply(getSettings().getEps() - min));
467             Hnew = dsX.getV().multiply(diag.multiply(dsX.getVT()));
468 
469         }
470         return Hnew;
471 
472     }
473 
474 }