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.util.Precision;
20  
21  /**
22   * Utility class for formatting SQP iteration logs with dynamic precision and aligned columns.
23   */
24  public class SQPLogger {
25  
26      /** LS column fixed to 2 digits + 1 space for safety. */
27      private static final int LS_WIDTH = 5;
28  
29      /** Field start. */
30      private static final String FIELD_START = " %";
31  
32      /** Field continuation. */
33      private static final String FIELD_CONTINUATION = "s |";
34  
35      /** Fields width. */
36      private int width;
37  
38      /** Format of header line. */
39      private String headerFormat;
40  
41      /** Format of row lines. */
42      private String rowFormat;
43  
44      /** Debug printer. */
45      private DebugPrinter printer;
46  
47      /**
48       * Constructs a LogFormatter with custom epsilon.
49       *
50       * @param epsilon convergence threshold
51       */
52      public SQPLogger(double epsilon) {
53          setEps(epsilon);
54      }
55  
56      /**
57       * Updates the formatter precision and formats based on a new epsilon value.
58       *
59       * @param epsilon convergence threshold
60       */
61      public void setEps(double epsilon) {
62          final int precision = (int) Math.ceil(-Math.log10(epsilon)) + 2;
63          this.width = precision + 7; // space for digits, sign, exponent, padding
64  
65          final String f = "%%-%ds";
66          String col = String.format(f, width);
67          String lsCol = String.format(f, LS_WIDTH);
68          this.headerFormat = String.format(
69              "[SQP] ITER %%4s | %s | %s | %s | %s | %s | %s | %s | %s | %s | %s | %s | %s |",
70              col, lsCol, col, col, col, col, col, col, col, col, col, lsCol
71          );
72  
73          final String percent = "%%";
74          // use scientific notation for all doubles
75          String fld  = String.format(percent + width + "." + precision + "e");
76          String intf = String.format(percent + LS_WIDTH + "d");
77          this.rowFormat = String.format(
78              "[SQP] ITER %%4d | %s | %s | %s | %s | %s | %s | %s | %s | %s | %s | %s | %s |",
79              fld, intf, fld, fld, fld, fld, fld, fld, fld, fld, fld, intf
80          );
81      }
82  
83      /** Set debug printer.
84       * @param debugPrinter debug printer
85       */
86      public void setDebugPrinter(DebugPrinter debugPrinter) {
87          this.printer = debugPrinter;
88      }
89  
90      /** Get header line.
91       * @return header line
92       */
93      public String header() {
94          return String.format(headerFormat,
95              "", "alpha", "LS", "dxNorm", "dx'Hdx", "complSlack", "KKT", "viol", "sigma", "penalty", "f(x)", "funDiff", "Hupd");
96      }
97  
98      /** Format one row.
99       * @param iter        iteration number
100      * @param alpha       step length
101      * @param lsCount     line search iteration
102      * @param dxNorm      || dX ||
103      * @param dxHdx       dX H dX
104      * @param complSlack  complementary slackness measure, i.e. Sum |yi * gi|
105      * @param kkt         Lagrangian norm
106      * @param viol        constraints violations
107      * @param sigma       solution of the additional variable in QP subproblem
108      * @param penalty     penalty
109      * @param fx          objective function evaluation
110      * @param funDiff     difference f(x_old) - f(x_new) (or other convention)
111      * @param hUpdate     Hessian update code (implementation-defined)
112      * @return formatted row
113      */
114     public String formatRow(final int iter, final double alpha, final int lsCount,
115                             final double dxNorm, final double dxHdx, final double complSlack,
116                             final double kkt, final double viol, final double sigma,
117                             final double penalty, final double fx, final double funDiff,
118                             final int hUpdate) {
119         return String.format(rowFormat,
120                              iter, alpha, lsCount, dxNorm, dxHdx, complSlack, kkt, viol, sigma, penalty, fx, funDiff, hUpdate);
121     }
122 
123     /** Log header.
124      */
125     public void logHeader() {
126         if (printer != null) {
127             printer.print(header());
128         }
129     }
130 
131     /**
132      * Log one row of convergence criteria flags (kept aligned with table layout).
133      * @param funEvalCount total functions evaluations;
134      * @param crit2 norm criterion
135      * @param crit1 gradient criterion?
136      * @param crit5 criterion?
137      * @param crit0 Lagrangian norm criterion
138      * @param crit3 constraints violations criterion
139      * @param crit4 criterion?
140      */
141     public void logRow(final int funEvalCount,final boolean crit2, final boolean crit1, final boolean crit5,
142                        final boolean crit0, final boolean crit3, final boolean crit4) {
143         if (printer == null) {
144             return;
145         }
146         StringBuilder sb = new StringBuilder();
147         sb.append(String.format("[SQP] ITER %4d |", -1)).
148            append(String.format(FIELD_START + width     + FIELD_CONTINUATION, "")).
149            append(String.format(FIELD_START + LS_WIDTH  + FIELD_CONTINUATION, funEvalCount)).
150            append(String.format(FIELD_START + width     + FIELD_CONTINUATION, crit2)).
151            append(String.format(FIELD_START + width     + FIELD_CONTINUATION, crit1)).
152            append(String.format(FIELD_START + width     + FIELD_CONTINUATION, crit5)).
153            append(String.format(FIELD_START + width     + FIELD_CONTINUATION, crit0)).
154            append(String.format(FIELD_START + width     + FIELD_CONTINUATION, crit3)).
155            append(String.format(FIELD_START + width     + FIELD_CONTINUATION, "")).
156            append(String.format(FIELD_START + width     + FIELD_CONTINUATION, "")).
157            append(String.format(FIELD_START + width     + FIELD_CONTINUATION, "")).
158            append(String.format(FIELD_START + width     + FIELD_CONTINUATION, crit4)).
159            append(String.format(FIELD_START + LS_WIDTH  + FIELD_CONTINUATION, ""));
160         printer.print(sb.toString());
161     }
162 
163     /** Log one row.
164      * @param iter        iteration number
165      * @param alpha       step length
166      * @param lsCount     line search iteration
167      * @param dxNorm      || dX ||
168      * @param dxHdx       dX H dX
169      * @param complSlack  complementary slackness measure, i.e. Sum |yi * gi|
170      * @param kkt         Lagrangian norm
171      * @param viol        constraints violations
172      * @param sigma       solution of the additional variable in QP subproblem
173      * @param penalty     penalty
174      * @param fx          objective function evaluation
175      * @param funDiff     difference f(x_old) - f(x_new) (or other convention)
176      * @param hUpdate     Hessian update code (implementation-defined)
177      */
178     public void logRow(int iter, double alpha, int lsCount,
179                        double dxNorm, double dxHdx, double complSlack, double kkt,
180                        double viol, double sigma, double penalty, double fx,
181                        double funDiff, int hUpdate) {
182         if (printer != null) {
183             printer.print(formatRow(iter, alpha, lsCount, dxNorm, dxHdx, complSlack, kkt, viol, sigma, penalty, fx, funDiff, hUpdate));
184         }
185     }
186 
187     /** Get default logger.
188      * @return default logger
189      */
190     public static SQPLogger defaultLogger() {
191         return new SQPLogger(Precision.EPSILON);
192     }
193 
194 }