alpaqa matlab
Nonconvex constrained optimization
Loading...
Searching...
No Matches
pantr.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 "PANTRSolver<" + 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[3]{{n, m}, {n, m}, {n, m}};
72 Iterate *curr = &iterates[0];
73 Iterate *prox = &iterates[1];
74 Iterate *cand = &iterates[2];
75
76 bool need_grad_ψx̂ = Helpers::stop_crit_requires_grad_ψx̂(params.stop_crit);
77 vec grad_ψx̂(n);
78 vec work_n(n), work_m(m);
79 vec q(n); // (quasi-)Newton step Hₖ pₖ
80 std::chrono::nanoseconds direction_duration{};
81
82 // Problem functions -------------------------------------------------------
83
84 auto eval_ψ_grad_ψ = [&problem, &y, &Σ, &work_n, &work_m](Iterate &i) {
85 i.ψx = problem.eval_ψ_grad_ψ(i.x, y, Σ, i.grad_ψ, work_n, work_m);
86 };
87 auto eval_prox_grad_step = [&problem](Iterate &i) {
88 i.hx̂ = problem.eval_prox_grad_step(i.γ, i.x, i.grad_ψ, i.x̂, i.p);
89 i.pᵀp = i.p.squaredNorm();
90 i.grad_ψᵀp = i.p.dot(i.grad_ψ);
91 };
92 auto eval_ψx̂ = [&problem, &y, &Σ](Iterate &i) {
93 i.ψx̂ = problem.eval_ψ(i.x̂, y, Σ, i.ŷx̂);
94 };
95 auto eval_grad_ψx̂ = [&problem, &work_n](Iterate &i, rvec grad_ψx̂) {
96 problem.eval_grad_L(i.x̂, i.ŷx̂, grad_ψx̂, work_n);
97 };
98
99 // Helper functions --------------------------------------------------------
100
101 auto qub_violated = [this](const Iterate &i) {
102 real_t margin =
103 (1 + std::abs(i.ψx)) * params.quadratic_upperbound_tolerance_factor;
104 return i.ψx̂ > i.ψx + i.grad_ψᵀp + real_t(0.5) * i.L * i.pᵀp + margin;
105 };
106 auto backtrack_qub = [&](Iterate &i) {
107 while (i.L < params.L_max && qub_violated(i)) {
108 i.γ /= 2;
109 i.L *= 2;
110 // Compute x̂, p, ψ(x̂)
111 eval_prox_grad_step(i);
112 eval_ψx̂(i);
114 }
115 };
116
117 // Printing ----------------------------------------------------------------
118
119 std::array<char, 64> print_buf;
120 auto print_real = [this, &print_buf](real_t x) {
121 return float_to_str_vw(print_buf, x, params.print_precision);
122 };
123 auto print_real3 = [&print_buf](real_t x) {
124 return float_to_str_vw(print_buf, x, 3);
125 };
126
127 auto print_progress_1 = [&](unsigned k, real_t φₖ, real_t ψₖ, crvec grad_ψₖ,
129 if (k == 0)
130 *os << "┌─[PANTR]\n";
131 else
132 *os << "├─ " << std::setw(6) << k << " ──\n";
133 *os << "│ φγ = " << print_real(φₖ) //
134 << ", ψ = " << print_real(ψₖ) //
135 << ", ‖∇ψ‖ = " << print_real(grad_ψₖ.norm()) //
136 << ", ‖p‖ = " << print_real(std::sqrt(pₖᵀpₖ)) //
137 << ", γ = " << print_real(γₖ) //
138 << ", Δ = " << print_real(Δₖ) //
139 << ", ε = " << print_real(εₖ) << '\n';
140 };
141 auto print_progress_2 = [&](crvec qₖ, real_t ρₖ, bool accept,
142 std::chrono::nanoseconds direction_duration) {
143 *os << "│ ‖q‖ = " << print_real(qₖ.norm()) //
144 << ", ρ = " << print_real3(ρₖ) //
145 << ", time = "
146 << print_real3(
147 static_cast<real_t>(1e6) *
148 std::chrono::duration<real_t>(direction_duration).count())
149 << " µs, "
150 << (accept ? "\033[0;32maccepted\033[0m"
151 : "\033[0;35mrejected\033[0m") //
152 << std::endl; // Flush for Python buffering
153 };
154 auto print_progress_n = [&](SolverStatus status) {
155 *os << "└─ " << status << " ──"
156 << std::endl; // Flush for Python buffering
157 };
158 auto do_progress_cb = [this, &s, &problem, &Σ, &y,
159 &opts](unsigned k, Iterate &it, crvec q,
161 bool accepted, SolverStatus status) {
162 if (!progress_cb)
163 return;
166 progress_cb(ProgressInfo{
167 .k = k,
168 .status = status,
169 .x = it.x,
170 .p = it.p,
171 .norm_sq_p = it.pᵀp,
172 .x̂ = it.x̂,
173 .ŷ = it.ŷx̂,
174 .φγ = it.fbe(),
175 .ψ = it.ψx,
176 .grad_ψ = it.grad_ψ,
177 .ψ_hat = it.ψx̂,
178 .grad_ψ_hat = grad_ψx̂,
179 .q = q,
180 .L = it.L,
181 .γ = it.γ,
182 .Δ = Δ,
183 .ρ = ρ,
184 .τ = static_cast<real_t>(accepted),
185 .ε = εₖ,
186 .Σ = Σ,
187 .y = y,
188 .outer_iter = opts.outer_iter,
189 .problem = &problem,
190 .params = &params,
191 });
192 };
193
194 // Initialization ----------------------------------------------------------
195
196 curr->x = x;
197
198 // Estimate Lipschitz constant ---------------------------------------------
199
200 // Finite difference approximation of ∇²ψ in starting point
201 if (params.Lipschitz.L_0 <= 0) {
202 curr->L = Helpers::initial_lipschitz_estimate(
203 problem, curr->x, y, Σ, params.Lipschitz.ε, params.Lipschitz.δ,
204 params.L_min, params.L_max,
205 /* in ⟹ out */ curr->ψx, curr->grad_ψ, curr->x̂, cand->grad_ψ,
206 work_n, work_m);
207 }
208 // Initial Lipschitz constant provided by the user
209 else {
210 curr->L = params.Lipschitz.L_0;
211 // Calculate ψ(xₖ), ∇ψ(x₀)
212 eval_ψ_grad_ψ(*curr);
213 }
214 if (not std::isfinite(curr->L)) {
216 return s;
217 }
218 curr->γ = params.Lipschitz.Lγ_factor / curr->L;
219
220 // First proximal gradient step --------------------------------------------
221
222 eval_prox_grad_step(*curr);
225
226 // Loop data ---------------------------------------------------------------
227
228 unsigned k = 0; // iteration
229 bool accept_candidate = false;
230 // Keep track of how many successive iterations didn't update the iterate
231 unsigned no_progress = 0;
232 // Trust radius
233 real_t Δ = params.initial_radius;
234 if (!std::isfinite(Δ) || Δ == 0)
235 Δ = real_t(0.1) * curr->grad_ψ.norm();
236 Δ = std::fmax(Δ, params.min_radius);
237 // Reduction ratio
239
240 // Main PANTR loop
241 // =========================================================================
242
243 ScopedMallocBlocker mb; // Don't allocate in the inner loop
244 while (true) {
245
246 // Check stopping criteria ---------------------------------------------
247
248 // Calculate ∇ψ(x̂ₖ)
249 if (need_grad_ψx̂)
252
253 real_t εₖ = Helpers::calc_error_stop_crit(
254 problem, params.stop_crit, curr->p, curr->γ, curr->x, curr->x̂,
255 curr->ŷx̂, curr->grad_ψ, grad_ψx̂, work_n, cand->p);
256
257 // Print progress ------------------------------------------------------
258
259 bool do_print =
260 params.print_interval != 0 && k % params.print_interval == 0;
261 if (do_print)
262 print_progress_1(k, curr->fbe(), curr->ψx, curr->grad_ψ, curr->pᵀp,
263 curr->γ, εₖ, Δ);
264
265 // Return solution -----------------------------------------------------
266
267 auto time_elapsed = std::chrono::steady_clock::now() - start_time;
268 auto stop_status = Helpers::check_all_stop_conditions(
269 params, opts, time_elapsed, k, stop_signal, εₖ, no_progress);
273 bool do_final_print = params.print_interval != 0;
274 if (!do_print && do_final_print)
275 print_progress_1(k, curr->fbe(), curr->ψx, curr->grad_ψ,
276 curr->pᵀp, curr->γ, εₖ, Δ);
279 // Overwrite output arguments
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 // Save statistics
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 // Perform FBS step ----------------------------------------------------
302
303 // x̂ₖ = xₖ + pₖ
304 auto compute_FBS_step = [&] {
305 assert(curr->L >= params.L_max || !qub_violated(*curr));
306 // Calculate ∇ψ(x̂ₖ)
309 have_grad_ψx̂ = true;
310 prox->x = curr->x̂;
311 prox->ψx = curr->ψx̂;
312 prox->grad_ψ.swap(grad_ψx̂);
313 prox->γ = curr->γ;
314 prox->L = curr->L;
315 eval_ψ_grad_ψ(*prox);
316 eval_prox_grad_step(*prox);
317 };
318
319 // store x̂ₖ in prox->x
321
322 // Initialize direction
323 if (k == 0) {
325 direction.initialize(problem, y, Σ, prox->γ, prox->x, prox->x̂,
326 prox->p, prox->grad_ψ);
327 }
328
329 // Check if x̂ₖ + q provides sufficient decrease
330 auto compute_candidate_fbe = [&](crvec q) {
331 // Candidate step xₖ₊₁ = x̂ₖ + q
332 cand->x = prox->x + q;
333 // Compute ψ(xₖ₊₁), ∇ψ(xₖ₊₁)
334 eval_ψ_grad_ψ(*cand);
335 cand->γ = prox->γ;
336 cand->L = prox->L;
337 // Compute x̂ₖ₊₁, pₖ₊₁, ψ(x̂ₖ₊₁)
338 eval_prox_grad_step(*cand);
339
340 // Quadratic upper bound in candidate point
341 if (params.compute_ratio_using_new_stepsize) {
344 }
345 };
346
347 // Check ratio ρ
349 real_t ϕγ = prox->fbe();
350 real_t ϕγ_next = cand->fbe();
351 real_t margin = (1 + std::abs(ϕγ)) * params.TR_tolerance_factor;
352 real_t ρ = (ϕγ - ϕγ_next + margin) / (-q_model);
353 return params.ratio_approx_fbe_quadratic_model
354 ? ρ / (1 - params.Lipschitz.Lγ_factor)
355 : ρ;
356 };
357
358 // update trust radius accordingly
359 auto compute_updated_radius = [this](crvec q, real_t ρ, real_t old_Δ) {
360 // Very successful TR step
361 if (ρ >= params.ratio_threshold_good)
362 return std::max(params.radius_factor_good * q.norm(), old_Δ);
363 // Successful TR step
364 else if (ρ >= params.ratio_threshold_acceptable)
365 return old_Δ * params.radius_factor_acceptable;
366 // Unsuccessful TR step
367 else
368 return params.radius_factor_rejected * q.norm();
369 };
370
371 // Compute trust region direction from x̂ₖ
372 auto compute_trust_region_step = [&](rvec q, real_t Δ) {
373 auto t0 = std::chrono::steady_clock::now();
374 real_t q_model = direction.apply(prox->γ, prox->x, prox->x̂, prox->p,
375 prox->grad_ψ, Δ, q);
376 auto t1 = std::chrono::steady_clock::now();
378
379 // Check if step is valid
380 if (not q.allFinite()) {
381 *os << "Direction fail: not finite" << std::endl;
383 direction.reset();
384 return +inf<config_t>;
385 }
386 if (q_model >= 0) {
387 *os << "Direction fail: no decrease on model (" << q_model
388 << ')' << std::endl;
390 direction.reset(); // Is there anything else we can do?
391 }
392 return q_model;
393 };
394
395 // Solve TR subproblem and update radius
396 accept_candidate = false;
397 bool accelerated_iteration = k > 0 || direction.has_initial_direction();
398 if (accelerated_iteration && !params.disable_acceleration) {
399 if (auto q_model = compute_trust_region_step(q, Δ); q_model < 0) {
402 accept_candidate = ρ >= params.ratio_threshold_acceptable;
403 Δ = std::fmax(compute_updated_radius(q, ρ, Δ),
404 params.min_radius);
405 }
406 }
407
408 // Progress callback
411
412 // Accept TR step
413 if (accept_candidate) {
414 // Quadratic upper bound in next iterate
415 if (!params.compute_ratio_using_new_stepsize) {
418 }
419 // Flush L-BFGS if γ changed
420 if (prox->γ != cand->γ) {
421 direction.changed_γ(cand->γ, prox->γ);
422 if (params.recompute_last_prox_step_after_direction_reset) {
423 std::tie(prox->γ, prox->L) = std::tie(cand->γ, cand->L);
424 eval_prox_grad_step(*prox);
425 }
426 }
427 // update L-BFGS
428 s.direction_update_rejected += not direction.update(
429 prox->γ, cand->γ, prox->x, cand->x, prox->p, cand->p,
430 prox->grad_ψ, cand->grad_ψ);
431
432 if (do_print)
434 // Candidate becomes new iterate
435 std::swap(curr, cand);
436 }
437 // Fall back to proximal gradient step
438 else {
441 // Quadratic upper bound in x̂ₖ
444 if (prox->γ != curr->γ) {
445 direction.changed_γ(prox->γ, curr->γ);
446 if (params.recompute_last_prox_step_after_direction_reset) {
447 std::tie(curr->γ, curr->L) = std::tie(prox->γ, prox->L);
448 eval_prox_grad_step(*curr);
449 }
450 }
451 // update direction
452 if (params.update_direction_on_prox_step)
453 s.direction_update_rejected += not direction.update(
454 curr->γ, prox->γ, curr->x, prox->x, curr->p, prox->p,
455 curr->grad_ψ, prox->grad_ψ);
458 // x̂ₖ becomes new iterate
459 std::swap(curr, prox);
460 }
461
462#ifndef NDEBUG
463 { // Make sure that we don't rely on any data from previous iterations,
464 // reset to NaN:
466 *prox = {n, m};
467 *cand = {n, m};
468 }
469#endif
470
471 // Advance step --------------------------------------------------------
472 ++k;
473 }
474 throw std::logic_error("[PANTR] loop error");
475}
476
477} // namespace alpaqa
std::string get_name() const
Definition pantr.tpp:20
Stats operator()(const Problem &problem, const SolveOptions &opts, rvec x, rvec y, crvec Σ, rvec err_z)
Definition pantr.tpp:25
struct alpaqa::prox_fn prox
Compute the proximal mapping.
unsigned stepsize_backtracks
Definition pantr.hpp:108
unsigned direction_update_rejected
Definition pantr.hpp:110
unsigned accelerated_step_rejected
Definition pantr.hpp:107
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 pantr.hpp:105
std::chrono::nanoseconds elapsed_time
Definition pantr.hpp:104
typename Conf::real_t real_t
Definition config.hpp:65
unsigned direction_failures
Definition pantr.hpp:109
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
typename Conf::vec vec
Definition config.hpp:66
unsigned iterations
Definition pantr.hpp:106
SolverStatus status
Definition pantr.hpp:102