alpaqa 1.0.0a13
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 auto &ŷ = curr->ŷx̂;
285 if (err_z.size() > 0)
286 err_z = Σ.asDiagonal().inverse() * (ŷ - y);
287 x = std::move(curr->x̂);
288 y = std::move(curr->ŷx̂);
289 }
290 s.iterations = k;
291 s.ε = εₖ;
294 s.final_γ = curr->γ;
295 s.final_ψ = curr->ψx̂;
296 s.final_h = curr->hx̂;
297 s.final_φγ = curr->fbe();
298 return s;
299 }
300
301 // Calculate quasi-Newton step -----------------------------------------
302
304 if (k == 0) { // Initialize L-BFGS
306 direction.initialize(problem, y, Σ, curr->γ, curr->x, curr->x̂,
307 curr->p, curr->grad_ψ);
308 τ_init = 0;
309 }
310 if (k > 0 || direction.has_initial_direction()) {
311 τ_init = direction.apply(curr->γ, curr->x, curr->x̂, curr->p,
312 curr->grad_ψ, q)
313 ? 1
314 : 0;
315 // Make sure quasi-Newton step is valid
316 if (τ_init == 1 && not q.allFinite())
317 τ_init = 0;
318 if (τ_init != 1) { // If we computed a quasi-Newton step
319 ++s.lbfgs_failures;
320 direction.reset(); // Is there anything else we can do?
321 }
322 }
323
324 // Line search ---------------------------------------------------------
325
326 next->γ = curr->γ;
327 next->L = curr->L;
328 τ = τ_init;
329 real_t τ_prev = -1;
330 bool update_lbfgs_in_linesearch = params.update_direction_in_candidate;
331 bool updated_lbfgs = false;
332 bool dir_rejected = true;
333
334 // xₖ₊₁ = xₖ + pₖ
335 auto take_safe_step = [&] {
336 // Calculate ∇ψ(xₖ₊₁)
337 if (not curr->have_grad_ψx̂)
339 next->x = curr->x̂; // → safe prox step
340 next->ψx = curr->ψx̂;
341 next->grad_ψ.swap(curr->grad_ψx̂);
342 curr->have_grad_ψx̂ = next->have_grad_ψx̂ = false;
343 };
344
345 // xₖ₊₁ = xₖ + (1-τ) pₖ + τ qₖ
346 auto take_accelerated_step = [&](real_t τ) {
347 if (τ == 1) // → faster quasi-Newton step
348 next->x = curr->x + q;
349 else
350 next->x = curr->x + (1 - τ) * curr->p + τ * q;
351 // Calculate ψ(xₖ₊₁), ∇ψ(xₖ₊₁)
352 eval_ψ_grad_ψ(*next);
353 next->have_grad_ψx̂ = false;
354 };
355
356 while (!stop_signal.stop_requested()) {
357
358 // Recompute step only if τ changed
359 if (τ != τ_prev) {
360 τ != 0 ? take_accelerated_step(τ) : take_safe_step();
361 τ_prev = τ;
362 }
363
364 // If the cost is not finite, or if the quadratic upper bound could
365 // not be satisfied, abandon the direction entirely, don't even
366 // bother backtracking.
367 bool fail = !std::isfinite(next->ψx);
368 fail |= next->L >= params.L_max && !(curr->L >= params.L_max);
369 if (τ > 0 && fail) {
370 // Don't allow a bad accelerated step to destroy the FBS step
371 // size
372 next->L = curr->L;
373 next->γ = curr->γ;
374 // Line search failed
375 τ = 0;
376 direction.reset();
377 // Update the direction in the FB iterate later
379 continue;
380 }
381
382 // Calculate x̂ₖ₊₁, ψ(x̂ₖ₊₁)
383 eval_prox_grad_step(*next);
385
386 // Quadratic upper bound step size condition
387 if (next->L < params.L_max && qub_violated(*next)) {
388 next->γ /= 2;
389 next->L *= 2;
390 if (τ > 0)
391 τ = τ_init;
393 // If the step size changes, we need extra care when updating
394 // the direction later
396 continue;
397 }
398
399 // Update L-BFGS in candidate (even if we don't accept this point)
401 s.lbfgs_rejected += dir_rejected = not direction.update(
402 curr->γ, next->γ, curr->x, next->x, curr->p, next->p,
403 curr->grad_ψ, next->grad_ψ);
405 updated_lbfgs = true;
406 }
407
408 // Line search condition
409 if (τ > 0 && linesearch_violated(*curr, *next)) {
410 τ /= 2;
411 if (τ < params.min_linesearch_coefficient)
412 τ = 0;
414 continue;
415 }
416
417 // QUB and line search satisfied (or τ is 0 and L > L_max)
418 break;
419 }
420 // If τ < τ_min the line search failed and we accepted the prox step
421 s.linesearch_failures += (τ == 0 && τ_init > 0);
422 s.τ_1_accepted += τ == 1;
423 s.count_τ += (τ_init > 0);
424 s.sum_τ += τ;
425
426 // Check if we made any progress
427 if (no_progress > 0 || k % params.max_no_progress == 0)
428 no_progress = curr->x == next->x ? no_progress + 1 : 0;
429
430 // Update L-BFGS -------------------------------------------------------
431
432 if (!updated_lbfgs) {
433 if (curr->γ != next->γ) { // Flush L-BFGS if γ changed
434 direction.changed_γ(next->γ, curr->γ);
435 if (params.recompute_last_prox_step_after_stepsize_change) {
436 curr->γ = next->γ;
437 curr->L = next->L;
438 eval_prox_grad_step(*curr);
439 }
440 }
441 s.lbfgs_rejected += dir_rejected = not direction.update(
442 curr->γ, next->γ, curr->x, next->x, curr->p, next->p,
443 curr->grad_ψ, next->grad_ψ);
444 }
445
446 // Print ---------------------------------------------------------------
448 if (do_print && (k != 0 || direction.has_initial_direction()))
450
451 // Advance step --------------------------------------------------------
452 std::swap(curr, next);
453 ++k;
454 }
455 throw std::logic_error("[PANOC] loop error");
456}
457
458} // 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