View Javadoc
1   /*
2    * Licensed to the Apache Software Foundation (ASF) 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 ASF 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  
18  /*
19   * This is not the original file distributed by the Apache Software Foundation.
20   * It has been extended by the Hipparchus project.
21   */
22  
23  package org.hipparchus.optim.nonlinear.vector.constrained;
24  
25  import org.hipparchus.exception.LocalizedCoreFormats;
26  import org.hipparchus.exception.MathIllegalArgumentException;
27  import org.hipparchus.linear.Array2DRowRealMatrix;
28  import org.hipparchus.linear.ArrayRealVector;
29  import org.hipparchus.linear.DecompositionSolver;
30  import org.hipparchus.linear.MatrixUtils;
31  import org.hipparchus.linear.RealMatrix;
32  import org.hipparchus.linear.RealVector;
33  import org.hipparchus.util.FastMath;
34  
35  /**
36   * Calculates a Cholesky decomposition with adaptive diagonal regularization.
37   * <p>
38   * Given a symmetric matrix {@code A}, this class attempts to compute a lower
39   * triangular matrix {@code L} such that:
40   * </p>
41   * <pre>
42   * A + shift * I = L L^T
43   * </pre>
44   * <p>
45   * where {@code shift >= 0} is chosen automatically when needed to enforce
46   * strict positive definiteness.
47   * </p>
48   * <p>
49   * The decomposition is therefore performed on the regularized matrix, which can
50   * be retrieved using {@link #getRegularizedMatrix()}.
51   * </p>
52   *
53   * @see org.hipparchus.linear.CholeskyDecomposition
54   * @see org.hipparchus.linear.SemiDefinitePositiveCholeskyDecomposition
55   */
56  public class RegularizedCholeskyDecomposition {
57  
58      /**
59       * Default threshold above which off-diagonal elements are considered too
60       * different and the matrix is not symmetric.
61       */
62      public static final double DEFAULT_RELATIVE_SYMMETRY_THRESHOLD = 1.0e-15;
63  
64      /**
65       * Default threshold below which diagonal pivots are considered too small.
66       */
67      public static final double DEFAULT_ABSOLUTE_POSITIVITY_THRESHOLD = 1.0e-14;
68  
69      /**
70       * Default growth factor for the diagonal shift.
71       */
72      public static final double DEFAULT_DIAGONAL_GROWTH_FACTOR = 2.0;
73  
74      /**
75       * Default maximum number of regularization attempts.
76       */
77      public static final int DEFAULT_MAX_REGULARIZATION_STEPS = 50;
78  
79      /**
80       * Upper-triangular row-oriented storage for L^T.
81       */
82      private final double[][] lTData;
83  
84      /**
85       * Cached value of L.
86       */
87      private RealMatrix cachedL;
88  
89      /**
90       * Cached value of LT.
91       */
92      private RealMatrix cachedLT;
93  
94      /**
95       * Regularized matrix actually factorized.
96       */
97      private final RealMatrix regularizedMatrix;
98  
99      /**
100      * Final diagonal shift added to the input matrix.
101      */
102     private final double diagonalShift;
103 
104     /**
105      * Build the decomposition using default thresholds.
106      *
107      * @param matrix matrix to decompose
108      */
109     public RegularizedCholeskyDecomposition(final RealMatrix matrix) {
110         this(matrix,
111              DEFAULT_RELATIVE_SYMMETRY_THRESHOLD,
112              DEFAULT_ABSOLUTE_POSITIVITY_THRESHOLD,
113              DEFAULT_DIAGONAL_GROWTH_FACTOR,
114              DEFAULT_MAX_REGULARIZATION_STEPS);
115     }
116 
117     /**
118      * Build the decomposition using custom symmetry and positivity thresholds.
119      *
120      * @param matrix matrix to decompose
121      * @param relativeSymmetryThreshold symmetry threshold
122      * @param absolutePositivityThreshold positivity threshold
123      */
124     public RegularizedCholeskyDecomposition(final RealMatrix matrix,
125                                             final double relativeSymmetryThreshold,
126                                             final double absolutePositivityThreshold) {
127         this(matrix,
128              relativeSymmetryThreshold,
129              absolutePositivityThreshold,
130              DEFAULT_DIAGONAL_GROWTH_FACTOR,
131              DEFAULT_MAX_REGULARIZATION_STEPS);
132     }
133 
134     /**
135      * Build the decomposition using fully custom settings.
136      *
137      * @param matrix matrix to decompose
138      * @param relativeSymmetryThreshold symmetry threshold
139      * @param absolutePositivityThreshold positivity threshold
140      * @param diagonalGrowthFactor growth factor applied to the diagonal shift
141      * @param maxRegularizationSteps maximum number of regularization attempts
142      */
143     public RegularizedCholeskyDecomposition(final RealMatrix matrix,
144                                             final double relativeSymmetryThreshold,
145                                             final double absolutePositivityThreshold,
146                                             final double diagonalGrowthFactor,
147                                             final int maxRegularizationSteps) {
148         if (!matrix.isSquare()) {
149             throw new MathIllegalArgumentException(LocalizedCoreFormats.NON_SQUARE_MATRIX,
150                                                    matrix.getRowDimension(),
151                                                    matrix.getColumnDimension());
152         }
153 
154         final double[][] original = copyAndCheckSymmetry(matrix, relativeSymmetryThreshold);
155         final FactorizationResult result = factorizeWithRegularization(original,
156                                                                        absolutePositivityThreshold,
157                                                                        diagonalGrowthFactor,
158                                                                        maxRegularizationSteps);
159 
160         this.lTData = result.lTData;
161         this.regularizedMatrix = new Array2DRowRealMatrix(result.regularizedMatrix, false);
162         this.diagonalShift = result.diagonalShift;
163         this.cachedL = null;
164         this.cachedLT = null;
165     }
166 
167     /**
168      * Get the final diagonal shift added to the original matrix.
169      *
170      * @return diagonal shift
171      */
172     public double getDiagonalShift() {
173         return diagonalShift;
174     }
175 
176     /**
177      * Get the regularized matrix actually factorized.
178      *
179      * @return regularized matrix
180      */
181     public RealMatrix getRegularizedMatrix() {
182         return regularizedMatrix;
183     }
184 
185     /**
186      * Returns the matrix L of the decomposition.
187      * <p>
188      * L is a lower-triangular matrix.
189      * </p>
190      *
191      * @return the L matrix
192      */
193     public RealMatrix getL() {
194         if (cachedL == null) {
195             cachedL = getLT().transpose();
196         }
197         return cachedL;
198     }
199 
200     /**
201      * Returns the transpose of the matrix L of the decomposition.
202      * <p>
203      * L<sup>T</sup> is an upper-triangular matrix.
204      * </p>
205      *
206      * @return the transpose of the matrix L
207      */
208     public RealMatrix getLT() {
209         if (cachedLT == null) {
210             cachedLT = MatrixUtils.createRealMatrix(lTData);
211         }
212         return cachedLT;
213     }
214 
215     /**
216      * Return the determinant of the regularized matrix.
217      *
218      * @return determinant of the regularized matrix
219      */
220     public double getDeterminant() {
221         double determinant = 1.0;
222         for (int i = 0; i < lTData.length; ++i) {
223             final double d = lTData[i][i];
224             determinant *= d * d;
225         }
226         return determinant;
227     }
228 
229     /**
230      * Get a solver for finding the solution of the regularized system.
231      *
232      * @return a solver
233      */
234     public DecompositionSolver getSolver() {
235         return new Solver();
236     }
237 
238     /**
239      * Copy matrix data and check symmetry.
240      *
241      * @param matrix input matrix
242      * @param relativeSymmetryThreshold symmetry threshold
243      * @return symmetric copy of the matrix data
244      */
245     private static double[][] copyAndCheckSymmetry(final RealMatrix matrix,
246                                                    final double relativeSymmetryThreshold) {
247         final int order = matrix.getRowDimension();
248         final double[][] data = matrix.getData();
249 
250         for (int i = 0; i < order; ++i) {
251             final double[] rowI = data[i];
252             for (int j = i + 1; j < order; ++j) {
253                 final double[] rowJ = data[j];
254                 final double aij = rowI[j];
255                 final double aji = rowJ[i];
256                 final double maxDelta =
257                         relativeSymmetryThreshold * FastMath.max(FastMath.abs(aij), FastMath.abs(aji));
258 
259                 if (FastMath.abs(aij - aji) > maxDelta) {
260                     throw new MathIllegalArgumentException(LocalizedCoreFormats.NON_SYMMETRIC_MATRIX,
261                                                            i, j, relativeSymmetryThreshold);
262                 }
263 
264                 rowJ[i] = aij;
265             }
266         }
267 
268         return data;
269     }
270 
271     /**
272      * Perform factorization with adaptive diagonal regularization.
273      *
274      * @param original original symmetric matrix
275      * @param positivityThreshold positivity threshold
276      * @param diagonalGrowthFactor growth factor for the shift
277      * @param maxSteps maximum number of regularization attempts
278      * @return factorization result
279      */
280     private static FactorizationResult factorizeWithRegularization(final double[][] original,
281                                                                    final double positivityThreshold,
282                                                                    final double diagonalGrowthFactor,
283                                                                    final int maxSteps) {
284         final int n = original.length;
285         final double[] originalDiag = new double[n];
286 
287         for (int i = 0; i < n; ++i) {
288             originalDiag[i] = original[i][i];
289         }
290 
291         double shift = 0.0;
292 
293         // Initial estimate of the shift.
294         for (int i = 0; i < n; ++i) {
295             shift = FastMath.max(shift, positivityThreshold - originalDiag[i]);
296             for (int j = i + 1; j < n; ++j) {
297                 final double aij = original[i][j];
298                 final double ajj = originalDiag[j];
299                 double candidate = -FastMath.min(originalDiag[i], ajj);
300                 final double scale = FastMath.abs(originalDiag[i] - ajj) + FastMath.abs(aij);
301                 if (scale > 0.0) {
302                     candidate += (aij * aij) / scale;
303                 }
304                 shift = FastMath.max(shift, candidate);
305             }
306         }
307 
308         // If no shift appears necessary, try the unmodified matrix first.
309         if (shift <= 0.0) {
310             final AttemptResult plain = attemptFactorization(original, 0.0, positivityThreshold);
311             if (plain.success) {
312                 return new FactorizationResult(plain.lTData, plain.regularizedMatrix, 0.0);
313             }
314             shift = plain.additionalShift;
315         }
316 
317         double currentShift = shift;
318         for (int step = 0; step < maxSteps; ++step) {
319             currentShift *= diagonalGrowthFactor;
320 
321             final AttemptResult attempt = attemptFactorization(original, currentShift, positivityThreshold);
322             if (attempt.success) {
323                 return new FactorizationResult(attempt.lTData,
324                                                attempt.regularizedMatrix,
325                                                currentShift);
326             }
327 
328             currentShift += attempt.additionalShift;
329         }
330 
331         throw new MathIllegalArgumentException(LocalizedCoreFormats.NOT_POSITIVE_DEFINITE_MATRIX);
332     }
333 
334     /**
335      * Attempt factorization of {@code original + shift * I}.
336      *
337      * @param original original matrix
338      * @param shift diagonal shift
339      * @param positivityThreshold positivity threshold
340      * @return attempt result
341      */
342     private static AttemptResult attemptFactorization(final double[][] original,
343                                                       final double shift,
344                                                       final double positivityThreshold) {
345         final int n = original.length;
346         final double[][] r = new double[n][n];
347         final double[][] regularized = new double[n][n];
348 
349         for (int i = 0; i < n; ++i) {
350             System.arraycopy(original[i], 0, regularized[i], 0, n);
351             regularized[i][i] += shift;
352         }
353 
354         for (int j = 0; j < n; ++j) {
355             double pivotCandidate = 0.0;
356 
357             for (int i = 0; i <= j; ++i) {
358                 pivotCandidate = regularized[i][j];
359 
360                 for (int k = 0; k < i; ++k) {
361                     pivotCandidate -= r[k][i] * r[k][j];
362                 }
363 
364                 if (i < j) {
365                     if (FastMath.abs(r[i][i]) <= positivityThreshold) {
366                         final double additional = computeAdditionalShift(r, i, pivotCandidate, positivityThreshold);
367                         return AttemptResult.failure(additional);
368                     }
369                     r[i][j] = pivotCandidate / r[i][i];
370                 } else {
371                     if (pivotCandidate < positivityThreshold) {
372                         final double additional = computeAdditionalShift(r, j, pivotCandidate, positivityThreshold);
373                         return AttemptResult.failure(additional);
374                     }
375                     r[j][j] = FastMath.sqrt(pivotCandidate);
376                 }
377             }
378         }
379 
380         return AttemptResult.success(r, regularized);
381     }
382 
383     /**
384      * Compute the extra diagonal correction when a pivot fails.
385      *
386      * @param r current upper-triangular factor
387      * @param pivotIndex failed pivot index
388      * @param pivotCandidate failed pivot value
389      * @param positivityThreshold positivity threshold
390      * @return additional shift
391      */
392     private static double computeAdditionalShift(final double[][] r,
393                                                  final int pivotIndex,
394                                                  final double pivotCandidate,
395                                                  final double positivityThreshold) {
396         final double sumx = computeRecurrenceNorm(r, pivotIndex);
397         if (sumx <= 0.0 || Double.isNaN(sumx) || Double.isInfinite(sumx)) {
398             return positivityThreshold - pivotCandidate;
399         }
400         return positivityThreshold - pivotCandidate / sumx;
401     }
402 
403     /**
404      * Compute the norm-like recurrence used during pivot correction.
405      *
406      * @param r current upper-triangular factor
407      * @param pivotIndex pivot index
408      * @return recurrence norm
409      */
410     private static double computeRecurrenceNorm(final double[][] r, final int pivotIndex) {
411         if (pivotIndex == 0) {
412             return 1.0;
413         }
414 
415         final double[] work = new double[pivotIndex + 1];
416         work[pivotIndex] = 1.0;
417         double sumx = 1.0;
418 
419         int k = pivotIndex;
420         while (k > 0) {
421             double sum = 0.0;
422             for (int i = k; i <= pivotIndex; ++i) {
423                 sum -= r[k - 1][i] * work[i];
424             }
425 
426             final double diag = r[k - 1][k - 1];
427             if (FastMath.abs(diag) < FastMath.ulp(1.0)) {
428                 return Double.POSITIVE_INFINITY;
429             }
430 
431             work[k - 1] = sum / diag;
432             sumx += work[k - 1] * work[k - 1];
433             --k;
434         }
435 
436         return sumx;
437     }
438 
439     /**
440      * Internal factorization result.
441      */
442     private static final class FactorizationResult {
443 
444         /** LT matrix data. */
445         private final double[][] lTData;
446 
447         /** Regularized matrix data. */
448         private final double[][] regularizedMatrix;
449 
450         /** Final diagonal shift. */
451         private final double diagonalShift;
452 
453         FactorizationResult(final double[][] lTData,
454                             final double[][] regularizedMatrix,
455                             final double diagonalShift) {
456             this.lTData = lTData;
457             this.regularizedMatrix = regularizedMatrix;
458             this.diagonalShift = diagonalShift;
459         }
460     }
461 
462     /**
463      * Result of one factorization attempt.
464      */
465     private static final class AttemptResult {
466 
467         /** Whether the attempt succeeded. */
468         private final boolean success;
469 
470         /** LT matrix data if successful. */
471         private final double[][] lTData;
472 
473         /** Regularized matrix data if successful. */
474         private final double[][] regularizedMatrix;
475 
476         /** Additional shift suggested after failure. */
477         private final double additionalShift;
478 
479         private AttemptResult(final boolean success,
480                               final double[][] lTData,
481                               final double[][] regularizedMatrix,
482                               final double additionalShift) {
483             this.success = success;
484             this.lTData = lTData;
485             this.regularizedMatrix = regularizedMatrix;
486             this.additionalShift = additionalShift;
487         }
488 
489         static AttemptResult success(final double[][] lTData,
490                                      final double[][] regularizedMatrix) {
491             return new AttemptResult(true, lTData, regularizedMatrix, 0.0);
492         }
493 
494         static AttemptResult failure(final double additionalShift) {
495             return new AttemptResult(false, null, null, additionalShift);
496         }
497     }
498 
499     /**
500      * Specialized solver.
501      */
502     private class Solver implements DecompositionSolver {
503 
504         /** {@inheritDoc} */
505         @Override
506         public boolean isNonSingular() {
507             return true;
508         }
509 
510         /** {@inheritDoc} */
511         @Override
512         public RealVector solve(final RealVector b) {
513             final int m = lTData.length;
514             if (b.getDimension() != m) {
515                 throw new MathIllegalArgumentException(LocalizedCoreFormats.DIMENSIONS_MISMATCH,
516                                                        b.getDimension(), m);
517             }
518 
519             final double[] x = b.toArray();
520 
521             // Solve L Y = b
522             for (int j = 0; j < m; j++) {
523                 final double[] lJ = lTData[j];
524                 x[j] /= lJ[j];
525                 final double xJ = x[j];
526                 for (int i = j + 1; i < m; i++) {
527                     x[i] -= xJ * lJ[i];
528                 }
529             }
530 
531             // Solve L^T X = Y
532             for (int j = m - 1; j >= 0; j--) {
533                 x[j] /= lTData[j][j];
534                 final double xJ = x[j];
535                 for (int i = 0; i < j; i++) {
536                     x[i] -= xJ * lTData[i][j];
537                 }
538             }
539 
540             return new ArrayRealVector(x, false);
541         }
542 
543         /** {@inheritDoc} */
544         @Override
545         public RealMatrix solve(final RealMatrix b) {
546             final int m = lTData.length;
547             if (b.getRowDimension() != m) {
548                 throw new MathIllegalArgumentException(LocalizedCoreFormats.DIMENSIONS_MISMATCH,
549                                                        b.getRowDimension(), m);
550             }
551 
552             final int nColB = b.getColumnDimension();
553             final double[][] x = b.getData();
554 
555             // Solve L Y = b
556             for (int j = 0; j < m; j++) {
557                 final double[] lJ = lTData[j];
558                 final double lJJ = lJ[j];
559                 final double[] xJ = x[j];
560                 for (int k = 0; k < nColB; ++k) {
561                     xJ[k] /= lJJ;
562                 }
563                 for (int i = j + 1; i < m; i++) {
564                     final double[] xI = x[i];
565                     final double lJI = lJ[i];
566                     for (int k = 0; k < nColB; ++k) {
567                         xI[k] -= xJ[k] * lJI;
568                     }
569                 }
570             }
571 
572             // Solve L^T X = Y
573             for (int j = m - 1; j >= 0; j--) {
574                 final double lJJ = lTData[j][j];
575                 final double[] xJ = x[j];
576                 for (int k = 0; k < nColB; ++k) {
577                     xJ[k] /= lJJ;
578                 }
579                 for (int i = 0; i < j; i++) {
580                     final double[] xI = x[i];
581                     final double lIJ = lTData[i][j];
582                     for (int k = 0; k < nColB; ++k) {
583                         xI[k] -= xJ[k] * lIJ;
584                     }
585                 }
586             }
587 
588             return new Array2DRowRealMatrix(x, false);
589         }
590 
591         /**
592          * Get the inverse of the regularized matrix.
593          *
594          * @return inverse matrix
595          */
596         @Override
597         public RealMatrix getInverse() {
598             return solve(MatrixUtils.createRealIdentityMatrix(lTData.length));
599         }
600 
601         /** {@inheritDoc} */
602         @Override
603         public int getRowDimension() {
604             return lTData.length;
605         }
606 
607         /** {@inheritDoc} */
608         @Override
609         public int getColumnDimension() {
610             return lTData[0].length;
611         }
612 
613         /**
614      * Get the final diagonal shift added to the original matrix.
615      *
616      * @return diagonal shift
617      */
618     public double getDiagonalShift() {
619         return diagonalShift;
620     }
621     }
622 }