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