Sleipnir C++ API
Loading...
Searching...
No Matches
newton.hpp
1// Copyright (c) Sleipnir contributors
2
3#pragma once
4
5#include <algorithm>
6#include <chrono>
7#include <cmath> // IWYU pragma: keep
8#include <functional>
9#include <limits>
10#include <optional>
11#include <span>
12
13#include <Eigen/Core>
14#include <Eigen/SparseCore>
15
16#include "sleipnir/optimization/solver/control_flow.hpp"
17#include "sleipnir/optimization/solver/exit_status.hpp"
18#include "sleipnir/optimization/solver/iteration_info.hpp"
19#include "sleipnir/optimization/solver/newton_matrix_callbacks.hpp"
20#include "sleipnir/optimization/solver/options.hpp"
21#include "sleipnir/optimization/solver/util/all_finite.hpp"
22#include "sleipnir/optimization/solver/util/filter.hpp"
23#include "sleipnir/optimization/solver/util/kkt_error.hpp"
24#include "sleipnir/optimization/solver/util/kkt_system.hpp"
25#include "sleipnir/optimization/solver/util/time_trace.hpp"
26#include "sleipnir/util/assert.hpp"
27#include "sleipnir/util/print_diagnostics.hpp"
28#include "sleipnir/util/symbol_exports.hpp"
29#include "sleipnir/util/time_tracer.hpp"
30
31// See docs/algorithms.md#Works_cited for citation definitions.
32
33namespace slp {
34
53template <typename Scalar>
54ExitStatus newton(
55 const NewtonMatrixCallbacks<Scalar>& matrix_callbacks,
56 std::span<std::function<ControlFlow(const IterationInfo<Scalar>& info)>>
57 iteration_callbacks,
58 const Options<Scalar>& options, Eigen::VectorX<Scalar>& x) {
59 using DenseVector = Eigen::VectorX<Scalar>;
60 using SparseMatrix = Eigen::SparseMatrix<Scalar>;
61 using SparseVector = Eigen::SparseVector<Scalar>;
62
63 using std::isfinite;
64
65 const auto solve_start_time = std::chrono::steady_clock::now();
66
67 using enum SolveTimeTracerID;
68
69 int iterations = 0;
70
71 // Prints final solver diagnostics when the solver exits
72 SolveDiagnostics<newton_time_trace> diagnostics{options.diagnostics,
73 options.diagnostics};
74
75 // Set up traced matrix callbacks if diagnostics are enabled
76#ifndef SLEIPNIR_DISABLE_DIAGNOSTICS
77 std::optional<NewtonMatrixCallbacks<Scalar>> traced_matrices;
78 if (options.diagnostics) {
79 traced_matrices.emplace(matrix_callbacks.num_decision_variables,
80 traced(diagnostics[COST], matrix_callbacks.f),
81 traced(diagnostics[GRADIENT], matrix_callbacks.g),
82 traced(diagnostics[HESSIAN], matrix_callbacks.H),
83 matrix_callbacks.scaling);
84 }
85 const auto& matrices = traced_matrices ? *traced_matrices : matrix_callbacks;
86#else
87 const auto& matrices = matrix_callbacks;
88#endif
89
90 ScopedTimeTracer setup_tracer{diagnostics[SETUP]};
91
92 Scalar f = matrices.f(x);
93 SparseVector g = matrices.g(x);
94 SparseMatrix H = matrices.H(x);
95
96 // Ensure matrix callback dimensions are consistent
97 slp_assert(g.rows() == matrices.num_decision_variables);
98 slp_assert(H.rows() == matrices.num_decision_variables);
99 slp_assert(H.cols() == matrices.num_decision_variables);
100
101 DenseVector trial_x;
102
103 Scalar trial_f;
104
105 // Check whether initial guess has finite cost and derivatives
106 if (!isfinite(f) || !all_finite(g) || !all_finite(H)) {
107 return ExitStatus::NONFINITE_INITIAL_GUESS;
108 }
109
110 NewtonKKTSystem<Scalar> kkt_system{H};
111
112 Filter<Scalar> filter;
113
114 // Step size reduction factor
115 constexpr Scalar α_reduction_factor(0.5);
116
117 // The smallest KKT error of a step accepted by the KKT error reduction
118 // fallback. Each fallback step must improve on it, so finitely many fallback
119 // steps are taken before the solver converges.
120 Scalar fallback_kkt_error = std::numeric_limits<Scalar>::infinity();
121
122 // Error
123 Scalar E_0 = unscaled_kkt_error_inf_norm<Scalar>(matrices.scaling, g);
124
125 setup_tracer.stop();
126
127 // Prints initial iterate diagnostics now and closes the iterate diagnostics
128 // table when the solver exits
129 IterateDiagnosticsTable table{options.diagnostics, E_0, f,
130 Scalar(0), Scalar(0), Scalar(0)};
131
132 while (E_0 > options.tolerance) {
133 ScopedTimeTracer inner_iter_tracer{diagnostics[ITERATION]};
134
135 // Check for diverging iterates
136 if (x.template lpNorm<Eigen::Infinity>() > Scalar(1e10) || !x.allFinite()) {
137 return ExitStatus::DIVERGING_ITERATES;
138 }
139
140 PhaseTimeTracer phase_tracer{diagnostics[CALLBACKS]};
141
142 // Call iteration callbacks
143 for (const auto& callback : iteration_callbacks) {
144 if (callback({iterations, x, {}, {}, {}, g, H, {}, {}}) ==
145 ControlFlow::BREAK) {
146 return ExitStatus::CALLBACK_REQUESTED_STOP;
147 }
148 }
149
150 phase_tracer.next(diagnostics[KKT_MATRIX_FACTOR]);
151
152 if (!kkt_system.factorize(H)) [[unlikely]] {
153 return ExitStatus::FACTORIZATION_FAILED;
154 }
155
156 phase_tracer.next(diagnostics[KKT_SYSTEM_SOLVE]);
157
158 const auto step = kkt_system.solve(g);
159
160 phase_tracer.next(diagnostics[LINE_SEARCH]);
161
162 constexpr Scalar α_max(1);
163 Scalar α = α_max;
164
165 const FilterEntry<Scalar> current_entry{f};
166
167 const Scalar D_ϕ = g.transpose() * step.p_x;
168
169 const Scalar α_min = filter.min_step_size(current_entry, D_ϕ);
170
171 // α_min is zero when the search direction is a descent direction, so also
172 // end the line search when the step becomes negligible relative to the
173 // iterate. This bounds the number of step size reductions.
174 const Scalar α_tiny = step.tiny_step_size(x);
175
176 // Loop until a step is accepted
177 while (1) {
178 trial_x = x + α * step.p_x;
179
180 trial_f = matrices.f(trial_x);
181
182 // If f(xₖ + αpₖˣ) isn't finite, reduce step size immediately
183 if (!isfinite(trial_f)) {
184 // Reduce step size
185 α *= α_reduction_factor;
186
187 if (α < α_min || α < α_tiny) {
188 return ExitStatus::LINE_SEARCH_FAILED;
189 }
190 continue;
191 }
192
193 // Check whether filter accepts trial iterate
194 if (filter.try_add(current_entry, FilterEntry{trial_f}, D_ϕ, α)) {
195 // Accept step
196 break;
197 }
198
199 // Reduce step size
200 α *= α_reduction_factor;
201
202 // If step size hit a minimum or the step became negligible, check if the
203 // KKT error was reduced. If it wasn't, report line search failure.
204 if (α < α_min || α < α_tiny) {
205 Scalar current_kkt_error = kkt_error_one_norm<Scalar>(g);
206
207 trial_x = x + α_max * step.p_x;
208
209 trial_f = matrices.f(trial_x);
210
211 Scalar next_kkt_error = kkt_error_one_norm<Scalar>(matrices.g(trial_x));
212
213 // If the step using αᵐᵃˣ reduced the KKT error below the current
214 // iterate's and every previous fallback step's, accept it anyway
215 if (next_kkt_error <=
216 Scalar(0.999) * std::min(current_kkt_error, fallback_kkt_error)) {
217 // Accept step
218 fallback_kkt_error = next_kkt_error;
219 α = α_max;
220 break;
221 }
222
223 return ExitStatus::LINE_SEARCH_FAILED;
224 }
225 }
226
227 phase_tracer.stop();
228
229 // Update iterates and function values
230 x = trial_x;
231 f = trial_f;
232
233 // Update autodiff for Hessian
234 g = matrices.g(x);
235 H = matrices.H(x);
236
237 // Update the error
238 E_0 = unscaled_kkt_error_inf_norm<Scalar>(matrices.scaling, g);
239
240 inner_iter_tracer.stop();
241
242 if (options.diagnostics) {
243 print_iterate_diagnostics(iterations, IterationType::NORMAL,
244 inner_iter_tracer.current_duration(), E_0, f,
245 Scalar(0), Scalar(0), Scalar(0),
246 kkt_system.hessian_regularization(),
247 kkt_system.constraint_jacobian_regularization(),
248 step.primal_inf_norm(), Scalar(1), α, α_max,
249 α_reduction_factor, Scalar(1));
250 }
251
252 ++iterations;
253
254 // Check for max iterations
255 if (iterations >= options.max_iterations) {
256 return ExitStatus::MAX_ITERATIONS_EXCEEDED;
257 }
258
259 // Check for max wall clock time
260 if (std::chrono::steady_clock::now() - solve_start_time > options.timeout) {
261 return ExitStatus::TIMEOUT;
262 }
263 }
264
265 if (!isfinite(E_0)) {
266 return ExitStatus::DIVERGING_ITERATES;
267 } else {
268 return ExitStatus::SUCCESS;
269 }
270}
271
272extern template SLEIPNIR_DLLEXPORT ExitStatus
273newton(const NewtonMatrixCallbacks<double>& matrix_callbacks,
274 std::span<std::function<ControlFlow(const IterationInfo<double>& info)>>
275 iteration_callbacks,
276 const Options<double>& options, Eigen::VectorX<double>& x);
277
278} // namespace slp