alpaqa 1.0.0a8
Nonconvex constrained optimization
Loading...
Searching...
No Matches
alm.tpp
Go to the documentation of this file.
1#pragma once
2
4
5#include <algorithm>
6#include <iomanip>
7#include <iostream>
8#include <utility>
9
16
17namespace alpaqa {
18
19template <class InnerSolverT>
20typename ALMSolver<InnerSolverT>::Stats
22 using std::chrono::duration_cast;
23 using std::chrono::nanoseconds;
24 auto start_time = std::chrono::steady_clock::now();
25
26 // Check the problem dimensions etc.
27 p.check();
28
29 auto m = p.get_m();
30 if (m == 0) { // No general constraints, only box constraints
31 Stats s;
32 vec Σ(0), error(0);
35 .max_time = params.max_time,
36 .tolerance = params.tolerance,
37 .os = os,
38 .check = false,
39 };
40 auto ps = inner_solver(p, opts, x, y, Σ, error);
41 bool inner_converged = ps.status == SolverStatus::Converged;
42 auto time_elapsed = std::chrono::steady_clock::now() - start_time;
43 s.inner_convergence_failures = not inner_converged;
44 s.inner += ps;
45 s.ε = ps.ε;
46 s.δ = 0;
47 s.norm_penalty = 0;
48 s.outer_iterations = 1;
49 s.elapsed_time = duration_cast<nanoseconds>(time_elapsed);
50 s.status = ps.status;
51 return s;
52 }
53
54 constexpr auto NaN = alpaqa::NaN<config_t>;
55 vec Σ = vec::Constant(m, NaN);
56 vec Σ_old = vec::Constant(m, NaN);
57 vec error_1 = vec::Constant(m, NaN);
58 vec error_2 = vec::Constant(m, NaN);
59 [[maybe_unused]] real_t norm_e_1 = NaN;
60 [[maybe_unused]] real_t norm_e_2 = NaN;
61
62 std::array<char, 64> printbuf;
63 auto print_real = [&](real_t x) {
64 return float_to_str_vw(printbuf, x, params.print_precision);
65 };
66
67 Stats s;
68
69 // Initialize the penalty weights
70 if (params.initial_penalty > 0) {
71 Σ.fill(params.initial_penalty);
72 }
73 // Initial penalty weights from problem
74 else {
75 Helpers::initialize_penalty(p, params, x, Σ);
76 }
77
78 real_t ε = params.initial_tolerance;
79 [[maybe_unused]] real_t ε_old = NaN;
80 real_t Δ = params.penalty_update_factor;
81 real_t ρ = params.tolerance_update_factor;
82
83 unsigned num_successful_iters = 0;
84
85 for (unsigned i = 0; i < params.max_iter; ++i) {
86 // TODO: this is unnecessary when the previous iteration lowered the
87 // penalty update factor.
88 p.eval_proj_multipliers(y, params.max_multiplier);
89 // Check if we're allowed to lower the penalty factor even further.
90 bool out_of_penalty_factor_updates =
91 (num_successful_iters == 0
92 ? s.initial_penalty_reduced == params.max_num_initial_retries
93 : s.penalty_reduced == params.max_num_retries) ||
95 params.max_total_num_retries);
96 bool out_of_iter = i + 1 == params.max_iter;
97 // If this is the final iteration, or the final chance to reduce the
98 // penalty update factor, the inner solver can just return its results,
99 // even if it doesn't converge.
100 bool overwrite_results = out_of_iter || out_of_penalty_factor_updates;
101
102 // Inner solver
103 // ------------
104
105 auto time_elapsed = std::chrono::steady_clock::now() - start_time;
107 .always_overwrite_results = overwrite_results,
108 .max_time = params.max_time - time_elapsed,
109 .tolerance = ε,
110 .os = os,
111 .outer_iter = i,
112 .check = false,
113 };
114 // Call the inner solver to minimize the augmented lagrangian for fixed
115 // Lagrange multipliers y.
116 auto ps = inner_solver(p, opts, x, y, Σ, error_2);
117 // Check if the inner solver converged
118 bool inner_converged = ps.status == SolverStatus::Converged;
119 // Accumulate the inner solver statistics
120 s.inner_convergence_failures += not inner_converged;
121 s.inner += ps;
122
123 time_elapsed = std::chrono::steady_clock::now() - start_time;
124 bool out_of_time = time_elapsed > params.max_time;
125 bool backtrack =
126 not inner_converged && not overwrite_results && not out_of_time;
127
128 // Print statistics of current iteration
129 if (params.print_interval != 0 && i % params.print_interval == 0) {
130 real_t δ = backtrack ? NaN : vec_util::norm_inf(error_2);
131 const char *color = inner_converged ? "\x1b[0;32m" : "\x1b[0;31m";
132 const char *color_end = "\x1b[0m";
133 *os << "[\x1b[0;34mALM\x1b[0m] " << std::setw(5) << i
134 << ": ‖Σ‖ = " << print_real(Σ.norm())
135 << ", ‖y‖ = " << print_real(y.norm())
136 << ", δ = " << print_real(δ) << ", ε = " << print_real(ps.ε)
137 << ", Δ = " << print_real(Δ) << ", status = " << color
138 << std::setw(13) << ps.status << color_end
139 << ", iter = " << std::setw(13) << ps.iterations
140 << std::endl; // Flush for Python buffering
141 }
142
143 // TODO: check penalty size?
144 if (ps.status == SolverStatus::Interrupted) {
145 s.ε = ps.ε;
146 s.δ = vec_util::norm_inf(error_2);
147 s.norm_penalty = Σ.norm();
148 s.outer_iterations = i + 1;
149 s.elapsed_time = duration_cast<nanoseconds>(time_elapsed);
150 s.status = ps.status;
151 return s;
152 }
153
154 // Backtrack and lower penalty if inner solver did not converge
155 if (backtrack) {
156 // This means the inner solver didn't produce a solution that
157 // satisfies the required tolerance.
158 // The best thing we can do now is to restore the penalty to its
159 // previous value (when the inner solver did converge), then lower
160 // the penalty update factor Δ, and update the penalty with this
161 // smaller factor.
162 // On convergence failure, error_2 is not overwritten by the inner
163 // solver, so it still contains the error from the iteration before
164 // the previous successful iteration. error_1 contains the error of
165 // the last successful iteration. (Unless, of course, there hasn't
166 // been a successful iteration yet, which is covered by the second
167 // branch of the following if statement.)
168 if (num_successful_iters > 0) {
169 // We have a previous Σ and error
170 // Recompute penalty with smaller Δ
171 Δ = std::fmax(params.min_penalty_update_factor,
172 Δ * params.penalty_update_factor_lower);
173 Helpers::update_penalty_weights(params, Δ, false, error_1,
174 error_2, norm_e_1, norm_e_2,
175 Σ_old, Σ, true);
176 // Recompute the primal tolerance with larger ρ
177 ρ = std::fmin(params.ρ_max, ρ * params.ρ_increase);
178 ε = std::fmax(ρ * ε_old, params.tolerance);
179 ++s.penalty_reduced;
180 } else {
181 // We don't have a previous Σ, simply lower the current Σ and
182 // increase ε
183 Σ *= params.initial_penalty_lower;
184 ε *= params.initial_tolerance_increase;
186 }
187 }
188
189 // If the inner solver did converge, increase penalty
190 else {
191 // After this line, error_1 contains the error of the current
192 // (successful) iteration, and error_2 contains the error of the
193 // previous successful iteration.
194 error_2.swap(error_1);
195 norm_e_2 = std::exchange(norm_e_1, vec_util::norm_inf(error_1));
196
197 // Check the termination criteria
198 bool alm_converged = ps.ε <= params.tolerance && inner_converged &&
199 norm_e_1 <= params.dual_tolerance;
200 bool exit = alm_converged || out_of_iter || out_of_time;
201 if (exit) {
202 s.ε = ps.ε;
203 s.δ = norm_e_1;
204 s.norm_penalty = Σ.norm();
205 s.outer_iterations = i + 1;
206 s.elapsed_time = duration_cast<nanoseconds>(time_elapsed);
207 s.status = alm_converged ? SolverStatus::Converged
208 : out_of_time ? SolverStatus::MaxTime
209 : out_of_iter ? SolverStatus::MaxIter
211 return s;
212 }
213 // After this line, Σ_old contains the penalty used in the current
214 // (successful) iteration.
215 Σ_old.swap(Σ);
216 // Update Σ to contain the penalty to use on the next iteration.
217 Helpers::update_penalty_weights(
218 params, Δ, num_successful_iters == 0, error_1, error_2,
219 norm_e_1, norm_e_2, Σ_old, Σ, true);
220 // Lower the primal tolerance for the inner solver.
221 ε_old = std::exchange(ε, std::fmax(ρ * ε, params.tolerance));
222 ++num_successful_iters;
223 }
224 }
225 throw std::logic_error("[ALM] loop error");
226}
227
228} // namespace alpaqa
unsigned penalty_reduced
The number of times that the penalty update factor ALMParams::penalty_update_factor was reduced,...
Definition: alm.hpp:127
real_t δ
Final dual tolerance or constraint violation that was reached:
Definition: alm.hpp:138
real_t norm_penalty
2-norm of the final penalty factors .
Definition: alm.hpp:140
typename InnerSolver::Problem Problem
Definition: alm.hpp:102
std::chrono::nanoseconds elapsed_time
Total elapsed time.
Definition: alm.hpp:109
unsigned initial_penalty_reduced
The number of times that the initial penalty factor was reduced by ALMParams::initial_penalty_lower a...
Definition: alm.hpp:117
Stats operator()(const Problem &problem, rvec x, rvec y)
Definition: alm.tpp:21
InnerStatsAccumulator< typename InnerSolver::Stats > inner
The statistics of the inner solver invocations, accumulated over all ALM iterations.
Definition: alm.hpp:148
unsigned inner_convergence_failures
The total number of times that the inner solver failed to converge.
Definition: alm.hpp:129
real_t ε
Final primal tolerance that was reached, depends on the stopping criterion used by the inner solver,...
Definition: alm.hpp:133
unsigned outer_iterations
Total number of outer ALM iterations (i.e.
Definition: alm.hpp:107
SolverStatus status
Whether the solver converged or not.
Definition: alm.hpp:144
auto norm_inf(const Eigen::MatrixBase< Derived > &v)
Get the maximum or infinity-norm of the given vector.
Definition: config.hpp:151
@ Interrupted
Solver was interrupted by the user.
@ MaxTime
Maximum allowed execution time exceeded.
@ MaxIter
Maximum number of iterations exceeded.
@ Busy
In progress.
@ Converged
Converged and reached given tolerance.
typename Conf::real_t real_t
Definition: config.hpp:51
bool always_overwrite_results
Return the final iterate and multipliers, even if the solver did not converge.
constexpr const auto NaN
Definition: config.hpp:71
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:39
typename Conf::vec vec
Definition: config.hpp:52