alpaqa pantr
Nonconvex constrained optimization
Loading...
Searching...
No Matches
panoc.tpp
Go to the documentation of this file.
1#pragma once
2
4
5#include <cassert>
6#include <cmath>
7#include <iomanip>
8#include <iostream>
9#include <stdexcept>
10
16#include <alpaqa/util/timed.hpp>
17
18namespace alpaqa {
19
20template <class DirectionProviderT>
22 return "PANOCSolver<" + std::string(direction.get_name()) + ">";
23}
24
25template <class DirectionProviderT>
27 /// [in] Problem description
28 const Problem &problem,
29 /// [in] Solve options
30 const SolveOptions &opts,
31 /// [inout] Decision variable @f$ x @f$
32 rvec x,
33 /// [inout] Lagrange multipliers @f$ y @f$
34 rvec y,
35 /// [in] Constraint weights @f$ \Sigma @f$
36 crvec Σ,
37 /// [out] Slack variable error @f$ g(x) - \Pi_D(g(x) + \Sigma^{-1} y) @f$
38 rvec err_z) -> Stats {
39
40 if (opts.check)
41 problem.check();
42
43 using std::chrono::nanoseconds;
44 auto os = opts.os ? opts.os : this->os;
45 auto start_time = std::chrono::steady_clock::now();
46 Stats s;
47
48 const auto n = problem.get_n();
49 const auto m = problem.get_m();
50
51 // Represents an iterate in the algorithm, keeping track of some
52 // intermediate values and function evaluations.
53 struct Iterate {
54 vec x; //< Decision variables
55 vec x̂; //< Decision variables after proximal gradient step
56 vec grad_ψ; //< Gradient of cost in x
57 vec p; //< Proximal gradient step in x
58 vec ŷx̂; //< Candidate Lagrange multipliers in x̂
59 real_t ψx = NaN<config_t>; //< Cost in x
60 real_t ψx̂ = NaN<config_t>; //< Cost in x̂
61 real_t γ = NaN<config_t>; //< Step size γ
62 real_t L = NaN<config_t>; //< Lipschitz estimate L
63 real_t pᵀp = NaN<config_t>; //< Norm squared of p
64 real_t grad_ψᵀp = NaN<config_t>; //< Dot product of gradient and p
65 real_t hx̂ = NaN<config_t>; //< Non-smooth function value in x̂
66
67 // @pre @ref ψx, @ref hx̂ @ref pᵀp, @ref grad_ψᵀp
68 // @return φγ
69 real_t fbe() const { return ψx + hx̂ + pᵀp / (2 * γ) + grad_ψᵀp; }
70
71 Iterate(length_t n, length_t m) : x(n), x̂(n), grad_ψ(n), p(n), ŷx̂(m) {}
72 } iterates[2]{{n, m}, {n, m}};
73 Iterate *curr = &iterates[0];
74 Iterate *next = &iterates[1];
75
76 bool need_grad_ψx̂ = Helpers::stop_crit_requires_grad_ψx̂(params.stop_crit);
77 vec grad_ψx̂(n);
78 vec work_n(n), work_m(m);
79 vec q(n); // (quasi-)Newton step Hₖ pₖ
80
81 // Helper functions --------------------------------------------------------
82
83 auto qub_violated = [this](const Iterate &i) {
84 real_t margin =
85 (1 + std::abs(i.ψx)) * params.quadratic_upperbound_tolerance_factor;
86 return i.ψx̂ > i.ψx + i.grad_ψᵀp + real_t(0.5) * i.L * i.pᵀp + margin;
87 };
88
89 auto linesearch_violated = [this](const Iterate &curr,
90 const Iterate &next) {
91 if (params.force_linesearch)
92 return false;
93 real_t β = params.linesearch_strictness_factor;
94 real_t σ = β * (1 - curr.γ * curr.L) / (2 * curr.γ);
95 real_t φγ = curr.fbe();
96 real_t margin = (1 + std::abs(φγ)) * params.linesearch_tolerance_factor;
97 return next.fbe() > φγ - σ * curr.pᵀp + margin;
98 };
99
100 // Problem functions -------------------------------------------------------
101
102 auto eval_ψ_grad_ψ = [&problem, &y, &Σ, &work_n, &work_m](Iterate &i) {
103 i.ψx = problem.eval_ψ_grad_ψ(i.x, y, Σ, i.grad_ψ, work_n, work_m);
104 };
105 auto eval_prox_grad_step = [&problem](Iterate &i) {
106 i.hx̂ = problem.eval_prox_grad_step(i.γ, i.x, i.grad_ψ, i.x̂, i.p);
107 i.pᵀp = i.p.squaredNorm();
108 i.grad_ψᵀp = i.p.dot(i.grad_ψ);
109 };
110 auto eval_ψx̂ = [&problem, &y, &Σ](Iterate &i) {
111 i.ψx̂ = problem.eval_ψ(i.x̂, y, Σ, i.ŷx̂);
112 };
113 auto eval_grad_ψx̂ = [&problem, &work_n](Iterate &i, rvec grad_ψx̂) {
114 problem.eval_grad_L(i.x̂, i.ŷx̂, grad_ψx̂, work_n);
115 };
116
117 // Printing ----------------------------------------------------------------
118
119 std::array<char, 64> print_buf;
120 auto print_real = [this, &print_buf](real_t x) {
121 return float_to_str_vw(print_buf, x, params.print_precision);
122 };
123 auto print_real3 = [&print_buf](real_t x) {
124 return float_to_str_vw(print_buf, x, 3);
125 };
126 auto print_progress_1 = [&print_real, os](unsigned k, real_t φₖ, real_t ψₖ,
127 crvec grad_ψₖ, real_t pₖᵀpₖ,
128 real_t γₖ, real_t εₖ) {
129 if (k == 0)
130 *os << "┌─[PANOC]\n";
131 else
132 *os << "├─ " << std::setw(6) << k << '\n';
133 *os << "│ φγ = " << print_real(φₖ) //
134 << ", ψ = " << print_real(ψₖ) //
135 << ", ‖∇ψ‖ = " << print_real(grad_ψₖ.norm()) //
136 << ", ‖p‖ = " << print_real(std::sqrt(pₖᵀpₖ)) //
137 << ", γ = " << print_real(γₖ) //
138 << ", ε = " << print_real(εₖ) << '\n';
139 };
140 auto print_progress_2 = [&print_real, &print_real3, os](crvec qₖ,
141 real_t τₖ) {
142 *os << "│ ‖q‖ = " << print_real(qₖ.norm()) //
143 << ", τ = " << print_real3(τₖ) //
144 << std::endl; // Flush for Python buffering
145 };
146 auto print_progress_n = [&](SolverStatus status) {
147 *os << "└─ " << status << " ──"
148 << std::endl; // Flush for Python buffering
149 };
150
151 auto do_progress_cb = [this, &s, &problem, &Σ, &y, &opts](
152 unsigned k, Iterate &it, crvec q, crvec grad_ψx̂,
153 real_t τ, real_t εₖ, SolverStatus status) {
154 using enum SolverStatus;
155 if (!progress_cb)
156 return;
159 progress_cb(ProgressInfo{
160 .k = k,
161 .status = status,
162 .x = it.x,
163 .p = it.p,
164 .norm_sq_p = it.pᵀp,
165 .x̂ = it.x̂,
166 .φγ = it.fbe(),
167 .ψ = it.ψx,
168 .grad_ψ = it.grad_ψ,
169 .ψ_hat = it.ψx̂,
170 .grad_ψ_hat = grad_ψx̂,
171 .q = q,
172 .L = it.L,
173 .γ = it.γ,
174 .τ = τ,
175 .ε = εₖ,
176 .Σ = Σ,
177 .y = y,
178 .outer_iter = opts.outer_iter,
179 .problem = &problem,
180 .params = &params,
181 });
182 };
183
184 // Initialization ----------------------------------------------------------
185
186 curr->x = x;
187
188 // Estimate Lipschitz constant ---------------------------------------------
189
190 // Finite difference approximation of ∇²ψ in starting point
191 if (params.Lipschitz.L_0 <= 0) {
192 curr->L = Helpers::initial_lipschitz_estimate(
193 problem, curr->x, y, Σ, params.Lipschitz.ε, params.Lipschitz.δ,
194 params.L_min, params.L_max,
195 /* in ⟹ out */ curr->ψx, curr->grad_ψ, curr->x̂, next->grad_ψ,
196 work_n, work_m);
197 }
198 // Initial Lipschitz constant provided by the user
199 else {
200 curr->L = params.Lipschitz.L_0;
201 // Calculate ψ(xₖ), ∇ψ(x₀)
202 eval_ψ_grad_ψ(*curr);
203 }
204 if (not std::isfinite(curr->L)) {
206 return s;
207 }
208 curr->γ = params.Lipschitz.Lγ_factor / curr->L;
209
210 // First proximal gradient step --------------------------------------------
211
212 eval_prox_grad_step(*curr);
213 eval_ψx̂(*curr);
214
215 // Quadratic upper bound
216 while (curr->L < params.L_max && qub_violated(*curr)) {
217 curr->γ /= 2;
218 curr->L *= 2;
219 eval_prox_grad_step(*curr);
220 eval_ψx̂(*curr);
221 }
222
223 // Loop data ---------------------------------------------------------------
224
225 unsigned k = 0; // iteration
226 real_t τ = NaN<config_t>; // line search parameter
227 // Keep track of how many successive iterations didn't update the iterate
228 unsigned no_progress = 0;
229
230 // Main PANOC loop
231 // =========================================================================
232
233 ScopedMallocBlocker mb; // Don't allocate in the inner loop
234 while (true) {
235
236 // Check stopping criteria ---------------------------------------------
237
238 // Calculate ∇ψ(x̂ₖ)
239 if (need_grad_ψx̂)
240 eval_grad_ψx̂(*curr, grad_ψx̂);
241 bool have_grad_ψx̂ = need_grad_ψx̂;
242
243 real_t εₖ = Helpers::calc_error_stop_crit(
244 problem, params.stop_crit, curr->p, curr->γ, curr->x, curr->x̂,
245 curr->ŷx̂, curr->grad_ψ, grad_ψx̂, work_n, next->p);
246
247 // Print progress ------------------------------------------------------
248 bool do_print =
249 params.print_interval != 0 && k % params.print_interval == 0;
250 if (do_print)
251 print_progress_1(k, curr->fbe(), curr->ψx, curr->grad_ψ, curr->pᵀp,
252 curr->γ, εₖ);
253
254 // Return solution -----------------------------------------------------
255
256 auto time_elapsed = std::chrono::steady_clock::now() - start_time;
257 auto stop_status = Helpers::check_all_stop_conditions(
258 params, opts, time_elapsed, k, stop_signal, εₖ, no_progress);
259 if (stop_status != SolverStatus::Busy) {
260 do_progress_cb(k, *curr, null_vec<config_t>, grad_ψx̂, -1, εₖ,
261 stop_status);
262 bool do_final_print = params.print_interval != 0;
263 if (!do_print && do_final_print)
264 print_progress_1(k, curr->fbe(), curr->ψx, curr->grad_ψ,
265 curr->pᵀp, curr->γ, εₖ);
266 if (do_print || do_final_print)
267 print_progress_n(stop_status);
268 if (stop_status == SolverStatus::Converged ||
269 stop_status == SolverStatus::Interrupted ||
270 opts.always_overwrite_results) {
271 auto &ŷ = curr->ŷx̂;
272 if (err_z.size() > 0)
273 err_z = Σ.asDiagonal().inverse() * (ŷ - y);
274 x = std::move(curr->x̂);
275 y = std::move(curr->ŷx̂);
276 }
277 s.iterations = k;
278 s.ε = εₖ;
279 s.elapsed_time = duration_cast<nanoseconds>(time_elapsed);
280 s.status = stop_status;
281 s.final_γ = curr->γ;
282 s.final_ψ = curr->ψx̂;
283 s.final_h = curr->hx̂;
284 s.final_φγ = curr->fbe();
285 return s;
286 }
287
288 // Calculate quasi-Newton step -----------------------------------------
289
290 real_t τ_init = NaN<config_t>;
291 if (k == 0) { // Initialize L-BFGS
293 direction.initialize(problem, y, Σ, curr->γ, curr->x, curr->x̂,
294 curr->p, curr->grad_ψ);
295 τ_init = 0;
296 }
297 if (k > 0 || direction.has_initial_direction()) {
298 τ_init = direction.apply(curr->γ, curr->x, curr->x̂, curr->p,
299 curr->grad_ψ, q)
300 ? 1
301 : 0;
302 // Make sure quasi-Newton step is valid
303 if (τ_init == 1 && not q.allFinite())
304 τ_init = 0;
305 if (τ_init != 1) { // If we computed a quasi-Newton step
306 ++s.lbfgs_failures;
307 direction.reset(); // Is there anything else we can do?
308 }
309 }
310
311 // Line search ---------------------------------------------------------
312
313 next->γ = curr->γ;
314 next->L = curr->L;
315 τ = τ_init;
316 real_t τ_prev = -1;
317 bool update_lbfgs_in_linesearch = params.update_direction_in_candidate;
318 bool update_lbfgs_later = !update_lbfgs_in_linesearch;
319
320 // xₖ₊₁ = xₖ + pₖ
321 auto take_safe_step = [&] {
322 // Calculate ∇ψ(xₖ₊₁)
323 if (not have_grad_ψx̂)
324 eval_grad_ψx̂(*curr, grad_ψx̂);
325 have_grad_ψx̂ = true;
326 next->x = curr->x̂; // → safe prox step
327 next->ψx = curr->ψx̂;
328 next->grad_ψ.swap(grad_ψx̂);
329 };
330
331 // xₖ₊₁ = xₖ + (1-τ) pₖ + τ qₖ
332 auto take_accelerated_step = [&](real_t τ) {
333 if (τ == 1) // → faster quasi-Newton step
334 next->x = curr->x + q;
335 else
336 next->x = curr->x + (1 - τ) * curr->p + τ * q;
337 // Calculate ψ(xₖ₊₁), ∇ψ(xₖ₊₁)
338 eval_ψ_grad_ψ(*next);
339 };
340
341 while (!stop_signal.stop_requested()) {
342
343 // Recompute step only if τ changed
344 if (τ != τ_prev) {
345 τ != 0 ? take_accelerated_step(τ) : take_safe_step();
346 τ_prev = τ;
347 }
348
349 // If the cost is not finite, abandon the direction entirely, don't
350 // even bother backtracking.
351 if (τ > 0 && !std::isfinite(next->ψx)) {
352 τ = 0;
353 direction.reset();
354 continue;
355 }
356
357 // Calculate x̂ₖ₊₁, ψ(x̂ₖ₊₁)
358 eval_prox_grad_step(*next);
359 eval_ψx̂(*next);
360
361 // Quadratic upper bound
362 if (next->L < params.L_max && qub_violated(*next)) {
363 next->γ /= 2;
364 next->L *= 2;
365 τ = τ_init;
367 update_lbfgs_in_linesearch = false;
368 update_lbfgs_later = true;
369 continue;
370 }
371
372 // Update L-BFGS
373 if (τ == 1 && update_lbfgs_in_linesearch) {
374 s.lbfgs_rejected += not direction.update(
375 curr->γ, next->γ, curr->x, next->x, curr->p, next->p,
376 curr->grad_ψ, next->grad_ψ);
377 update_lbfgs_in_linesearch = false;
378 update_lbfgs_later = false;
379 }
380
381 // Line search condition
382 if (τ > 0 && linesearch_violated(*curr, *next)) {
383 τ /= 2;
384 if (τ < params.min_linesearch_coefficient)
385 τ = 0;
387 continue;
388 }
389
390 // QUB and line search satisfied
391 break;
392 }
393 // If τ < τ_min the line search failed and we accepted the prox step
394 s.linesearch_failures += (τ == 0 && τ_init > 0);
395 s.τ_1_accepted += τ == 1;
396 s.count_τ += 1;
397 s.sum_τ += τ;
398
399 // Check if we made any progress
400 if (no_progress > 0 || k % params.max_no_progress == 0)
401 no_progress = curr->x == next->x ? no_progress + 1 : 0;
402
403 // Update L-BFGS -------------------------------------------------------
404
405 if (τ_init < 1 || update_lbfgs_later) {
406 if (curr->γ != next->γ) { // Flush L-BFGS if γ changed
407 direction.changed_γ(next->γ, curr->γ);
408 if (params.recompute_last_prox_step_after_lbfgs_flush) {
409 curr->γ = next->γ;
410 curr->L = next->L;
411 eval_prox_grad_step(*curr);
412 }
413 }
414 s.lbfgs_rejected += not direction.update(
415 curr->γ, next->γ, curr->x, next->x, curr->p, next->p,
416 curr->grad_ψ, next->grad_ψ);
417 }
418
419 // Print ---------------------------------------------------------------
420 do_progress_cb(k, *curr, q, grad_ψx̂, τ, εₖ, SolverStatus::Busy);
421 if (do_print && (k != 0 || direction.has_initial_direction()))
422 print_progress_2(q, τ);
423
424 // Advance step --------------------------------------------------------
425 std::swap(curr, next);
426 ++k;
427 }
428 throw std::logic_error("[PANOC] loop error");
429}
430
431} // namespace alpaqa
std::string get_name() const
Definition: panoc.tpp:21
Stats operator()(const Problem &problem, const SolveOptions &opts, rvec x, rvec y, crvec Σ, rvec err_z)
Definition: panoc.tpp:26
unsigned stepsize_backtracks
Definition: panoc.hpp:76
unsigned lbfgs_rejected
Definition: panoc.hpp:78
unsigned τ_1_accepted
Definition: panoc.hpp:79
unsigned lbfgs_failures
Definition: panoc.hpp:77
real_t final_φγ
Definition: panoc.hpp:85
SolverStatus
Exit status of a numerical solver such as ALM or PANOC.
@ Interrupted
Solver was interrupted by the user.
@ Busy
In progress.
@ Converged
Converged and reached given tolerance.
@ NotFinite
Intermediate results were infinite or not-a-number.
std::chrono::nanoseconds time_progress_callback
Definition: panoc.hpp:72
std::chrono::nanoseconds elapsed_time
Definition: panoc.hpp:71
typename Conf::real_t real_t
Definition: config.hpp:51
unsigned linesearch_backtracks
Definition: panoc.hpp:75
real_t final_ψ
Definition: panoc.hpp:83
real_t final_h
Definition: panoc.hpp:84
typename Conf::length_t length_t
Definition: config.hpp:62
typename Conf::rvec rvec
Definition: config.hpp:55
std::string_view float_to_str_vw(auto &buf, double value, int precision=std::numeric_limits< double >::max_digits10)
Definition: print.tpp:38
typename Conf::crvec crvec
Definition: config.hpp:56
unsigned linesearch_failures
Definition: panoc.hpp:74
typename Conf::vec vec
Definition: config.hpp:52
real_t final_γ
Definition: panoc.hpp:82
unsigned iterations
Definition: panoc.hpp:73
SolverStatus status
Definition: panoc.hpp:69
unsigned count_τ
Definition: panoc.hpp:80