alpaqa matlab
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
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) {
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 ψₖ,
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 };
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.ŷx̂,
180 .φγ = it.fbe(),
181 .ψ = it.ψx,
182 .grad_ψ = it.grad_ψ,
183 .ψ_hat = it.ψx̂,
184 .grad_ψ_hat = grad_ψx̂,
185 .q = q,
186 .L = it.L,
187 .γ = it.γ,
188 .τ = τ,
189 .ε = εₖ,
190 .Σ = Σ,
191 .y = y,
192 .outer_iter = opts.outer_iter,
193 .problem = &problem,
194 .params = &params,
195 });
196 };
197
198 // Initialization ----------------------------------------------------------
199
200 curr->x = x;
201
202 // Estimate Lipschitz constant ---------------------------------------------
203
204 // Finite difference approximation of ∇²ψ in starting point
205 if (params.Lipschitz.L_0 <= 0) {
206 curr->L = Helpers::initial_lipschitz_estimate(
207 problem, curr->x, y, Σ, params.Lipschitz.ε, params.Lipschitz.δ,
208 params.L_min, params.L_max,
209 /* in ⟹ out */ curr->ψx, curr->grad_ψ, curr->x̂, next->grad_ψ,
210 work_n, work_m);
211 }
212 // Initial Lipschitz constant provided by the user
213 else {
214 curr->L = params.Lipschitz.L_0;
215 // Calculate ψ(xₖ), ∇ψ(x₀)
216 eval_ψ_grad_ψ(*curr);
217 }
218 if (not std::isfinite(curr->L)) {
220 return s;
221 }
222 curr->γ = params.Lipschitz.Lγ_factor / curr->L;
223
224 // First proximal gradient step --------------------------------------------
225
226 eval_prox_grad_step(*curr);
228
229 // Quadratic upper bound
230 while (curr->L < params.L_max && qub_violated(*curr)) {
231 curr->γ /= 2;
232 curr->L *= 2;
233 eval_prox_grad_step(*curr);
236 }
237
238 // Loop data ---------------------------------------------------------------
239
240 unsigned k = 0; // iteration
241 real_t τ = NaN<config_t>; // line search parameter
242 // Keep track of how many successive iterations didn't update the iterate
243 unsigned no_progress = 0;
244
245 // Main PANOC loop
246 // =========================================================================
247
248 ScopedMallocBlocker mb; // Don't allocate in the inner loop
249 while (true) {
250
251 // Check stopping criteria ---------------------------------------------
252
253 // Calculate ∇ψ(x̂ₖ)
254 if (need_grad_ψx̂ && !curr->have_grad_ψx̂)
256
257 real_t εₖ = Helpers::calc_error_stop_crit(
258 problem, params.stop_crit, curr->p, curr->γ, curr->x, curr->x̂,
259 curr->ŷx̂, curr->grad_ψ, curr->grad_ψx̂, work_n, next->p);
260
261 // Print progress ------------------------------------------------------
262 bool do_print =
263 params.print_interval != 0 && k % params.print_interval == 0;
264 if (do_print)
265 print_progress_1(k, curr->fbe(), curr->ψx, curr->grad_ψ, curr->pᵀp,
266 curr->γ, εₖ);
267
268 // Return solution -----------------------------------------------------
269
270 auto time_elapsed = std::chrono::steady_clock::now() - start_time;
271 auto stop_status = Helpers::check_all_stop_conditions(
272 params, opts, time_elapsed, k, stop_signal, εₖ, no_progress);
275 bool do_final_print = params.print_interval != 0;
276 if (!do_print && do_final_print)
277 print_progress_1(k, curr->fbe(), curr->ψx, curr->grad_ψ,
278 curr->pᵀp, curr->γ, εₖ);
283 opts.always_overwrite_results) {
284 // Calculate ŷ
285 if (params.eager_gradient_eval)
287 auto &ŷ = curr->ŷx̂;
288 if (err_z.size() > 0)
289 err_z = Σ.asDiagonal().inverse() * (ŷ - y);
290 x = std::move(curr->x̂);
291 y = std::move(curr->ŷx̂);
292 }
293 s.iterations = k;
294 s.ε = εₖ;
297 s.final_γ = curr->γ;
298 s.final_ψ = curr->ψx̂;
299 s.final_h = curr->hx̂;
300 s.final_φγ = curr->fbe();
301 return s;
302 }
303
304 // Calculate quasi-Newton step -----------------------------------------
305
307 if (k == 0) { // Initialize L-BFGS
309 direction.initialize(problem, y, Σ, curr->γ, curr->x, curr->x̂,
310 curr->p, curr->grad_ψ);
311 τ_init = 0;
312 }
313 if (k > 0 || direction.has_initial_direction()) {
314 τ_init = direction.apply(curr->γ, curr->x, curr->x̂, curr->p,
315 curr->grad_ψ, q)
316 ? 1
317 : 0;
318 // Make sure quasi-Newton step is valid
319 if (τ_init == 1 && not q.allFinite())
320 τ_init = 0;
321 if (τ_init != 1) { // If we computed a quasi-Newton step
322 ++s.lbfgs_failures;
323 direction.reset(); // Is there anything else we can do?
324 }
325 }
326
327 // Line search ---------------------------------------------------------
328
329 next->γ = curr->γ;
330 next->L = curr->L;
331 τ = τ_init;
332 real_t τ_prev = -1;
333 bool update_lbfgs_in_linesearch = params.update_direction_in_candidate;
334 bool updated_lbfgs = false;
335 bool dir_rejected = true;
336
337 // xₖ₊₁ = xₖ + pₖ
338 auto take_safe_step = [&] {
339 // Calculate ∇ψ(xₖ₊₁)
340 if (not curr->have_grad_ψx̂)
342 next->x = curr->x̂; // → safe prox step
343 next->ψx = curr->ψx̂;
344 next->grad_ψ.swap(curr->grad_ψx̂);
345 curr->have_grad_ψx̂ = next->have_grad_ψx̂ = false;
346 };
347
348 // xₖ₊₁ = xₖ + (1-τ) pₖ + τ qₖ
349 auto take_accelerated_step = [&](real_t τ) {
350 if (τ == 1) // → faster quasi-Newton step
351 next->x = curr->x + q;
352 else
353 next->x = curr->x + (1 - τ) * curr->p + τ * q;
354 // Calculate ψ(xₖ₊₁), ∇ψ(xₖ₊₁)
355 eval_ψ_grad_ψ(*next);
356 next->have_grad_ψx̂ = false;
357 };
358
359 while (!stop_signal.stop_requested()) {
360
361 // Recompute step only if τ changed
362 if (τ != τ_prev) {
363 τ != 0 ? take_accelerated_step(τ) : take_safe_step();
364 τ_prev = τ;
365 }
366
367 // If the cost is not finite, or if the quadratic upper bound could
368 // not be satisfied, abandon the direction entirely, don't even
369 // bother backtracking.
370 bool fail = !std::isfinite(next->ψx);
371 fail |= next->L >= params.L_max && !(curr->L >= params.L_max);
372 if (τ > 0 && fail) {
373 // Don't allow a bad accelerated step to destroy the FBS step
374 // size
375 next->L = curr->L;
376 next->γ = curr->γ;
377 // Line search failed
378 τ = 0;
379 direction.reset();
380 // Update the direction in the FB iterate later
382 continue;
383 }
384
385 // Calculate x̂ₖ₊₁, ψ(x̂ₖ₊₁)
386 eval_prox_grad_step(*next);
388
389 // Quadratic upper bound step size condition
390 if (next->L < params.L_max && qub_violated(*next)) {
391 next->γ /= 2;
392 next->L *= 2;
393 if (τ > 0)
394 τ = τ_init;
396 // If the step size changes, we need extra care when updating
397 // the direction later
399 continue;
400 }
401
402 // Update L-BFGS in candidate (even if we don't accept this point)
404 s.lbfgs_rejected += dir_rejected = not direction.update(
405 curr->γ, next->γ, curr->x, next->x, curr->p, next->p,
406 curr->grad_ψ, next->grad_ψ);
408 updated_lbfgs = true;
409 }
410
411 // Line search condition
412 if (τ > 0 && linesearch_violated(*curr, *next)) {
413 τ /= 2;
414 if (τ < params.min_linesearch_coefficient)
415 τ = 0;
417 continue;
418 }
419
420 // QUB and line search satisfied (or τ is 0 and L > L_max)
421 break;
422 }
423 // If τ < τ_min the line search failed and we accepted the prox step
424 s.linesearch_failures += (τ == 0 && τ_init > 0);
425 s.τ_1_accepted += τ == 1;
426 s.count_τ += (τ_init > 0);
427 s.sum_τ += τ;
428
429 // Check if we made any progress
430 if (no_progress > 0 || k % params.max_no_progress == 0)
431 no_progress = curr->x == next->x ? no_progress + 1 : 0;
432
433 // Update L-BFGS -------------------------------------------------------
434
435 if (!updated_lbfgs) {
436 if (curr->γ != next->γ) { // Flush L-BFGS if γ changed
437 direction.changed_γ(next->γ, curr->γ);
438 if (params.recompute_last_prox_step_after_stepsize_change) {
439 curr->γ = next->γ;
440 curr->L = next->L;
441 eval_prox_grad_step(*curr);
442 }
443 }
444 s.lbfgs_rejected += dir_rejected = not direction.update(
445 curr->γ, next->γ, curr->x, next->x, curr->p, next->p,
446 curr->grad_ψ, next->grad_ψ);
447 }
448
449 // Print ---------------------------------------------------------------
451 if (do_print && (k != 0 || direction.has_initial_direction()))
453
454 // Advance step --------------------------------------------------------
455 std::swap(curr, next);
456 ++k;
457 }
458 throw std::logic_error("[PANOC] loop error");
459}
460
461} // 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:96
unsigned lbfgs_rejected
Definition panoc.hpp:98
unsigned τ_1_accepted
Definition panoc.hpp:99
unsigned lbfgs_failures
Definition panoc.hpp:97
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:92
std::chrono::nanoseconds elapsed_time
Definition panoc.hpp:91
typename Conf::real_t real_t
Definition config.hpp:65
unsigned linesearch_backtracks
Definition panoc.hpp:95
typename Conf::length_t length_t
Definition config.hpp:76
constexpr const auto inf
Definition config.hpp:85
typename Conf::rvec rvec
Definition config.hpp:69
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:70
unsigned linesearch_failures
Definition panoc.hpp:94
typename Conf::vec vec
Definition config.hpp:66
unsigned iterations
Definition panoc.hpp:93
SolverStatus status
Definition panoc.hpp:89
unsigned count_τ
Definition panoc.hpp:100