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.MatrixUtils;
21  import org.hipparchus.linear.RealMatrix;
22  import org.hipparchus.linear.RealVector;
23  import org.hipparchus.util.FastMath;
24  import org.hipparchus.util.Precision;
25  
26  /**
27   * BFGS Hessian updater with dynamic damping and robustness improvements.
28   * <p>
29   * Manages Hessian updates for SQP solvers by:
30   * </p>
31   * <ul>
32   * <li>Checking curvature condition</li>
33   * <li>Applying dynamic damping if necessary</li>
34   * <li>Skipping update if curvature still fails after damping</li>
35   * <li>Soft regularization of diagonal entries on repeated failures</li>
36   * <li>Automatic Hessian reset after configurable failures</li>
37   * </ul>
38   *
39   * @since 4.1
40   */
41  public class BFGSUpdater {
42  
43      /**
44       * Damping factor.
45       */
46      private static final double GAMMA = 0.2;
47  
48      /**
49       * trigger skip update for diagonal of Hessian.
50       */
51      private static final double SQRT_EPS = FastMath.sqrt(Precision.EPSILON);
52  
53      /** Reducing factor. */
54      private static final double TH = 1.0e-3;
55  
56      /**
57       * AutoScaling Flag.
58       */
59      private final boolean scale;
60  
61      /**
62       * EPS.
63       */
64      private final double eps;
65  
66      /**
67       * Tolerance for symmetric matrices decomposition.
68       *
69       * @since 4.1
70       */
71      private final double decompositionEpsilon;
72  
73      /**
74       * Stored initial Hessian for resets.
75       */
76      private final RealMatrix initialH;
77  
78      /**
79       * Current Cholesky factor L such that H = L·Lᵀ.
80       */
81      private RealMatrix L;
82  
83      /** Dimension. */
84      private final int dim;
85  
86      /** Hessian factor. */
87      private double    factor;
88  
89      /**
90       * Creates a new updater.
91       *
92       * @param initialHess initial positive‐definite Hessian matrix
93       * @param eps treshold to apply auto scale sty &lt; sqrt(eps)
94       * @param autoScale true apply auto hessian rescaling
95       * @param decompositionEpsilon tolerance for symmetric matrices
96       * decomposition
97       */
98      public BFGSUpdater(final RealMatrix initialHess, final double eps, final boolean autoScale, final double decompositionEpsilon) {
99          this.initialH = new Array2DRowRealMatrix(initialHess.getData());
100         this.eps      = eps;
101         this.scale    = autoScale;
102         this.dim      = initialHess.getColumnDimension();
103         this.factor   = 1.0;
104         this.decompositionEpsilon = decompositionEpsilon;
105         resetHessian();
106     }
107 
108     /**
109      * Returns the current Hessian matrix H = L·Lᵀ.
110      *
111      * @return current Hessian
112      */
113     public RealMatrix getHessian() {
114         return L.multiplyTransposed(L);
115     }
116 
117     /**
118      * Updates the Hessian approximation using the BFGS formula.
119      * <p>
120      * If curvature condition fails, applies damping or regularization.
121      * </p>
122      *
123      * @param s displacement vector (x<sub>k+1</sub> − x<sub>k</sub>)
124      * @param y1 gradient difference (∇f<sub>k+1</sub> − ∇f<sub>k</sub>)
125      * @return type of update:
126      * <ul>
127      *  <li>0: update is done</li>
128      *  <li>1: sHs not positive (zero step), Hessian reset to identity</li>
129      *  <li>2: sty not positive even after damping (non-finite input), skipped update</li>
130      *  <li>3: downdate would lose positive definiteness, Hessian reset to factor*I</li>
131      * </ul>
132      */
133     public int update(final RealVector s, final RealVector y1) {
134         final RealVector Hs = L.operate(L.preMultiply(s));
135         final double sHs = s.dotProduct(Hs);
136         double sty = s.dotProduct(y1);
137         if (sHs <= 0.0) {
138             resetHessian();
139             return 1;
140         }
141 
142         boolean damped = false;
143         RealVector y = y1;
144         if (sty < GAMMA * sHs) {
145             damped = true;
146             final double denominator = sHs - sty;
147             final double phi = (sHs - GAMMA * sHs) / denominator;
148             y = y1.mapMultiply(phi).add(Hs.mapMultiply(1.0 - phi));
149             sty = s.dotProduct(y);
150         }
151 
152         if (!(sty > 0.0)) {
153             return 2;
154         }
155 
156 
157         final double yy = y.dotProduct(y);
158         factor =1.0;
159         if (!damped && sty > Precision.SAFE_MIN) {
160              factor = yy / sty;
161         }
162         factor = FastMath.max(TH, FastMath.min(1.0 / TH, factor));
163 
164         if (!rankOneUpdate(s, y, Hs, sHs, sty)) {
165             return 3;
166         }
167 
168         return 0;
169     }
170 
171     /**
172      * Resets the Hessian approximation to its initial value.
173      */
174     public void resetHessian() {
175         L = MatrixUtils.createRealIdentityMatrix(dim);
176     }
177 
178     /**
179      * Resets the Hessian approximation with information on the curvature.
180      *
181      * @param gamma scale factor
182      */
183     public void resetHessian(double gamma) {
184         final double sqrtGAMMA = FastMath.sqrt(gamma);
185         L = MatrixUtils.createRealIdentityMatrix(dim).scalarMultiply(sqrtGAMMA);
186     }
187 
188     /**
189      * Resets the Hessian approximation with information on the curvature for external usage
190      *
191      */
192     public void resetHessianFactor() {
193         final double sqrtGAMMA = FastMath.sqrt(factor);
194         L = MatrixUtils.createRealIdentityMatrix(dim).scalarMultiply(sqrtGAMMA);
195     }
196 
197     /**
198      * Performs a BFGS rank‐one update on L.
199      *
200      * @param s displacement vector
201      * @param y gradient difference vector
202      * @param Hs vector
203      * @param sHs value
204      * @param sty Sᵀ.y
205      * @return true if update succeeded, false otherwise
206      */
207     private boolean rankOneUpdate(final RealVector s, final RealVector y, final RealVector Hs,
208                                   final double sHs, final double sty) {
209 
210         final double rho = 1.0 / FastMath.sqrt(sty);
211         final double theta = 1.0 / FastMath.sqrt(sHs);
212 
213         cholupdateLower(y, rho, +1);
214 
215         if (!cholupdateLower(Hs, theta, -1)) {
216 
217             resetHessian(factor);
218 
219             return false;
220         }
221 
222         return true;
223     }
224 
225     /**
226      * Performs a rank-one Cholesky update/downdate on L.
227      * <p>
228      * Updates L such that A' = A + sigma * alpha² * u * uᵀ, without refactorization.
229      * Uses a numerically robust variant based on Givens/hyperbolic rotations.
230      * </p>
231      *
232      * @param u direction vector
233      * @param alpha scaling factor applied to {@code u}
234      * @param sigma +1 for update, -1 for downdate
235      * @return true if resulting matrix remains SPD, false otherwise
236      */
237     private boolean cholupdateLower(final RealVector u, final double alpha, final int sigma) {
238         final int n = u.getDimension();
239         final double[] work = u.toArray();
240         for (int i = 0; i < n; ++i) {
241             work[i] *= alpha;
242         }
243         // --- Single global guard for downdate ---
244     if (sigma < 0) {
245         final double[] z = new double[n];
246 
247         // Solve L z = work
248         for (int i = 0; i < n; ++i) {
249             double sum = work[i];
250             for (int j = 0; j < i; ++j) {
251                 sum -= L.getEntry(i, j) * z[j];
252             }
253             final double lii = L.getEntry(i, i);
254             z[i] = sum / lii;
255         }
256 
257         double znorm2 = 0.0;
258         for (int i = 0; i < n; ++i) {
259             znorm2 += z[i] * z[i];
260         }
261 
262         if (znorm2 >= 1.0 - Precision.EPSILON) {
263             return false;
264         }
265     }
266 
267         for (int k = 0; k < n; ++k) {
268             final double lkk = L.getEntry(k, k);
269             final double xk = work[k];
270 
271             double r;
272             if (sigma > 0) {
273                 r = FastMath.hypot(lkk, xk);
274             } else {
275                 double radicand = (lkk - xk) * (lkk + xk);
276                 r = radicand <= Precision.EPSILON ? SQRT_EPS : FastMath.sqrt(radicand);
277             }
278 
279 
280             final double c = r / lkk;
281             final double s = xk / lkk;
282             final double invC = 1.0 / c;
283 
284             L.setEntry(k, k, r);
285 
286             for (int i = k + 1; i < n; ++i) {
287                 final double lik = L.getEntry(i, k);
288                 final double xi = work[i];
289                 final double newLik = (lik + sigma * s * xi) * invC;
290                 final double newXi = c * xi - s * newLik;
291                 L.setEntry(i, k, newLik);
292                 work[i] = newXi;
293             }
294         }
295         return true;
296     }
297 
298 
299 
300     /**
301      * Scales the Hessian H = L*L^T by a positive factor gamma,
302      * by scaling the Cholesky factor L in-place.
303      *
304      * H_new = gamma * H
305      * L_new = sqrt(gamma) * L
306      *
307      * @param gamma scaling factor (must be > 0)
308      */
309     private void scaleHessian(final double gamma) {
310 
311         final double s = FastMath.sqrt(gamma);
312 
313         final int n = L.getRowDimension();
314         for (int i = 0; i < n; ++i) {
315             for (int j = 0; j <= i; ++j) {
316                 L.setEntry(i, j, s * L.getEntry(i, j));
317             }
318         }
319     }
320 
321     /**
322      * Returns the current lower-triangular Cholesky factor L.
323      *
324      * @return current lower-triangular Cholesky factor
325      */
326     public RealMatrix getL() {
327         return L;
328     }
329 
330 
331 }