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.MatrixUtils;
20 import org.hipparchus.linear.RealMatrix;
21 import org.hipparchus.linear.RealVector;
22 import org.hipparchus.linear.ArrayRealVector;
23 import org.hipparchus.util.FastMath;
24 import org.hipparchus.util.Precision;
25
26 /**
27 * Updates a QR factorization when adding or removing constraints in active-set methods.
28 *
29 * @see "J. W. Daniel, W. B. Gragg, L. Kaufman and G. W. Stewart,
30 * Reorthogonalization and Stable Algorithms for Updating the Gram-Schmidt QR Factorization"
31 */
32 public class QRUpdater {
33
34 /** The full working matrix J (representing the basis of the subspace). */
35 private final RealMatrix J;
36
37 /** The upper triangular factor R of the active constraints. */
38 private final RealMatrix R;
39
40 /** Number of currently active constraints. */
41 private int iq;
42
43 /** Dimension of the optimization problem. */
44 private final int n;
45
46 /** Workspace buffer for the constraint vector being added. */
47 private final double[] tempDBuffer;
48
49 /** Workspace for rotation cosines. */
50 private final double[] cList;
51
52 /** Workspace for rotation sines. */
53 private final double[] sList;
54
55 /**
56 * Constructs a new QRUpdater given the lower triangular matrix L.
57 * <p>
58 * J is initialized as L^T using matrix-level operations to preserve
59 * block-storage benefits if n is large.
60 * </p>
61 * @param L lower triangular matrix from Cholesky decomposition.
62 */
63 public QRUpdater(final RealMatrix L) {
64 this.n = L.getRowDimension();
65 this.iq = 0;
66
67 // Initialize J and R through MatrixUtils to exploit BlockRealMatrix for large n
68 this.J = L.transpose();
69 this.R = MatrixUtils.createRealMatrix(n, n);
70
71 // Pre-allocated workspace for Givens rotations and rollback
72 this.tempDBuffer = new double[n];
73 this.cList = new double[n];
74 this.sList = new double[n];
75 }
76
77 /**
78 * Adds a constraint vector and updates the QR factorization via a backward Givens cascade.
79 * @param d constraint vector to add.
80 * @return {@code true} if added successfully; {@code false} if degenerate.
81 */
82
83 public boolean addConstraint(final RealVector d) {
84
85 // Load the constraint vector into the reusable workspace.
86 for (int i = 0; i < n; i++) {
87 tempDBuffer[i] = d.getEntry(i);
88 }
89
90 /*
91 * Apply a backward cascade of orthogonal reflectors to eliminate
92 * all components beyond the current active-set position.
93 */
94 for (int j = n - 1; j >= iq + 1; j--) {
95
96 double cc = tempDBuffer[j - 1];
97 double ss = tempDBuffer[j];
98
99 /*
100 * The component to eliminate is already exactly zero.
101 * Store (0, 0) as an unambiguous marker indicating that no
102 * transformation was applied.
103 */
104 if (ss == 0.0) {
105 cList[j] = 0.0;
106 sList[j] = 0.0;
107 continue;
108 }
109
110 /*
111 * FastMath.hypot computes the Euclidean norm without the
112 * avoidable intermediate overflow/underflow of cc*cc + ss*ss.
113 *
114 * Give h the sign of cc. Consequently, after normalization,
115 * cc is non-negative and 1 + cc cannot suffer cancellation.
116 *
117 * The cc == 0 case needs no special treatment:
118 * it naturally produces cc = 0 and ss = +/-1.
119 */
120 double h = FastMath.hypot(cc, ss);
121
122 if (cc < 0.0) {
123 h = -h;
124 }
125
126 cc /= h;
127 ss /= h;
128
129 tempDBuffer[j - 1] = h;
130 tempDBuffer[j] = 0.0;
131
132 cList[j] = cc;
133 sList[j] = ss;
134
135 final double xny = ss / (1.0 + cc);
136
137 // Apply the same reflector to columns j - 1 and j of J.
138 for (int k = 0; k < n; k++) {
139 final double t1 = J.getEntry(k, j - 1);
140 final double t2 = J.getEntry(k, j);
141
142 final double newT1 = t1 * cc + t2 * ss;
143 final double newT2 = xny * (t1 + newT1) - t2;
144
145 J.setEntry(k, j - 1, newT1);
146 J.setEntry(k, j, newT2);
147 }
148 }
149
150 /*
151 * Preserve the existing degeneracy test.
152 * This test concerns acceptance of the new constraint, not whether
153 * an individual orthogonal transformation must be applied.
154 */
155 if (FastMath.abs(tempDBuffer[iq]) < Precision.EPSILON) {
156
157 /*
158 * Roll back the applied transformations in reverse order.
159 * The reflector is symmetric and orthogonal, hence self-inverse.
160 */
161 for (int j = iq + 1; j < n; j++) {
162
163 final double cc = cList[j];
164 final double ss = sList[j];
165
166 // No transformation was applied at this position.
167 if (cc == 0.0 && ss == 0.0) {
168 continue;
169 }
170
171 final double xny = ss / (1.0 + cc);
172
173 for (int k = 0; k < n; k++) {
174 final double t1 = J.getEntry(k, j - 1);
175 final double t2 = J.getEntry(k, j);
176
177 final double newT1 = t1 * cc + t2 * ss;
178 final double newT2 = xny * (t1 + newT1) - t2;
179
180 J.setEntry(k, j - 1, newT1);
181 J.setEntry(k, j, newT2);
182 }
183 }
184
185 return false;
186 }
187
188 // Append the new column to the active triangular factor R.
189 for (int i = 0; i <= iq; i++) {
190 R.setEntry(i, iq, tempDBuffer[i]);
191 }
192
193 iq++;
194 return true;
195 }
196
197 /**
198 * Deletes the active constraint at the specified index.
199 * @param index index of the constraint to remove.
200 */
201 //
202 public void deleteConstraint(final int index) {
203
204 if (index < 0 || index >= iq) {
205 return;
206 }
207
208 // Shift the columns following the deleted constraint to the left.
209 for (int j = index; j < iq - 1; j++) {
210 for (int i = 0; i < n; i++) {
211 R.setEntry(i, j, R.getEntry(i, j + 1));
212 }
213 }
214
215 // Clear the final column, which is no longer active.
216 for (int i = 0; i < n; i++) {
217 R.setEntry(i, iq - 1, 0.0);
218 }
219
220 iq--;
221
222 if (iq == 0) {
223 return;
224 }
225
226 /*
227 * Restore the upper-triangular form of R by eliminating each
228 * subdiagonal component created by the column shift.
229 */
230 for (int j = index; j < iq; j++) {
231
232 double cc = R.getEntry(j, j);
233 double ss = R.getEntry(j + 1, j);
234
235 /*
236 * The subdiagonal component is already exactly zero.
237 * No transformation is necessary.
238 */
239 if (ss == 0.0) {
240 continue;
241 }
242
243 /*
244 * Give h the sign of cc so that the normalized cc is
245 * non-negative. The cc == 0 case is handled naturally.
246 */
247 double h = FastMath.hypot(cc, ss);
248
249 if (cc < 0.0) {
250 h = -h;
251 }
252
253 cc /= h;
254 ss /= h;
255
256 R.setEntry(j, j, h);
257 R.setEntry(j + 1, j, 0.0);
258
259 final double xny = ss / (1.0 + cc);
260
261 // Apply the reflector to the remaining active part of R.
262 for (int k = j + 1; k < iq; k++) {
263 final double t1 = R.getEntry(j, k);
264 final double t2 = R.getEntry(j + 1, k);
265
266 final double newT1 = t1 * cc + t2 * ss;
267 final double newT2 = xny * (t1 + newT1) - t2;
268
269 R.setEntry(j, k, newT1);
270 R.setEntry(j + 1, k, newT2);
271 }
272
273 // Apply the same reflector to columns j and j + 1 of J.
274 for (int k = 0; k < n; k++) {
275 final double t1 = J.getEntry(k, j);
276 final double t2 = J.getEntry(k, j + 1);
277
278 final double newT1 = t1 * cc + t2 * ss;
279 final double newT2 = xny * (t1 + newT1) - t2;
280
281 J.setEntry(k, j, newT1);
282 J.setEntry(k, j + 1, newT2);
283 }
284 }
285 }
286
287 /**
288 * Computes z = J_inactive * d_inactive.
289 * @param d vector containing inactive components from index iq.
290 * @return resulting vector z of dimension n.
291 */
292 public RealVector computeZ(final RealVector d) {
293 final double[] zRaw = new double[n];
294 for (int col = iq; col < n; col++) {
295 final double val = d.getEntry(col);
296 if (val == 0.0) {
297 continue;
298 }
299 for (int row = 0; row < n; row++) {
300 zRaw[row] += J.getEntry(row, col) * val;
301 }
302 }
303 return new ArrayRealVector(zRaw, false);
304 }
305
306 /**
307 * Solves R x = rhs using backward substitution.
308 * @param d right-hand side vector.
309 * @return solution vector of dimension iq.
310 */
311 public RealVector solveR(final RealVector d) {
312 if (iq == 0) {
313 return new ArrayRealVector(0);
314 }
315
316 final double[] xResult = new double[iq];
317
318 for (int i = iq - 1; i >= 0; i--) {
319
320 double sum = 0.0;
321
322 for (int j = i + 1; j < iq; j++) {
323 sum += R.getEntry(i, j) * xResult[j];
324 }
325
326 final double rii = R.getEntry(i, i);
327
328 if (FastMath.abs(rii) < Precision.SAFE_MIN) {
329 return null;
330 }
331
332 xResult[i] = (d.getEntry(i) - sum) / rii;
333 }
334
335 return new ArrayRealVector(xResult, false);
336 }
337
338 /**
339 * Solves R^T * x = rhs using forward substitution.
340 * @param rhs right-hand side vector.
341 * @return solution vector of dimension iq.
342 */
343 public RealVector solveRT(final RealVector rhs) {
344 if (iq == 0) {
345 return new ArrayRealVector(0);
346 }
347 final double[] xResult = new double[iq];
348 for (int i = 0; i < iq; i++) {
349 double sum = 0.0;
350 for (int j = 0; j < i; j++) {
351 sum += R.getEntry(j, i) * xResult[j];
352 }
353 double rii = R.getEntry(i, i);
354 if (FastMath.abs(rii) < Precision.SAFE_MIN) {
355 return null;
356 }
357 xResult[i] = (rhs.getEntry(i) - sum) / rii;
358 }
359 return new ArrayRealVector(xResult, false);
360 }
361
362 /**
363 * Applies the active part of J (J1 * coeffs).
364 * @param coeffs multipliers for active constraints.
365 * @return resulting vector of dimension n.
366 */
367 public RealVector applyJActive(final RealVector coeffs) {
368 final double[] out = new double[n];
369 for (int col = 0; col < iq; col++) {
370 final double c = coeffs.getEntry(col);
371 if (c == 0.0) {
372 continue;
373 }
374 for (int row = 0; row < n; row++) {
375 out[row] += J.getEntry(row, col) * c;
376 }
377 }
378 return new ArrayRealVector(out, false);
379 }
380
381 /** Get the current active R factor.
382 * @return the current active R factor (submatrix if iq < n)
383 */
384 public RealMatrix getR() {
385 return (iq == n) ? R : (iq > 0 ? R.getSubMatrix(0, iq - 1, 0, iq - 1) : null);
386 }
387
388 /** Get the full working matrix J.
389 * @return the full working matrix J
390 */
391 public RealMatrix getJ() {
392 return J;
393 }
394
395 /** Get current number of active constraints.
396 * @return current number of active constraints.
397 */
398 public int getIq() {
399 return iq;
400 }
401
402 /** Computes d = J^T * a.
403 * @param a a vector
404 * @return d = J^T * a
405 */
406 public RealVector computeD(final RealVector a) {
407 return J.preMultiply(a);
408 }
409
410 }