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.exception.LocalizedCoreFormats;
20  import org.hipparchus.exception.MathIllegalArgumentException;
21  import org.hipparchus.linear.AbstractRealMatrix;
22  import org.hipparchus.linear.ArrayRealVector;
23  import org.hipparchus.linear.MatrixUtils;
24  import org.hipparchus.linear.RealMatrix;
25  import org.hipparchus.linear.RealVector;
26  
27  /**
28   * Read-only, zero-copy row-oriented view of all linear constraints of a QP.
29   *
30   * <p>The represented matrix has the form:</p>
31   *
32   * <pre>
33   *     A = [ Ae          ]
34   *         [ Ai          ]
35   *         [ Ab          ]
36   *         [ -Ab         ]
37   * </pre>
38   *
39   * <p>where each constraint gradient is stored as a row. The class keeps only
40   * references to the original equality, inequality and bounded-constraint
41   * matrices. In particular, the upper-bound block {@code -Ab} is generated on
42   * demand and is never stored.</p>
43   *
44   * <p>The global row ordering is:</p>
45   * <ol>
46   *   <li>equality constraints,</li>
47   *   <li>inequality constraints,</li>
48   *   <li>lower bounded constraints,</li>
49   *   <li>upper bounded constraints.</li>
50   * </ol>
51   *
52   * <p>The matrix is intentionally read-only. Calling {@link #copy()} creates a
53   * physical independent matrix, but normal solver operations such as
54   * {@link #getEntry(int, int)}, {@link #getRowVector(int)} and
55   * {@link #operate(RealVector)} do not materialize the global matrix.</p>
56   */
57  public final class QPConstraintMatrix extends AbstractRealMatrix {
58  
59      /** Number of primal variables, i.e. matrix columns. */
60      private final int variableCount;
61  
62      /** Equality matrix, one equality per row. */
63      private final RealMatrix equalityMatrix;
64  
65      /** Inequality matrix, one inequality per row. */
66      private final RealMatrix inequalityMatrix;
67  
68      /** Bounded-constraint matrix, one bounded expression per row. */
69      private final RealMatrix boundedMatrix;
70  
71      /** Number of equality rows. */
72      private final int equalityCount;
73  
74      /** Number of inequality rows. */
75      private final int inequalityCount;
76  
77      /** Number of bounded-expression rows. */
78      private final int boundedCount;
79  
80      /** First global row of the inequality block. */
81      private final int inequalityOffset;
82  
83      /** First global row of the lower-bound block. */
84      private final int lowerBoundOffset;
85  
86      /** First global row of the upper-bound block. */
87      private final int upperBoundOffset;
88  
89      /** Total number of represented constraints. */
90      private final int constraintCount;
91  
92      /**
93       * Build a row-oriented virtual QP constraint matrix.
94       *
95       * @param variableCount number of primal variables
96       * @param equalityMatrix equality matrix, or {@code null}
97       * @param inequalityMatrix inequality matrix, or {@code null}
98       * @param boundedMatrix bounded-expression matrix, or {@code null}
99       */
100     public QPConstraintMatrix(final int variableCount,
101                               final RealMatrix equalityMatrix,
102                               final RealMatrix inequalityMatrix,
103                               final RealMatrix boundedMatrix) {
104 
105         if (variableCount < 0) {
106             throw new MathIllegalArgumentException(LocalizedCoreFormats.NEGATIVE_VALUE, variableCount);
107         }
108 
109         this.variableCount = variableCount;
110         this.equalityMatrix = equalityMatrix;
111         this.inequalityMatrix = inequalityMatrix;
112         this.boundedMatrix = boundedMatrix;
113 
114         checkColumnDimension(equalityMatrix,   variableCount);
115         checkColumnDimension(inequalityMatrix, variableCount);
116         checkColumnDimension(boundedMatrix,    variableCount);
117 
118         this.equalityCount = equalityMatrix == null ? 0 : equalityMatrix.getRowDimension();
119         this.inequalityCount = inequalityMatrix == null ? 0 : inequalityMatrix.getRowDimension();
120         this.boundedCount = boundedMatrix == null ? 0 : boundedMatrix.getRowDimension();
121 
122         this.inequalityOffset = equalityCount;
123         this.lowerBoundOffset = equalityCount + inequalityCount;
124         this.upperBoundOffset = lowerBoundOffset + boundedCount;
125         this.constraintCount = upperBoundOffset + boundedCount;
126     }
127 
128     /** Validate the number of columns of a backing block.
129      * @param matrix constraint matrix
130      * @param expected expected number of columns
131      */
132     private static void checkColumnDimension(final RealMatrix matrix,
133                                              final int expected) {
134         if (matrix != null && matrix.getColumnDimension() != expected) {
135             throw new MathIllegalArgumentException(LocalizedCoreFormats.DIMENSIONS_MISMATCH,
136                                                    matrix.getColumnDimension(), expected);
137         }
138     }
139 
140     /** {@inheritDoc} */
141     @Override
142     public int getRowDimension() {
143         return constraintCount;
144     }
145 
146     /** {@inheritDoc} */
147     @Override
148     public int getColumnDimension() {
149         return variableCount;
150     }
151 
152     /**
153      * Get a coefficient without constructing the global matrix.
154      *
155      * @param row global constraint index
156      * @param column primal-variable index
157      * @return coefficient A[row, column]
158      */
159     @Override
160     public double getEntry(final int row, final int column) {
161         MatrixUtils.checkMatrixIndex(this, row, column);
162 
163         if (row < inequalityOffset) {
164             return equalityMatrix.getEntry(row, column);
165         }
166         if (row < lowerBoundOffset) {
167             return inequalityMatrix.getEntry(row - inequalityOffset, column);
168         }
169         if (row < upperBoundOffset) {
170             return boundedMatrix.getEntry(row - lowerBoundOffset, column);
171         }
172         return -boundedMatrix.getEntry(row - upperBoundOffset, column);
173     }
174 
175     /**
176      * Get a constraint gradient as a row vector.
177      *
178      * <p>The backing Hipparchus matrix already returns an independent vector.
179      * For an upper bound that same newly allocated vector is negated in place,
180      * avoiding an additional vector allocation.</p>
181      *
182      * @param row global constraint index
183      * @return constraint gradient
184      */
185     @Override
186     public RealVector getRowVector(final int row) {
187         MatrixUtils.checkRowIndex(this, row);
188 
189         if (row < inequalityOffset) {
190             return equalityMatrix.getRowVector(row);
191         }
192         if (row < lowerBoundOffset) {
193             return inequalityMatrix.getRowVector(row - inequalityOffset);
194         }
195         if (row < upperBoundOffset) {
196             return boundedMatrix.getRowVector(row - lowerBoundOffset);
197         }
198 
199         return boundedMatrix.getRowVector(row - upperBoundOffset)
200                             .mapMultiplyToSelf(-1.0);
201     }
202 
203     /**
204      * Get a constraint gradient as an array.
205      *
206      * @param row global constraint index
207      * @return independent coefficient array
208      */
209     @Override
210     public double[] getRow(final int row) {
211         MatrixUtils.checkRowIndex(this, row);
212 
213         if (row < inequalityOffset) {
214             return equalityMatrix.getRow(row);
215         }
216         if (row < lowerBoundOffset) {
217             return inequalityMatrix.getRow(row - inequalityOffset);
218         }
219         if (row < upperBoundOffset) {
220             return boundedMatrix.getRow(row - lowerBoundOffset);
221         }
222 
223         final double[] data = boundedMatrix.getRow(row - upperBoundOffset);
224         for (int i = 0; i < data.length; i++) {
225             data[i] = -data[i];
226         }
227         return data;
228     }
229 
230     /**
231      * Evaluate all linear constraint expressions A x.
232      *
233      * <p>Each physical backing block is multiplied only once. The product of
234      * the bounded matrix is reused for both the lower and upper blocks, with
235      * opposite signs.</p>
236      *
237      * @param x primal vector
238      * @return A x
239      */
240     @Override
241     public RealVector operate(final RealVector x) {
242         final double[] result = new double[constraintCount];
243 
244         if (equalityCount > 0) {
245             copy(equalityMatrix.operate(x), result, 0, 1.0);
246         }
247 
248         if (inequalityCount > 0) {
249             copy(inequalityMatrix.operate(x), result, inequalityOffset, 1.0);
250         }
251 
252         if (boundedCount > 0) {
253             final RealVector boundedValue = boundedMatrix.operate(x);
254             copy(boundedValue, result, lowerBoundOffset, 1.0);
255             copy(boundedValue, result, upperBoundOffset, -1.0);
256         }
257 
258         return new ArrayRealVector(result, false);
259     }
260 
261     /** Copy a vector into an array, optionally changing its sign.
262      * @param source      source vector
263      * @param destination destination array
264      * @param offset      offset in destination array
265      * @param scale       scaling factor applied to all components
266      */
267     private static void copy(final RealVector source,
268                              final double[] destination,
269                              final int offset,
270                              final double scale) {
271         for (int i = 0; i < source.getDimension(); i++) {
272             destination[offset + i] = scale * source.getEntry(i);
273         }
274     }
275 
276 
277     /**
278      * This view is read-only.
279      */
280     @Override
281     public void setEntry(final int row, final int column, final double value) {
282         throw new UnsupportedOperationException("QPConstraintMatrix is read-only");
283     }
284 
285     /**
286      * Create an independent physical matrix for results of generic operations.
287      */
288     @Override
289     public RealMatrix createMatrix(final int rowDimension, final int columnDimension) {
290         return MatrixUtils.createRealMatrix(rowDimension, columnDimension);
291     }
292 
293     /**
294      * Materialize an independent deep copy.
295      */
296     @Override
297     public RealMatrix copy() {
298         final RealMatrix result = MatrixUtils.createRealMatrix(constraintCount, variableCount);
299         for (int row = 0; row < constraintCount; row++) {
300             result.setRow(row, getRow(row));
301         }
302         return result;
303     }
304 }