alpaqa pantr
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
16#include <alpaqa/util/timed.hpp>
17
18namespace alpaqa {
19
20template <class DirectionProviderT>
22 return "PANTRSolver<" + std::string(direction.get_name()) + ">";
23}
24
25template <class DirectionProviderT>
27 /// [in] Problem description
28 const Problem &problem,
29 /// [in] Solve options
30 const SolveOptions &opts,
31 /// [inout] Decision variable @f$ x @f$
32 rvec x,
33 /// [inout] Lagrange multipliers @f$ y @f$
34 rvec y,
35 /// [in] Constraint weights @f$ \Sigma @f$
36 crvec Σ,
37 /// [out] Slack variable error @f$ g(x) - \Pi_D(g(x) + \Sigma^{-1} y) @f$
38 rvec err_z) -> Stats {
39
40 if (opts.check)
41 problem.check();
42
43 using std::chrono::nanoseconds;
44 auto os = opts.os ? opts.os : this->os;
45 auto start_time = std::chrono::steady_clock::now();
46 Stats s;
47
48 const auto n = problem.get_n();
49 const auto m = problem.get_m();
50
51 // Represents an iterate in the algorithm, keeping track of some
52 // intermediate values and function evaluations.
53 struct Iterate {
54 vec x; //< Decision variables
55 vec x̂; //< Decision variables after proximal gradient step
56 vec grad_ψ; //< 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
67 // @pre @ref ψx, @ref hx̂ @ref pᵀp, @ref grad_ψᵀp
68 // @return φγ
69 real_t fbe() const { return ψx + hx̂ + pᵀp / (2 * γ) + grad_ψᵀp; }
70
71 Iterate(length_t n, length_t m) : x(n), x̂(n), grad_ψ(n), p(n), ŷx̂(m) {}
72 } iterates[3]{{n, m}, {n, m}, {n, m}};
73 Iterate *curr = &iterates[0];
74 Iterate *prox = &iterates[1];
75 Iterate *cand = &iterates[2];
76
77 bool need_grad_ψx̂ = Helpers::stop_crit_requires_grad_ψx̂(params.stop_crit);
78 vec grad_ψx̂(n);
79 vec work_n(n), work_m(m);
80 vec q(n); // (quasi-)Newton step Hₖ pₖ
81 std::chrono::nanoseconds direction_duration{};
82
83 // Problem functions -------------------------------------------------------
84
85 auto eval_ψ_grad_ψ = [&problem, &y, &Σ, &work_n, &work_m](Iterate &i) {
86 i.ψx = problem.eval_ψ_grad_ψ(i.x, y, Σ, i.grad_ψ, work_n, work_m);
87 };
88 auto eval_prox_grad_step = [&problem](Iterate &i) {
89 i.hx̂ = problem.eval_prox_grad_step(i.γ, i.x, i.grad_ψ, i.x̂, i.p);
90 i.pᵀp = i.p.squaredNorm();
91 i.grad_ψᵀp = i.p.dot(i.grad_ψ);
92 };
93 auto eval_ψx̂ = [&problem, &y, &Σ](Iterate &i) {
94 i.ψx̂ = problem.eval_ψ(i.x̂, y, Σ, i.ŷx̂);
95 };
96 auto eval_grad_ψx̂ = [&problem, &work_n](Iterate &i, rvec grad_ψx̂) {
97 problem.eval_grad_L(i.x̂, i.ŷx̂, grad_ψx̂, work_n);
98 };
99
100 // Helper functions --------------------------------------------------------
101
102 auto qub_violated = [this](const Iterate &i) {
103 real_t margin =
104 (1 + std::abs(i.ψx)) * params.quadratic_upperbound_tolerance_factor;
105 return i.ψx̂ > i.ψx + i.grad_ψᵀp + real_t(0.5) * i.L * i.pᵀp + margin;
106 };
107 auto backtrack_qub = [&](Iterate &i) {
108 while (i.L < params.L_max && qub_violated(i)) {
109 i.γ /= 2;
110 i.L *= 2;
111 // Compute x̂, p, ψ(x̂)
112 eval_prox_grad_step(i);
113 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_ψₖ,
128 real_t pₖᵀpₖ, real_t γₖ, real_t εₖ, real_t Δₖ) {
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,
160 crvec grad_ψx̂, real_t Δ, real_t ρ, real_t εₖ,
161 SolverStatus status) {
162 using enum SolverStatus;
163 if (!progress_cb)
164 return;
167 progress_cb(ProgressInfo{
168 .k = k,
169 .status = status,
170 .x = it.x,
171 .p = it.p,
172 .norm_sq_p = it.pᵀp,
173 .x̂ = 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 .ε = εₖ,
185 .Σ = Σ,
186 .y = y,
187 .outer_iter = opts.outer_iter,
188 .problem = &problem,
189 .params = &params,
190 });
191 };
192
193 // Initialization ----------------------------------------------------------
194
195 curr->x = x;
196
197 // Estimate Lipschitz constant ---------------------------------------------
198
199 // Finite difference approximation of ∇²ψ in starting point
200 if (params.Lipschitz.L_0 <= 0) {
201 curr->L = Helpers::initial_lipschitz_estimate(
202 problem, curr->x, y, Σ, params.Lipschitz.ε, params.Lipschitz.δ,
203 params.L_min, params.L_max,
204 /* in ⟹ out */ curr->ψx, curr->grad_ψ, curr->x̂, cand->grad_ψ,
205 work_n, work_m);
206 }
207 // Initial Lipschitz constant provided by the user
208 else {
209 curr->L = params.Lipschitz.L_0;
210 // Calculate ψ(xₖ), ∇ψ(x₀)
211 eval_ψ_grad_ψ(*curr);
212 }
213 if (not std::isfinite(curr->L)) {
215 return s;
216 }
217 curr->γ = params.Lipschitz.Lγ_factor / curr->L;
218
219 // First proximal gradient step --------------------------------------------
220
221 eval_prox_grad_step(*curr);
222 eval_ψx̂(*curr);
223 backtrack_qub(*curr);
224
225 // Loop data ---------------------------------------------------------------
226
227 unsigned k = 0; // iteration
228 bool accept_candidate = false;
229 // Keep track of how many successive iterations didn't update the iterate
230 unsigned no_progress = 0;
231 // Trust radius
232 real_t Δ = params.initial_radius;
233 if (!std::isfinite(Δ) || Δ == 0)
234 Δ = real_t(0.1) * curr->grad_ψ.norm();
235 Δ = std::fmax(Δ, params.min_radius);
236 // Reduction ratio
237 real_t ρ = NaN<config_t>;
238
239 // Main PANTR loop
240 // =========================================================================
241
242 ScopedMallocBlocker mb; // Don't allocate in the inner loop
243 while (true) {
244
245 // Check stopping criteria ---------------------------------------------
246
247 // Calculate ∇ψ(x̂ₖ)
248 if (need_grad_ψx̂)
249 eval_grad_ψx̂(*curr, grad_ψx̂);
250 bool have_grad_ψx̂ = need_grad_ψx̂;
251
252 real_t εₖ = Helpers::calc_error_stop_crit(
253 problem, params.stop_crit, curr->p, curr->γ, curr->x, curr->x̂,
254 curr->ŷx̂, curr->grad_ψ, grad_ψx̂, work_n, cand->p);
255
256 // Print progress ------------------------------------------------------
257
258 bool do_print =
259 params.print_interval != 0 && k % params.print_interval == 0;
260 if (do_print)
261 print_progress_1(k, curr->fbe(), curr->ψx, curr->grad_ψ, curr->pᵀp,
262 curr->γ, εₖ, Δ);
263
264 // Return solution -----------------------------------------------------
265
266 auto time_elapsed = std::chrono::steady_clock::now() - start_time;
267 auto stop_status = Helpers::check_all_stop_conditions(
268 params, opts, time_elapsed, k, stop_signal, εₖ, no_progress);
269 if (stop_status != SolverStatus::Busy) {
270 do_progress_cb(k, *curr, null_vec<config_t>, grad_ψx̂, NaN<config_t>,
271 NaN<config_t>, εₖ, stop_status);
272 bool do_final_print = params.print_interval != 0;
273 if (!do_print && do_final_print)
274 print_progress_1(k, curr->fbe(), curr->ψx, curr->grad_ψ,
275 curr->pᵀp, curr->γ, εₖ, Δ);
276 if (do_print || do_final_print)
277 print_progress_n(stop_status);
278 // Overwrite output arguments
279 if (stop_status == SolverStatus::Converged ||
280 stop_status == SolverStatus::Interrupted ||
281 opts.always_overwrite_results) {
282 auto &ŷ = curr->ŷx̂;
283 if (err_z.size() > 0)
284 err_z = Σ.asDiagonal().inverse() * (ŷ - y);
285 x = std::move(curr->x̂);
286 y = std::move(curr->ŷx̂);
287 }
288 // Save statistics
289 s.iterations = k;
290 s.ε = εₖ;
291 s.elapsed_time = duration_cast<nanoseconds>(time_elapsed);
292 s.status = stop_status;
293 s.final_γ = curr->γ;
294 s.final_ψ = curr->ψx̂;
295 s.final_h = curr->hx̂;
296 s.final_φγ = curr->fbe();
297 return s;
298 }
299
300 // Perform FBS step ----------------------------------------------------
301
302 // x̂ₖ = xₖ + pₖ
303 auto compute_FBS_step = [&] {
304 assert(curr->L >= params.L_max || !qub_violated(*curr));
305 // Calculate ∇ψ(x̂ₖ)
306 if (not have_grad_ψx̂)
307 eval_grad_ψx̂(*curr, grad_ψx̂);
308 have_grad_ψx̂ = true;
309 prox->x = curr->x̂;
310 prox->ψx = curr->ψx̂;
311 prox->grad_ψ.swap(grad_ψx̂);
312 prox->γ = curr->γ;
313 prox->L = curr->L;
314 eval_ψ_grad_ψ(*prox);
315 eval_prox_grad_step(*prox);
316 };
317
318 // store x̂ₖ in prox->x
319 compute_FBS_step();
320
321 // Initialize direction
322 if (k == 0) {
324 direction.initialize(problem, y, Σ, prox->γ, prox->x, prox->x̂,
325 prox->p, prox->grad_ψ);
326 }
327
328 // Check if x̂ₖ + q provides sufficient decrease
329 auto compute_candidate_fbe = [&](crvec q) {
330 // Candidate step xₖ₊₁ = x̂ₖ + q
331 cand->x = prox->x + q;
332 // Compute ψ(xₖ₊₁), ∇ψ(xₖ₊₁)
333 eval_ψ_grad_ψ(*cand);
334 cand->γ = prox->γ;
335 cand->L = prox->L;
336 // Compute x̂ₖ₊₁, pₖ₊₁, ψ(x̂ₖ₊₁)
337 eval_prox_grad_step(*cand);
338
339 // Quadratic upper bound in candidate point
340 if (params.compute_ratio_using_new_stepsize) {
341 eval_ψx̂(*cand);
342 backtrack_qub(*cand);
343 }
344 };
345
346 // Check ratio ρ
347 auto compute_candidate_ratio = [this, prox, cand](real_t q_model) {
348 real_t ϕγ = prox->fbe();
349 real_t ϕγ_next = cand->fbe();
350 real_t margin = (1 + std::abs(ϕγ)) * params.TR_tolerance_factor;
351 return (ϕγ - ϕγ_next + margin) / (-q_model);
352 };
353
354 // update trust radius accordingly
355 auto compute_updated_radius = [this](crvec q, real_t ρ, real_t old_Δ) {
356 // Very successful TR step
357 if (ρ >= params.ratio_threshold_good)
358 return std::max(params.radius_factor_good * q.norm(), old_Δ);
359 // Successful TR step
360 else if (ρ >= params.ratio_threshold_acceptable)
361 return old_Δ * params.radius_factor_acceptable;
362 // Unsuccessful TR step
363 else
364 return params.radius_factor_rejected * q.norm();
365 };
366
367 // Compute trust region direction from x̂ₖ
368 auto compute_trust_region_step = [&](rvec q, real_t Δ) {
369 auto t0 = std::chrono::steady_clock::now();
370 real_t q_model = direction.apply(prox->γ, prox->x, prox->x̂, prox->p,
371 prox->grad_ψ, Δ, q);
372 auto t1 = std::chrono::steady_clock::now();
373 direction_duration = t1 - t0;
374
375 // Check if step is valid
376 if (not q.allFinite()) {
377 *os << "Direction fail: not finite" << std::endl;
379 direction.reset();
380 return +inf<config_t>;
381 }
382 if (q_model >= 0) {
383 *os << "Direction fail: no decrease on model (" << q_model
384 << ')' << std::endl;
386 direction.reset(); // Is there anything else we can do?
387 }
388 return q_model;
389 };
390
391 // Solve TR subproblem and update radius
392 accept_candidate = false;
393 bool accelerated_iteration = k > 0 || direction.has_initial_direction();
394 if (accelerated_iteration && !params.disable_acceleration) {
395 if (auto q_model = compute_trust_region_step(q, Δ); q_model < 0) {
396 compute_candidate_fbe(q);
397 ρ = compute_candidate_ratio(q_model);
398 accept_candidate = ρ >= params.ratio_threshold_acceptable;
399 Δ = std::fmax(compute_updated_radius(q, ρ, Δ),
400 params.min_radius);
401 }
402 }
403
404 // Progress callback
405 do_progress_cb(k, *curr, q, grad_ψx̂, Δ, ρ, εₖ, SolverStatus::Busy);
406
407 // Accept TR step
408 if (accept_candidate) {
409 // Quadratic upper bound in next iterate
410 if (!params.compute_ratio_using_new_stepsize) {
411 eval_ψx̂(*cand);
412 backtrack_qub(*cand);
413 }
414 // Flush L-BFGS if γ changed
415 if (prox->γ != cand->γ) {
416 direction.changed_γ(cand->γ, prox->γ);
417 if (params.recompute_last_prox_step_after_direction_reset) {
418 std::tie(prox->γ, prox->L) = std::tie(cand->γ, cand->L);
419 eval_prox_grad_step(*prox);
420 }
421 }
422 // update L-BFGS
423 s.direction_update_rejected += not direction.update(
424 prox->γ, cand->γ, prox->x, cand->x, prox->p, cand->p,
425 prox->grad_ψ, cand->grad_ψ);
426
427 if (do_print)
428 print_progress_2(q, ρ, true, direction_duration);
429 // Candidate becomes new iterate
430 std::swap(curr, cand);
431 }
432 // Fall back to proximal gradient step
433 else {
434 if (accelerated_iteration)
436 // Quadratic upper bound in x̂ₖ
437 eval_ψx̂(*prox);
438 backtrack_qub(*prox);
439 if (prox->γ != curr->γ) {
440 direction.changed_γ(prox->γ, curr->γ);
441 if (params.recompute_last_prox_step_after_direction_reset) {
442 std::tie(curr->γ, curr->L) = std::tie(prox->γ, prox->L);
443 eval_prox_grad_step(*curr);
444 }
445 }
446 // update direction
447 if (params.update_direction_on_prox_step)
448 s.direction_update_rejected += not direction.update(
449 curr->γ, prox->γ, curr->x, prox->x, curr->p, prox->p,
450 curr->grad_ψ, prox->grad_ψ);
451 if (do_print && accelerated_iteration)
452 print_progress_2(q, ρ, false, direction_duration);
453 // x̂ₖ becomes new iterate
454 std::swap(curr, prox);
455 }
456
457#ifndef NDEBUG
458 { // Make sure that we don't rely on any data from previous iterations,
459 // reset to NaN:
461 *prox = {n, m};
462 *cand = {n, m};
463 }
464#endif
465
466 // Advance step --------------------------------------------------------
467 ++k;
468 }
469 throw std::logic_error("[PANTR] loop error");
470}
471
472} // namespace alpaqa
std::string get_name() const
Definition: pantr.tpp:21
Stats operator()(const Problem &problem, const SolveOptions &opts, rvec x, rvec y, crvec Σ, rvec err_z)
Definition: pantr.tpp:26
unsigned direction_update_rejected
Definition: pantr.hpp:89
real_t final_φγ
Definition: pantr.hpp:93
unsigned accelerated_step_rejected
Definition: pantr.hpp:86
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:84
std::chrono::nanoseconds elapsed_time
Definition: pantr.hpp:83
typename Conf::real_t real_t
Definition: config.hpp:51
unsigned direction_failures
Definition: pantr.hpp:88
real_t final_ψ
Definition: pantr.hpp:91
real_t final_h
Definition: pantr.hpp:92
typename Conf::length_t length_t
Definition: config.hpp:62
typename Conf::rvec rvec
Definition: config.hpp:55
std::string_view float_to_str_vw(auto &buf, double value, int precision=std::numeric_limits< double >::max_digits10)
Definition: print.tpp:38
typename Conf::crvec crvec
Definition: config.hpp:56
typename Conf::vec vec
Definition: config.hpp:52
real_t final_γ
Definition: pantr.hpp:90
unsigned iterations
Definition: pantr.hpp:85
SolverStatus status
Definition: pantr.hpp:81