alpaqa 1.0.0a10
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);
226 }
227
228 // Loop data ---------------------------------------------------------------
229
230 unsigned k = 0; // iteration
231 real_t τ = NaN<config_t>; // line search parameter
232 // Keep track of how many successive iterations didn't update the iterate
233 unsigned no_progress = 0;
234
235 // Main PANOC loop
236 // =========================================================================
237
238 ScopedMallocBlocker mb; // Don't allocate in the inner loop
239 while (true) {
240
241 // Check stopping criteria ---------------------------------------------
242
243 // Calculate ∇ψ(x̂ₖ)
244 if (need_grad_ψx̂)
245 eval_grad_ψx̂(*curr, grad_ψx̂);
246 bool have_grad_ψx̂ = need_grad_ψx̂;
247
248 real_t εₖ = Helpers::calc_error_stop_crit(
249 problem, params.stop_crit, curr->p, curr->γ, curr->x, curr->x̂,
250 curr->ŷx̂, curr->grad_ψ, grad_ψx̂, work_n, next->p);
251
252 // Print progress ------------------------------------------------------
253 bool do_print =
254 params.print_interval != 0 && k % params.print_interval == 0;
255 if (do_print)
256 print_progress_1(k, curr->fbe(), curr->ψx, curr->grad_ψ, curr->pᵀp,
257 curr->γ, εₖ);
258
259 // Return solution -----------------------------------------------------
260
261 auto time_elapsed = std::chrono::steady_clock::now() - start_time;
262 auto stop_status = Helpers::check_all_stop_conditions(
263 params, opts, time_elapsed, k, stop_signal, εₖ, no_progress);
264 if (stop_status != SolverStatus::Busy) {
265 do_progress_cb(k, *curr, null_vec<config_t>, grad_ψx̂, -1, εₖ,
266 stop_status);
267 bool do_final_print = params.print_interval != 0;
268 if (!do_print && do_final_print)
269 print_progress_1(k, curr->fbe(), curr->ψx, curr->grad_ψ,
270 curr->pᵀp, curr->γ, εₖ);
271 if (do_print || do_final_print)
272 print_progress_n(stop_status);
273 if (stop_status == SolverStatus::Converged ||
274 stop_status == SolverStatus::Interrupted ||
275 opts.always_overwrite_results) {
276 auto &ŷ = curr->ŷx̂;
277 if (err_z.size() > 0)
278 err_z = Σ.asDiagonal().inverse() * (ŷ - y);
279 x = std::move(curr->x̂);
280 y = std::move(curr->ŷx̂);
281 }
282 s.iterations = k;
283 s.ε = εₖ;
284 s.elapsed_time = duration_cast<nanoseconds>(time_elapsed);
285 s.status = stop_status;
286 s.final_γ = curr->γ;
287 s.final_ψ = curr->ψx̂;
288 s.final_h = curr->hx̂;
289 s.final_φγ = curr->fbe();
290 return s;
291 }
292
293 // Calculate quasi-Newton step -----------------------------------------
294
295 real_t τ_init = NaN<config_t>;
296 if (k == 0) { // Initialize L-BFGS
298 direction.initialize(problem, y, Σ, curr->γ, curr->x, curr->x̂,
299 curr->p, curr->grad_ψ);
300 τ_init = 0;
301 }
302 if (k > 0 || direction.has_initial_direction()) {
303 τ_init = direction.apply(curr->γ, curr->x, curr->x̂, curr->p,
304 curr->grad_ψ, q)
305 ? 1
306 : 0;
307 // Make sure quasi-Newton step is valid
308 if (τ_init == 1 && not q.allFinite())
309 τ_init = 0;
310 if (τ_init != 1) { // If we computed a quasi-Newton step
311 ++s.lbfgs_failures;
312 direction.reset(); // Is there anything else we can do?
313 }
314 }
315
316 // Line search ---------------------------------------------------------
317
318 next->γ = curr->γ;
319 next->L = curr->L;
320 τ = τ_init;
321 real_t τ_prev = -1;
322 bool update_lbfgs_in_linesearch = params.update_direction_in_candidate;
323 bool updated_lbfgs = false;
324 bool dir_rejected = true;
325
326 // xₖ₊₁ = xₖ + pₖ
327 auto take_safe_step = [&] {
328 // Calculate ∇ψ(xₖ₊₁)
329 if (not have_grad_ψx̂)
330 eval_grad_ψx̂(*curr, grad_ψx̂);
331 have_grad_ψx̂ = true;
332 next->x = curr->x̂; // → safe prox step
333 next->ψx = curr->ψx̂;
334 next->grad_ψ.swap(grad_ψx̂);
335 };
336
337 // xₖ₊₁ = xₖ + (1-τ) pₖ + τ qₖ
338 auto take_accelerated_step = [&](real_t τ) {
339 if (τ == 1) // → faster quasi-Newton step
340 next->x = curr->x + q;
341 else
342 next->x = curr->x + (1 - τ) * curr->p + τ * q;
343 // Calculate ψ(xₖ₊₁), ∇ψ(xₖ₊₁)
344 eval_ψ_grad_ψ(*next);
345 };
346
347 while (!stop_signal.stop_requested()) {
348
349 // Recompute step only if τ changed
350 if (τ != τ_prev) {
351 τ != 0 ? take_accelerated_step(τ) : take_safe_step();
352 τ_prev = τ;
353 }
354
355 // If the cost is not finite, or if the quadratic upper bound could
356 // not be satisfied, abandon the direction entirely, don't even
357 // bother backtracking.
358 bool fail = next->L >= params.L_max || !std::isfinite(next->ψx);
359 if (τ > 0 && fail) {
360 // Don't allow a bad accelerated step to destroy the FBS step
361 // size
362 next->L = curr->L;
363 next->γ = curr->γ;
364 // Line search failed
365 τ = 0;
366 direction.reset();
367 // Update the direction in the FB iterate later
368 update_lbfgs_in_linesearch = false;
369 continue;
370 }
371
372 // Calculate x̂ₖ₊₁, ψ(x̂ₖ₊₁)
373 eval_prox_grad_step(*next);
374 eval_ψx̂(*next);
375
376 // Quadratic upper bound step size condition
377 if (next->L < params.L_max && qub_violated(*next)) {
378 next->γ /= 2;
379 next->L *= 2;
380 if (τ > 0)
381 τ = τ_init;
383 // If the step size changes, we need extra care when updating
384 // the direction later
385 update_lbfgs_in_linesearch = false;
386 continue;
387 }
388
389 // Update L-BFGS in candidate (even if we don't accept this point)
390 if (update_lbfgs_in_linesearch && !updated_lbfgs) {
391 s.lbfgs_rejected += dir_rejected = not direction.update(
392 curr->γ, next->γ, curr->x, next->x, curr->p, next->p,
393 curr->grad_ψ, next->grad_ψ);
394 update_lbfgs_in_linesearch = false;
395 updated_lbfgs = true;
396 }
397
398 // Line search condition
399 if (τ > 0 && linesearch_violated(*curr, *next)) {
400 τ /= 2;
401 if (τ < params.min_linesearch_coefficient)
402 τ = 0;
404 continue;
405 }
406
407 // QUB and line search satisfied (or τ is 0 and L > L_max)
408 break;
409 }
410 // If τ < τ_min the line search failed and we accepted the prox step
411 s.linesearch_failures += (τ == 0 && τ_init > 0);
412 s.τ_1_accepted += τ == 1;
413 s.count_τ += (τ_init > 0);
414 s.sum_τ += τ;
415
416 // Check if we made any progress
417 if (no_progress > 0 || k % params.max_no_progress == 0)
418 no_progress = curr->x == next->x ? no_progress + 1 : 0;
419
420 // Update L-BFGS -------------------------------------------------------
421
422 if (!updated_lbfgs) {
423 if (curr->γ != next->γ) { // Flush L-BFGS if γ changed
424 direction.changed_γ(next->γ, curr->γ);
425 if (params.recompute_last_prox_step_after_lbfgs_flush) {
426 curr->γ = next->γ;
427 curr->L = next->L;
428 eval_prox_grad_step(*curr);
429 }
430 }
431 s.lbfgs_rejected += dir_rejected = not direction.update(
432 curr->γ, next->γ, curr->x, next->x, curr->p, next->p,
433 curr->grad_ψ, next->grad_ψ);
434 }
435
436 // Print ---------------------------------------------------------------
437 do_progress_cb(k, *curr, q, grad_ψx̂, τ, εₖ, SolverStatus::Busy);
438 if (do_print && (k != 0 || direction.has_initial_direction()))
439 print_progress_2(q, τ, dir_rejected);
440
441 // Advance step --------------------------------------------------------
442 std::swap(curr, next);
443 ++k;
444 }
445 throw std::logic_error("[PANOC] loop error");
446}
447
448} // 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