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 java.util.ArrayList;
20  import java.util.List;
21  
22  import org.hipparchus.exception.LocalizedCoreFormats;
23  import org.hipparchus.exception.MathIllegalArgumentException;
24  import org.hipparchus.linear.Array2DRowRealMatrix;
25  import org.hipparchus.linear.ArrayRealVector;
26  import org.hipparchus.linear.RealMatrix;
27  import org.hipparchus.linear.RealVector;
28  import org.hipparchus.optim.ConvergenceChecker;
29  import org.hipparchus.optim.LocalizedOptimFormats;
30  import org.hipparchus.optim.OptimizationData;
31  import org.hipparchus.optim.nonlinear.scalar.ObjectiveFunction;
32  import org.hipparchus.util.FastMath;
33  import org.hipparchus.util.MathUtils;
34  
35  /**
36   * Alternating Direction Method of Multipliers Quadratic Programming Optimizer.
37   * \[
38   *  min \frac{1}{2} X^T Q X + G X a\\
39   *  A  X    = B_1\\
40   *  B  X    \ge B_2\\
41   *  l_b \le C X \le u_b
42   * \]
43   * Algorithm based on paper:"An Operator Splitting Solver for Quadratic Programs(Bartolomeo Stellato, Goran Banjac, Paul Goulart, Alberto Bemporad, Stephen Boyd,February 13 2020)"
44   * @since 3.1
45   */
46  
47  public class ADMMQPOptimizer extends QPOptimizer {
48  
49      /** Algorithm settings. */
50      private ADMMQPOption settings;
51  
52      /** Equality constraint (may be null). */
53      private LinearEqualityConstraint eqConstraint;
54  
55      /** Inequality constraint (may be null). */
56      private LinearInequalityConstraint iqConstraint;
57  
58      /** Boundary constraint (may be null). */
59      private LinearBoundedConstraint bqConstraint;
60  
61      /** Objective function. */
62      private QuadraticFunction function;
63  
64      /** Problem solver. */
65      private final ADMMQPKKT solver;
66  
67      /** Problem convergence checker. */
68      private ADMMQPConvergenceChecker checker;
69  
70      /** Convergence indicator. */
71      private boolean converged;
72  
73      /** Current step size. */
74      private double rho;
75  
76      /** Simple constructor.
77       * <p>
78       * This constructor sets all {@link ADMMQPOption options} to their default values
79       * </p>
80       */
81      public ADMMQPOptimizer() {
82          settings  = new ADMMQPOption();
83          solver    = new ADMMQPKKT();
84          converged = false;
85          rho       = 0.1;
86      }
87  
88      /** {@inheritDoc} */
89      @Override
90      public ConvergenceChecker<LagrangeSolution> getConvergenceChecker() {
91          return checker;
92      }
93  
94      /** {@inheritDoc} */
95      @Override
96      public LagrangeSolution optimize(OptimizationData... optData) {
97          return super.optimize(optData);
98      }
99  
100     /** {@inheritDoc} */
101     @Override
102     protected void parseOptimizationData(OptimizationData... optData) {
103         super.parseOptimizationData(optData);
104         for (OptimizationData data: optData) {
105 
106              if (data instanceof ObjectiveFunction) {
107                 function = (QuadraticFunction) ((ObjectiveFunction) data).getObjectiveFunction();
108                 continue;
109             }
110 
111             if (data instanceof LinearEqualityConstraint) {
112                 eqConstraint = (LinearEqualityConstraint) data;
113                 continue;
114             }
115             if (data instanceof LinearInequalityConstraint) {
116                 iqConstraint = (LinearInequalityConstraint) data;
117                 continue;
118             }
119 
120             if (data instanceof LinearBoundedConstraint) {
121                 bqConstraint = (LinearBoundedConstraint) data;
122                 continue;
123             }
124 
125             if (data instanceof ADMMQPOption) {
126                 settings = (ADMMQPOption) data;
127             }
128 
129             if (data instanceof MatrixDecompositionTolerance) {
130                 final MatrixDecompositionTolerance tolerance = (MatrixDecompositionTolerance) data;
131                 solver.updateDecompositionEpsilon(tolerance.getEpsMatrixDecomposition());
132             }
133 
134         }
135         // if we got here, convexObjective exists
136         int n = function.dim();
137         if (eqConstraint != null) {
138             int nDual = eqConstraint.dimY();
139             if (nDual >= n) {
140                 throw new MathIllegalArgumentException(LocalizedOptimFormats.CONSTRAINTS_RANK, nDual, n);
141             }
142             int nTest = eqConstraint.getA().getColumnDimension();
143             if (nDual == 0) {
144                 throw new MathIllegalArgumentException(LocalizedCoreFormats.ZERO_NOT_ALLOWED);
145             }
146             MathUtils.checkDimension(nTest, n);
147         }
148 
149     }
150 
151     /** {@inheritDoc} */
152     @Override
153     public LagrangeSolution doOptimize() {
154         final int n = function.dim();
155         int me = 0;
156         int mi = 0;
157         int mb = 0;
158         int rhoUpdateCount = 0;
159 
160         //PHASE 1 First Solution
161 
162 
163         //QUADRATIC TERM
164         RealMatrix H = function.getP();
165         //GRADIENT
166         RealVector q = function.getQ();
167 
168 
169         //EQUALITY CONSTRAINT
170         if (eqConstraint != null) {
171             me = eqConstraint.dimY();
172         }
173         //INEQUALITY CONSTRAINT
174         if (iqConstraint != null) {
175             mi = iqConstraint.dimY();
176         }
177         //BOUNDED CONSTRAINT
178         if (bqConstraint != null) {
179             mb = bqConstraint.dimY();
180         }
181 
182         RealVector lb = new ArrayRealVector(me + mi + mb);
183         RealVector ub = new ArrayRealVector(me + mi + mb);
184 
185         //COMPOSE A MATRIX AND LOWER AND UPPER BOUND
186         RealMatrix A = new Array2DRowRealMatrix(me + mi + mb, n);
187         if (eqConstraint != null) {
188             A.setSubMatrix(eqConstraint.jacobian(null).getData(), 0, 0);
189             lb.setSubVector(0,eqConstraint.getLowerBound());
190             ub.setSubVector(0,eqConstraint.getUpperBound());
191         }
192         if (iqConstraint != null) {
193             A.setSubMatrix(iqConstraint.jacobian(null).getData(), me, 0);
194             ub.setSubVector(me,iqConstraint.getUpperBound());
195             lb.setSubVector(me,iqConstraint.getLowerBound());
196         }
197 
198         if (mb > 0) {
199             A.setSubMatrix(bqConstraint.jacobian(null).getData(), me + mi, 0);
200             ub.setSubVector(me + mi,bqConstraint.getUpperBound());
201             lb.setSubVector(me + mi,bqConstraint.getLowerBound());
202         }
203 
204         checker = new ADMMQPConvergenceChecker(H, A, q, settings.getEps(), settings.getEps());
205 
206         //SETUP WORKING MATRIX
207         RealMatrix Hw = H.copy();
208         RealMatrix Aw = A.copy();
209         RealVector qw = q.copy();
210         RealVector ubw = ub.copy();
211         RealVector lbw = lb.copy();
212         RealVector x;
213         if (getStartPoint() != null) {
214             x = new ArrayRealVector(getStartPoint());
215         } else {
216             x = new ArrayRealVector(function.dim());
217         }
218 
219         ADMMQPModifiedRuizEquilibrium dec = new ADMMQPModifiedRuizEquilibrium(H, A,q);
220 
221         if (settings.isScaling()) {
222            //
223             dec.normalize(settings.getEps(), settings.getScaleMaxIteration());
224             Hw = dec.getScaledH();
225             Aw = dec.getScaledA();
226             qw = dec.getScaledQ();
227             lbw = dec.getScaledLUb(lb);
228             ubw = dec.getScaledLUb(ub);
229 
230             x = dec.scaleX(x.copy());
231 
232         }
233 
234         final ADMMQPConvergenceChecker checkerRho = new ADMMQPConvergenceChecker(Hw, Aw, qw, settings.getEps(), settings.getEps());
235         //SETUP VECTOR SOLUTION
236 
237         RealVector z = Aw.operate(x);
238         RealVector y = new ArrayRealVector(me + mi + mb);
239 
240         solver.initialize(Hw, Aw, qw, me, lbw, ubw, rho, settings.getSigma(), settings.getAlpha());
241         RealVector xstar = null;
242         RealVector ystar = null;
243         RealVector zstar;
244 
245         while (iterations.getCount() <= iterations.getMaximalCount()) {
246             ADMMQPSolution sol = solver.iterate(x, y, z);
247             x = sol.getX();
248             y = sol.getLambda();
249             z = sol.getZ();
250             //new ArrayRealVector(me + mi + mb);
251             if (rhoUpdateCount < settings.getMaxRhoIteration()) {
252                 double rp       = checkerRho.residualPrime(x, z);
253                 double rd       = checkerRho.residualDual(x, y);
254                 double maxP     = checkerRho.maxPrimal(x, z);
255                 double maxD     = checkerRho.maxDual(x, y);
256                 boolean updated = manageRho(me, rp, rd, maxP, maxD);
257 
258                 if (updated) {
259                     ++rhoUpdateCount;
260                 }
261             }
262 
263 
264             if (settings.isScaling()) {
265 
266                 xstar = dec.unscaleX(x);
267                 ystar = dec.unscaleY(y);
268                 zstar = dec.unscaleZ(z);
269 
270             } else {
271 
272                 xstar = x.copy();
273                 ystar = y.copy();
274                 zstar = z.copy();
275 
276             }
277 
278             double rp        = checker.residualPrime(xstar, zstar);
279             double rd        = checker.residualDual(xstar, ystar);
280             double maxPrimal = checker.maxPrimal(xstar, zstar);
281             double maxDual   = checker.maxDual(xstar, ystar);
282 
283             if (checker.converged(rp, rd, maxPrimal, maxDual)) {
284                 converged = true;
285                 break;
286             }
287             iterations.increment();
288 
289         }
290 
291         //SOLUTION POLISHING
292         if (settings.isPolishing()) {
293             ADMMQPSolution finalSol = polish(Hw, Aw, qw, lbw, ubw, x, y, z);
294             if (settings.isScaling()) {
295                 xstar = dec.unscaleX(finalSol.getX());
296                 ystar = dec.unscaleY(finalSol.getLambda());
297             } else {
298                 xstar = finalSol.getX();
299                 ystar = finalSol.getLambda();
300             }
301         }
302         for (int i = 0; i < me + mi; i++) {
303             ystar.setEntry(i, -ystar.getEntry(i));
304         }
305 
306         return new LagrangeSolution(xstar, ystar, function.value(xstar));
307 
308     }
309 
310     /** Check if convergence has been reached.
311      * @return true if convergence has been reached
312      */
313     public boolean isConverged() {
314         return converged;
315     }
316 
317     /** Polish solution.
318      * @param H quadratic term matrix
319      * @param A constraint coefficients matrix
320      * @param q linear term matrix
321      * @param lb lower bound
322      * @param ub upper bound
323      * @param x primal problem solution
324      * @param y dual problem solution
325      * @param z auxiliary variable
326      * @return polished solution
327      */
328     private ADMMQPSolution polish(RealMatrix H, RealMatrix A, RealVector q, RealVector lb, RealVector ub,
329                                   RealVector x, RealVector y, RealVector z) {
330 
331         List<double[]> Aentry    = new ArrayList<>();
332         List<Double>  lubEntry   = new ArrayList<>();
333         List<Double>  yEntry     = new ArrayList<>();
334 
335         // FIND ACTIVE ON LOWER BAND
336         for (int j = 0; j < A.getRowDimension(); j++) {
337             if (z.getEntry(j) - lb.getEntry(j) < -y.getEntry(j)) {  // lower-active
338 
339                 Aentry.add(A.getRow(j));
340                 lubEntry.add(lb.getEntry(j));
341                 yEntry.add(y.getEntry(j));
342 
343             }
344         }
345         //FIND ACTIVE ON UPPER BAND
346         for (int j = 0; j < A.getRowDimension(); j++) {
347             if (-z.getEntry(j) + ub.getEntry(j) < y.getEntry(j)) { // lower-active
348 
349                 Aentry.add(A.getRow(j));
350                 lubEntry.add(ub.getEntry(j));
351                 yEntry.add(y.getEntry(j));
352 
353             }
354 
355         }
356         RealMatrix Aactive;
357         RealVector lub;
358 
359         RealVector ystar;
360         RealVector xstar = x.copy();
361         //!Aentry.isEmpty()
362         if (!Aentry.isEmpty()) {
363 
364             Aactive = new Array2DRowRealMatrix(Aentry.toArray(new double[0][]));
365             lub = new ArrayRealVector(lubEntry.toArray(new Double[0]));
366             ystar = new ArrayRealVector(yEntry.toArray(new Double[0]));
367             solver.initialize(H, Aactive, q, 0, lub, lub,
368                               settings.getSigma(), settings.getSigma(), settings.getAlpha());
369 
370             for (int i = 0; i < settings.getPolishIteration(); i++) {
371                 RealVector kttx = (H.operate(xstar)).add(Aactive.transpose().operate(ystar));
372                 RealVector ktty = Aactive.operate(xstar);
373                 RealVector b1 = q.mapMultiply(-1.0).subtract(kttx);
374                 RealVector b2 = lub.mapMultiply(1.0).subtract(ktty);
375                 ADMMQPSolution dxz = solver.solve(b1,b2);
376                 xstar = xstar.add(dxz.getX());
377                 ystar = ystar.add(dxz.getV());
378             }
379 
380             return new ADMMQPSolution(xstar, null, y, A.operate(xstar));
381 
382         } else {
383             return new ADMMQPSolution(x, null, y, z);
384         }
385     }
386 
387     /** Manage step size.
388      * @param me number of equality constraints
389      * @param rp primal residual
390      * @param rd dual residual
391      * @param maxPrimal primal vectors max
392      * @param maxDual dual vectors max
393      * @return true if rho has been updated
394      */
395     private boolean manageRho(int me, double rp, double rd, double maxPrimal, double maxDual) {
396         boolean updated = false;
397         if (settings.updateRho()) {
398 
399             // estimate new step size
400             double rhonew = FastMath.min(FastMath.max(rho * FastMath.sqrt((rp * maxDual) / (rd * maxPrimal)),
401                                                       settings.getRhoMin()),
402                                          settings.getRhoMax());
403 
404             if ((rhonew > rho * 5.0) || (rhonew < rho / 5.0)) {
405 
406                 rho = rhonew;
407                 updated = true;
408 
409                 solver.updateSigmaRho(settings.getSigma(), me, rho);
410             }
411         }
412         return updated;
413     }
414 
415 }