Nonconvex constrained optimization
Loading...
Searching...
No Matches
zerofpr.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
14#include <alpaqa/util/print.hpp>
15#include <guanaqo/timed.hpp>
16
17namespace alpaqa {
18
19template <class DirectionProviderT>
21 return "ZeroFPRSolver<" + 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_num_variables();
48 const auto m = problem.get_num_constraints();
49
50 // Represents an intermediate proximal iterate in the algorithm.
51 struct ProxIterate {
52 vec x̂; //< Decision variables after proximal gradient step
53 vec grad_ψ; //< Gradient of cost in x
54 vec p; //< Proximal gradient step in x
55 vec ŷx̂; //< Candidate Lagrange multipliers in x̂
56 real_t pᵀp = NaN<config_t>; //< Norm squared of p
57 real_t grad_ψᵀp = NaN<config_t>; //< Dot product of gradient and p
58 real_t hx̂ = NaN<config_t>; //< Non-smooth function value in x̂
59
60 ProxIterate(length_t n, length_t m) : x̂(n), grad_ψ(n), p(n), ŷx̂(m) {}
61 } prox_iterate{n, m};
62 // Represents an iterate in the algorithm, keeping track of some
63 // intermediate values and function evaluations.
64 struct Iterate {
65 vec x; //< Decision variables
66 vec x̂; //< Decision variables after proximal gradient step
67 vec grad_ψ; //< Gradient of cost in x
68 vec p; //< Proximal gradient step in x
69 vec ŷx̂; //< Candidate Lagrange multipliers in x̂
70 real_t ψx = NaN<config_t>; //< Cost in x
71 real_t ψx̂ = NaN<config_t>; //< Cost in x̂
72 real_t γ = NaN<config_t>; //< Step size γ
73 real_t L = NaN<config_t>; //< Lipschitz estimate L
74 real_t pᵀp = NaN<config_t>; //< Norm squared of p
75 real_t grad_ψᵀp = NaN<config_t>; //< Dot product of gradient and p
76 real_t hx̂ = NaN<config_t>; //< Non-smooth function value in x̂
77
78 // @pre @ref ψx, @ref hx̂ @ref pᵀp, @ref grad_ψᵀp
79 // @return φγ
80 real_t fbe() const { return ψx + hx̂ + pᵀp / (2 * γ) + grad_ψᵀp; }
81
82 Iterate(length_t n, length_t m) : x(n), x̂(n), grad_ψ(n), p(n), ŷx̂(m) {}
83 } iterates[2]{{n, m}, {n, m}};
84 Iterate *curr = &iterates[0];
85 ProxIterate *prox = &prox_iterate;
86 Iterate *next = &iterates[1];
87
88 vec work_n(n), work_m(m);
89 vec q(n); // (quasi-)Newton step Hₖ pₖ
90
91 // Helper functions --------------------------------------------------------
92
93 auto qub_violated = [this](const Iterate &i) {
94 real_t margin =
95 (1 + std::abs(i.ψx)) * params.quadratic_upperbound_tolerance_factor;
96 return i.ψx̂ > i.ψx + i.grad_ψᵀp + real_t(0.5) * i.L * i.pᵀp + margin;
97 };
98
99 auto linesearch_violated = [this](const Iterate &curr,
100 const Iterate &next) {
101 if (params.force_linesearch)
102 return false;
103 real_t β = params.linesearch_strictness_factor;
104 real_t σ = β * (1 - curr.γ * curr.L) / (2 * curr.γ);
105 real_t φγ = curr.fbe();
106 real_t margin = (1 + std::abs(φγ)) * params.linesearch_tolerance_factor;
107 return next.fbe() > φγ - σ * curr.pᵀp + margin;
108 };
109
110 // Problem functions -------------------------------------------------------
111
112 auto eval_ψ_grad_ψ = [&problem, &y, &Σ, &work_n, &work_m](Iterate &i) {
113 i.ψx = problem.eval_augmented_lagrangian_and_gradient(
114 i.x, y, Σ, i.grad_ψ, work_n, work_m);
115 };
116 auto eval_prox_grad_step = [&problem](Iterate &i) {
117 i.hx̂ =
118 problem.eval_proximal_gradient_step(i.γ, i.x, i.grad_ψ, i.x̂, i.p);
119 i.pᵀp = i.p.squaredNorm();
120 i.grad_ψᵀp = i.p.dot(i.grad_ψ);
121 };
122 auto eval_cost_in_prox = [&problem, &y, &Σ](Iterate &i) {
123 i.ψx̂ = problem.eval_augmented_lagrangian(i.x̂, y, Σ, i.ŷx̂);
124 };
125 auto eval_grad_in_prox = [&problem, &prox, &work_n](const Iterate &i) {
126 problem.eval_lagrangian_gradient(i.x̂, i.ŷx̂, prox->grad_ψ, work_n);
127 };
128 auto eval_prox_grad_step_in_prox = [&problem, &prox](const Iterate &i) {
129 prox->hx̂ = problem.eval_proximal_gradient_step(i.γ, i.x̂, prox->grad_ψ,
130 prox->x̂, prox->p);
131 prox->pᵀp = prox->p.squaredNorm();
132 prox->grad_ψᵀp = prox->p.dot(prox->grad_ψ);
133 };
134
135 // Printing ----------------------------------------------------------------
136
137 std::array<char, 64> print_buf;
138 auto print_real = [this, &print_buf](real_t x) {
139 return float_to_str_vw(print_buf, x, params.print_precision);
140 };
141 auto print_real3 = [&print_buf](real_t x) {
142 return float_to_str_vw(print_buf, x, 3);
143 };
144 auto print_progress_1 = [&print_real, os](unsigned k, real_t φₖ, real_t ψₖ,
145 crvec grad_ψₖ, real_t pₖᵀpₖ,
146 real_t γₖ, real_t εₖ) {
147 if (k == 0)
148 *os << "┌─[ZeroFPR]\n";
149 else
150 *os << "├─ " << std::setw(6) << k << '\n';
151 *os << "│ φγ = " << print_real(φₖ) //
152 << ", ψ = " << print_real(ψₖ) //
153 << ", ‖∇ψ‖ = " << print_real(grad_ψₖ.norm()) //
154 << ", ‖p‖ = " << print_real(std::sqrt(pₖᵀpₖ)) //
155 << ", γ = " << print_real(γₖ) //
156 << ", ε = " << print_real(εₖ) << '\n';
157 };
158 auto print_progress_2 = [&print_real, &print_real3, os](crvec qₖ, real_t τₖ,
159 bool reject) {
160 const char *color = τₖ == 1 ? "\033[0;32m"
161 : τₖ > 0 ? "\033[0;33m"
162 : "\033[0;35m";
163 *os << "│ ‖q‖ = " << print_real(qₖ.norm()) //
164 << ", τ = " << color << print_real3(τₖ) << "\033[0m" //
165 << ", dir update "
166 << (reject ? "\033[0;31mrejected\033[0m"
167 : "\033[0;32maccepted\033[0m") //
168 << std::endl; // Flush for Python buffering
169 };
170 auto print_progress_n = [&](SolverStatus status) {
171 *os << "└─ " << status << " ──"
172 << std::endl; // Flush for Python buffering
173 };
174
175 auto do_progress_cb = [this, &s, &problem, &Σ, &y, &opts](
176 unsigned k, Iterate &it, crvec q, crvec grad_ψx̂,
177 real_t τ, real_t εₖ, SolverStatus status) {
178 if (!progress_cb)
179 return;
181 guanaqo::Timed t{s.time_progress_callback};
183 .k = k,
184 .status = status,
185 .x = it.x,
186 .p = it.p,
187 .norm_sq_p = it.pᵀp,
188 .x̂ = it.x̂,
189 .ŷ = it.ŷx̂,
190 .φγ = it.fbe(),
191 .ψ = it.ψx,
192 .grad_ψ = it.grad_ψ,
193 .ψ_hat = it.ψx̂,
194 .grad_ψ_hat = grad_ψx̂,
195 .q = q,
196 .L = it.L,
197 .γ = it.γ,
198 .τ = τ,
199 .ε = εₖ,
200 .Σ = Σ,
201 .y = y,
202 .outer_iter = opts.outer_iter,
203 .problem = &problem,
204 .params = &params,
205 });
206 };
207
208 // Initialization ----------------------------------------------------------
209
210 curr->x = x;
211
212 // Estimate Lipschitz constant ---------------------------------------------
213
214 // Finite difference approximation of ∇²ψ in starting point
215 if (params.Lipschitz.L_0 <= 0) {
217 problem, curr->x, y, Σ, params.Lipschitz.ε, params.Lipschitz.δ,
218 params.L_min, params.L_max,
219 /* in ⟹ out */ curr->ψx, curr->grad_ψ, curr->x̂, next->grad_ψ,
220 work_n, work_m);
221 }
222 // Initial Lipschitz constant provided by the user
223 else {
224 curr->L = params.Lipschitz.L_0;
225 // Calculate ψ(xₖ), ∇ψ(x₀)
226 eval_ψ_grad_ψ(*curr);
227 }
228 if (not std::isfinite(curr->L)) {
230 return s;
231 }
232 curr->γ = params.Lipschitz.Lγ_factor / curr->L;
233
234 // First proximal gradient step --------------------------------------------
235
236 // Calculate x̂ₖ, ψ(x̂ₖ)
237 eval_prox_grad_step(*curr);
238 eval_cost_in_prox(*curr);
239
240 // Quadratic upper bound
241 while (curr->L < params.L_max && qub_violated(*curr)) {
242 curr->γ /= 2;
243 curr->L *= 2;
244 eval_prox_grad_step(*curr);
245 eval_cost_in_prox(*curr);
247 }
248
249 // Loop data ---------------------------------------------------------------
250
251 unsigned k = 0; // iteration
252 real_t τ = NaN<config_t>; // line search parameter
253 // Keep track of how many successive iterations didn't update the iterate
254 unsigned no_progress = 0;
255
256 // Main ZeroFPR loop
257 // =========================================================================
258
259 ScopedMallocBlocker mb; // Don't allocate in the inner loop
260 while (true) {
261
262 // Check stopping criteria ---------------------------------------------
263
264 // Calculate ∇ψ(x̂ₖ), p̂ₖ
265 eval_grad_in_prox(*curr);
266 eval_prox_grad_step_in_prox(*curr);
267
269 problem, params.stop_crit, curr->p, curr->γ, curr->x, curr->x̂,
270 curr->ŷx̂, curr->grad_ψ, prox->grad_ψ, work_n, next->p);
271
272 // Print progress ------------------------------------------------------
273 bool do_print =
274 params.print_interval != 0 && k % params.print_interval == 0;
275 if (do_print)
276 print_progress_1(k, curr->fbe(), curr->ψx, curr->grad_ψ, curr->pᵀp,
277 curr->γ, εₖ);
278
279 // Return solution -----------------------------------------------------
280
281 auto time_elapsed = std::chrono::steady_clock::now() - start_time;
282 auto stop_status = Helpers::check_all_stop_conditions(
283 params, opts, time_elapsed, k, stop_signal, εₖ, no_progress);
284 if (stop_status != SolverStatus::Busy) {
285 do_progress_cb(k, *curr, null_vec<config_t>, prox->grad_ψ, -1, εₖ,
286 stop_status);
287 bool do_final_print = params.print_interval != 0;
288 if (!do_print && do_final_print)
289 print_progress_1(k, curr->fbe(), curr->ψx, curr->grad_ψ,
290 curr->pᵀp, curr->γ, εₖ);
291 if (do_print || do_final_print)
292 print_progress_n(stop_status);
293 if (stop_status == SolverStatus::Converged ||
294 stop_status == SolverStatus::Interrupted ||
295 opts.always_overwrite_results) {
296 auto &ŷ = curr->ŷx̂;
297 if (err_z.size() > 0)
298 err_z = (ŷ - y).cwiseQuotient(Σ);
299 x = curr->x̂;
300 y = curr->ŷx̂;
301 }
302 s.iterations = k;
303 s.ε = εₖ;
304 s.elapsed_time = duration_cast<nanoseconds>(time_elapsed);
305 s.status = stop_status;
306 s.final_γ = curr->γ;
307 s.final_ψ = curr->ψx̂;
308 s.final_h = curr->hx̂;
309 s.final_φγ = curr->fbe();
310 return s;
311 }
312
313 // Calculate quasi-Newton step -----------------------------------------
314
315 real_t τ_init = NaN<config_t>;
316 if (k == 0) { // Initialize L-BFGS
318 direction.initialize(problem, y, Σ, curr->γ, curr->x̂, prox->x̂,
319 prox->p, prox->grad_ψ);
320 τ_init = 0;
321 }
322 if (k > 0 || direction.has_initial_direction()) {
323 τ_init = direction.apply(curr->γ, curr->x̂, prox->x̂, prox->p,
324 prox->grad_ψ, q)
325 ? 1
326 : 0;
327 // Make sure quasi-Newton step is valid
328 if (τ_init == 1 && not q.allFinite())
329 τ_init = 0;
330 if (τ_init != 1) { // If we computed a quasi-Newton step
332 direction.reset(); // Is there anything else we can do?
333 }
334 }
335
336 // Line search ---------------------------------------------------------
337
338 next->γ = curr->γ;
339 next->L = curr->L;
340 τ = τ_init;
341 real_t τ_prev = -1;
342 bool update_lbfgs_in_linesearch = params.update_direction_in_candidate;
343 bool update_lbfgs_in_accel = params.update_direction_in_accel;
344 bool updated_lbfgs = false;
345 bool dir_rejected = true;
346
347 // xₖ₊₁ = xₖ + pₖ
348 auto take_safe_step = [&] {
349 next->x = curr->x̂; // → safe prox step
350 next->ψx = curr->ψx̂;
351 next->grad_ψ = prox->grad_ψ;
352 // TODO: could swap gradients, but need for direction update
353 };
354
355 // xₖ₊₁ = x̂ₖ + τ qₖ
356 auto take_accelerated_step = [&](real_t τ) {
357 if (τ == 1) // → faster quasi-Newton step
358 next->x = curr->x̂ + q;
359 else
360 next->x = curr->x̂ + τ * q;
361 // Calculate ψ(xₖ₊₁), ∇ψ(xₖ₊₁)
362 eval_ψ_grad_ψ(*next);
363 };
364
365 while (!stop_signal.stop_requested()) {
366
367 // Recompute step only if τ changed
368 if (τ != τ_prev) {
369 τ != 0 ? take_accelerated_step(τ) : take_safe_step();
370 τ_prev = τ;
371 }
372
373 // If the cost is not finite, or if the quadratic upper bound could
374 // not be satisfied, abandon the direction entirely, don't even
375 // bother backtracking.
376 bool fail = !std::isfinite(next->ψx);
377 fail |= next->L >= params.L_max && !(curr->L >= params.L_max);
378 if (τ > 0 && fail) {
379 // Don't allow a bad accelerated step to destroy the FBS step
380 // size
381 next->L = curr->L;
382 next->γ = curr->γ;
383 // Line search failed
384 τ = 0;
385 direction.reset();
386 // Update the direction in the FB iterate later
387 update_lbfgs_in_linesearch = false;
388 continue;
389 }
390
391 // Calculate x̂ₖ₊₁, ψ(x̂ₖ₊₁)
392 eval_prox_grad_step(*next);
393 eval_cost_in_prox(*next);
394
395 // Update L-BFGS
396 if (update_lbfgs_in_accel && !updated_lbfgs) {
397 if (τ > 0 && params.update_direction_from_prox_step) {
398 s.direction_update_rejected += dir_rejected =
399 not direction.update(curr->γ, next->γ, curr->x̂, next->x,
400 prox->p, next->p, prox->grad_ψ,
401 next->grad_ψ);
402 } else {
403 s.direction_update_rejected += dir_rejected =
404 not direction.update(curr->γ, next->γ, curr->x, next->x,
405 curr->p, next->p, curr->grad_ψ,
406 next->grad_ψ);
407 }
408 update_lbfgs_in_accel = false;
409 updated_lbfgs = true;
410 }
411
412 // Quadratic upper bound step size condition
413 if (next->L < params.L_max && qub_violated(*next)) {
414 next->γ /= 2;
415 next->L *= 2;
416 if (τ > 0)
417 τ = τ_init;
419 // If the step size changes, we need extra care when updating
420 // the direction later
421 update_lbfgs_in_linesearch = false;
422 continue;
423 }
424
425 // Update L-BFGS
426 if (update_lbfgs_in_linesearch && !updated_lbfgs) {
427 if (τ > 0 && params.update_direction_from_prox_step) {
428 s.direction_update_rejected += dir_rejected =
429 not direction.update(curr->γ, next->γ, curr->x̂, next->x,
430 prox->p, next->p, prox->grad_ψ,
431 next->grad_ψ);
432 } else {
433 s.direction_update_rejected += dir_rejected =
434 not direction.update(curr->γ, next->γ, curr->x, next->x,
435 curr->p, next->p, curr->grad_ψ,
436 next->grad_ψ);
437 }
438 update_lbfgs_in_linesearch = false;
439 updated_lbfgs = true;
440 }
441
442 // Line search condition
443 if (τ > 0 && linesearch_violated(*curr, *next)) {
444 τ /= 2;
445 if (τ < params.min_linesearch_coefficient)
446 τ = 0;
448 continue;
449 }
450
451 // QUB and line search satisfied (or τ is 0 and L > L_max)
452 break;
453 }
454 // If τ < τ_min the line search failed and we accepted the prox step
455 s.linesearch_failures += (τ == 0 && τ_init > 0);
456 s.τ_1_accepted += τ == 1;
457 s.count_τ += (τ_init > 0);
458 s.sum_τ += τ;
459
460 // Check if we made any progress
461 if (no_progress > 0 || k % params.max_no_progress == 0)
462 no_progress = curr->x == next->x ? no_progress + 1 : 0;
463
464 // Update L-BFGS -------------------------------------------------------
465
466 if (!updated_lbfgs) {
467 if (curr->γ != next->γ) { // Flush L-BFGS if γ changed
468 direction.changed_γ(next->γ, curr->γ);
469 if (params.recompute_last_prox_step_after_stepsize_change) {
470 curr->γ = next->γ;
471 curr->L = next->L;
472 eval_prox_grad_step_in_prox(*curr);
473 }
474 }
475 if (τ > 0 && params.update_direction_from_prox_step) {
476 s.direction_update_rejected += dir_rejected =
477 not direction.update(curr->γ, next->γ, curr->x̂, next->x,
478 prox->p, next->p, prox->grad_ψ,
479 next->grad_ψ);
480 } else {
481 s.direction_update_rejected += dir_rejected =
482 not direction.update(curr->γ, next->γ, curr->x, next->x,
483 curr->p, next->p, curr->grad_ψ,
484 next->grad_ψ);
485 }
486 }
487
488 // Print ---------------------------------------------------------------
489 do_progress_cb(k, *curr, q, prox->grad_ψ, τ, εₖ, SolverStatus::Busy);
490 if (do_print && (k != 0 || direction.has_initial_direction()))
491 print_progress_2(q, τ, dir_rejected);
492
493 // Advance step --------------------------------------------------------
494 std::swap(curr, next);
495 ++k;
496
497#ifndef NDEBUG
498 {
500 *prox = {n, m};
501 *next = {n, m};
502 }
503#endif
504 }
505 throw std::logic_error("[ZeroFPR] loop error");
506}
507
508} // namespace alpaqa
std::string get_name() const
Definition zerofpr.tpp:20
ZeroFPRProgressInfo< config_t > ProgressInfo
Definition zerofpr.hpp:150
std::function< void(const ProgressInfo &)> progress_cb
Definition zerofpr.hpp:200
Stats operator()(const Problem &problem, const SolveOptions &opts, rvec x, rvec y, crvec Σ, rvec err_z)
Definition zerofpr.tpp:25
InnerSolveOptions< config_t > SolveOptions
Definition zerofpr.hpp:151
ZeroFPRStats< config_t > Stats
Definition zerofpr.hpp:149
guanaqo::AtomicStopSignal stop_signal
Definition zerofpr.hpp:199
TypeErasedProblem< config_t > Problem
Definition zerofpr.hpp:146
std::ostream * os
Definition zerofpr.hpp:205
struct alpaqa::prox_fn prox
Compute the proximal mapping.
unsigned stepsize_backtracks
Definition zerofpr.hpp:97
unsigned direction_update_rejected
Definition zerofpr.hpp:99
SolverStatus
Exit status of a numerical solver such as ALM or PANOC.
@ Interrupted
Solver was interrupted by the user.
@ Converged
Converged and reached given tolerance.
@ NotFinite
Intermediate results were infinite or not-a-number.
std::chrono::nanoseconds time_progress_callback
Definition zerofpr.hpp:93
std::chrono::nanoseconds elapsed_time
Definition zerofpr.hpp:92
typename Conf::real_t real_t
Definition config.hpp:86
const rvec< Conf > null_vec
Global empty vector for convenience.
Definition config.hpp:193
constexpr const auto NaN
Definition config.hpp:114
unsigned direction_failures
Definition zerofpr.hpp:98
unsigned linesearch_backtracks
Definition zerofpr.hpp:96
typename Conf::length_t length_t
Definition config.hpp:103
typename Conf::rvec rvec
Definition config.hpp:91
typename Conf::crvec crvec
Definition config.hpp:92
unsigned linesearch_failures
Definition zerofpr.hpp:95
typename Conf::vec vec
Definition config.hpp:88
SolverStatus status
Definition zerofpr.hpp:90
static real_t initial_lipschitz_estimate(const Problem &problem, crvec x, crvec y, crvec Σ, real_t ε, real_t δ, real_t L_min, real_t L_max, real_t &ψ, rvec grad_ψ, rvec work_x, rvec work_grad_ψ, rvec work_n, rvec work_m)
static real_t calc_error_stop_crit(const Problem &problem, PANOCStopCrit crit, crvec pₖ, real_t γ, crvec xₖ, crvec x̂ₖ, crvec ŷₖ, crvec grad_ψₖ, crvec grad_̂ψₖ, rvec work_n1, rvec work_n2)
static SolverStatus check_all_stop_conditions(const ParamsT &params, const InnerSolveOptions< config_t > &opts, DurationT time_elapsed, unsigned iteration, const guanaqo::AtomicStopSignal &stop_signal, real_t εₖ, unsigned no_progress)