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