alpaqa 1.0.0a13
Nonconvex constrained optimization
Loading...
Searching...
No Matches
params.cpp
Go to the documentation of this file.
11#include <alpaqa/outer/alm.hpp>
13#if ALPAQA_WITH_OCP
15#endif
16
18
19#include <fstream>
20
21#include "from_chars-compat.ipp"
22
23namespace alpaqa::params {
24
25template <>
28 if (s.value == "0" || s.value == "false")
29 b = false;
30 else if (s.value == "1" || s.value == "true")
31 b = true;
32 else
33 throw std::invalid_argument(
34 "Invalid value '" + std::string(s.value) +
35 "' for type 'bool' in '" + std::string(s.full_key) +
36 "',\n "
37 "possible values are: '0', '1', 'true', 'false'");
38}
39
40template <>
41void ALPAQA_EXPORT set_param(std::string_view &v, ParamString s) {
43 v = s.value;
44}
45
46template <>
47void ALPAQA_EXPORT set_param(std::string &v, ParamString s) {
49 v = s.value;
50}
51
52template <class T>
53 requires((std::floating_point<T> || std::integral<T>) && !std::is_enum_v<T>)
54void set_param(T &f, ParamString s) {
56 const auto *val_end = s.value.data() + s.value.size();
57 const auto *ptr = set_param_float_int(f, s);
58 if (ptr != val_end)
59 throw std::invalid_argument("Invalid suffix '" +
60 std::string(ptr, val_end) + "' for type '" +
61 demangled_typename(typeid(T)) + "' in '" +
62 std::string(s.full_key) + "'");
63}
64
65#ifdef ALPAQA_WITH_QUAD_PRECISION
66template <>
67void ALPAQA_EXPORT set_param(__float128 &f, ParamString s) {
68 long double ld;
69 set_param(ld, s);
70 f = static_cast<__float128>(ld);
71}
72#endif
73
74template <>
76 v.resize(std::count(s.value.begin(), s.value.end(), ',') + 1);
77 std::string_view value, remainder = s.value;
78 for (auto &e : v) {
79 std::tie(value, remainder) = split_key(remainder, ',');
80 set_param(e, {.full_key = s.full_key, .key = "", .value = value});
81 }
82}
83
84template <>
87 if (s.value.starts_with('@')) {
88 std::string fpath{s.value.substr(1)};
89 std::ifstream f(fpath);
90 if (!f)
91 throw std::invalid_argument("Unable to open file '" + fpath +
92 "' in '" + std::string(s.full_key) +
93 '\'');
94 try {
95 auto r = alpaqa::csv::read_row_std_vector<real_t<config_t>>(f);
96 auto r_size = static_cast<length_t<config_t>>(r.size());
97 if (v.expected_size >= 0 && r_size != v.expected_size)
98 throw std::invalid_argument(
99 "Incorrect size in '" + std::string(s.full_key) +
100 "' (got " + std::to_string(r.size()) + ", expected " +
101 std::to_string(v.expected_size) + ')');
102 v.value.emplace(cmvec<config_t>{r.data(), r_size});
103 } catch (alpaqa::csv::read_error &e) {
104 throw std::invalid_argument(
105 "Unable to read from file '" + fpath + "' in '" +
106 std::string(s.full_key) +
107 "': alpaqa::csv::read_error: " + e.what());
108 }
109 } else {
110 alpaqa::params::set_param(v.value.emplace(), s);
111 if (v.expected_size >= 0 && v.value->size() != v.expected_size)
112 throw std::invalid_argument(
113 "Incorrect size in '" + std::string(s.full_key) + "' (got " +
114 std::to_string(v.value->size()) + ", expected " +
115 std::to_string(v.expected_size) + ')');
116 }
117}
118
119template <class Rep, class Period>
120void set_param(std::chrono::duration<Rep, Period> &t, ParamString s) {
121 using Duration = std::remove_cvref_t<decltype(t)>;
123 const auto *val_end = s.value.data() + s.value.size();
124 double value;
125#if ALPAQA_USE_FROM_CHARS_FLOAT
126 auto [ptr, ec] = std::from_chars(s.value.data(), val_end, value);
127 if (ec != std::errc())
128 throw std::invalid_argument("Invalid value '" +
129 std::string(ptr, val_end) + "' for type '" +
131 "' in '" + std::string(s.full_key) +
132 "': " + std::make_error_code(ec).message());
133#else
134 size_t end_index;
135 try {
136 value = std::stod(std::string(s.value), &end_index);
137 } catch (std::exception &e) {
138 throw std::invalid_argument(
139 "Invalid value '" + std::string(s.value) + "' for type '" +
140 demangled_typename(typeid(Duration)) + "' in '" +
141 std::string(s.full_key) + "': " + e.what());
142 }
143 const char *ptr = s.value.data() + end_index;
144#endif
145 std::string_view units{ptr, val_end};
146 auto cast = [](auto t) { return std::chrono::duration_cast<Duration>(t); };
147 if (units == "s" || units.empty())
148 t = cast(std::chrono::duration<double, std::ratio<1, 1>>{value});
149 else if (units == "ms")
150 t = cast(std::chrono::duration<double, std::ratio<1, 1000>>{value});
151 else if (units == "us" || units == "µs")
152 t = cast(std::chrono::duration<double, std::ratio<1, 1000000>>{value});
153 else if (units == "ns")
154 t = cast(
155 std::chrono::duration<double, std::ratio<1, 1000000000>>{value});
156 else if (units == "min")
157 t = cast(std::chrono::duration<double, std::ratio<60, 1>>{value});
158 else
159 throw std::invalid_argument("Invalid units '" + std::string(units) +
160 "' in '" + std::string(s.full_key) + "'");
161}
162
163template <>
165 if (s.value == "BasedOnExternalStepSize")
167 else if (s.value == "BasedOnCurvature")
169 else
170 throw std::invalid_argument("Invalid value '" + std::string(s.value) +
171 "' for type 'LBFGSStepSize' in '" +
172 std::string(s.full_key) + "'");
173}
174
175template <>
177 if (s.value == "ApproxKKT")
179 else if (s.value == "ApproxKKT2")
181 else if (s.value == "ProjGradNorm")
183 else if (s.value == "ProjGradNorm2")
185 else if (s.value == "ProjGradUnitNorm")
187 else if (s.value == "ProjGradUnitNorm2")
189 else if (s.value == "FPRNorm")
191 else if (s.value == "FPRNorm2")
193 else if (s.value == "Ipopt")
195 else if (s.value == "LBFGSBpp")
197 else
198 throw std::invalid_argument("Invalid value '" + std::string(s.value) +
199 "' for type 'PANOCStopCrit' in '" +
200 std::string(s.full_key) + "'");
201}
202
204 PARAMS_MEMBER(memory), //
205 PARAMS_MEMBER(min_div_fac), //
206 PARAMS_MEMBER(min_abs_s), //
207 PARAMS_MEMBER(cbfgs), //
208 PARAMS_MEMBER(force_pos_def), //
209 PARAMS_MEMBER(stepsize), //
211
213 PARAMS_MEMBER(memory), //
214 PARAMS_MEMBER(min_div_fac), //
216
218 PARAMS_MEMBER(α), //
219 PARAMS_MEMBER(ϵ), //
221
223 PARAMS_MEMBER(L_0), //
224 PARAMS_MEMBER(δ), //
225 PARAMS_MEMBER(ε), //
226 PARAMS_MEMBER(Lγ_factor), //
228
230 PARAMS_MEMBER(Lipschitz), //
231 PARAMS_MEMBER(max_iter), //
232 PARAMS_MEMBER(max_time), //
233 PARAMS_MEMBER(L_min), //
234 PARAMS_MEMBER(L_max), //
235 PARAMS_MEMBER(stop_crit), //
236 PARAMS_MEMBER(max_no_progress), //
237 PARAMS_MEMBER(print_interval), //
238 PARAMS_MEMBER(print_precision), //
239 PARAMS_MEMBER(quadratic_upperbound_tolerance_factor), //
240 PARAMS_MEMBER(TR_tolerance_factor), //
241 PARAMS_MEMBER(ratio_threshold_acceptable), //
242 PARAMS_MEMBER(ratio_threshold_good), //
243 PARAMS_MEMBER(radius_factor_rejected), //
244 PARAMS_MEMBER(radius_factor_acceptable), //
245 PARAMS_MEMBER(radius_factor_good), //
246 PARAMS_MEMBER(initial_radius), //
247 PARAMS_MEMBER(min_radius), //
248 PARAMS_MEMBER(compute_ratio_using_new_stepsize), //
249 PARAMS_MEMBER(update_direction_on_prox_step), //
250 PARAMS_MEMBER(recompute_last_prox_step_after_direction_reset), //
251 PARAMS_MEMBER(disable_acceleration), //
252 PARAMS_MEMBER(ratio_approx_fbe_quadratic_model), //
254
256 PARAMS_MEMBER(Lipschitz), //
257 PARAMS_MEMBER(max_iter), //
258 PARAMS_MEMBER(max_time), //
259 PARAMS_MEMBER(min_linesearch_coefficient), //
260 PARAMS_MEMBER(force_linesearch), //
261 PARAMS_MEMBER(linesearch_strictness_factor), //
262 PARAMS_MEMBER(L_min), //
263 PARAMS_MEMBER(L_max), //
264 PARAMS_MEMBER(stop_crit), //
265 PARAMS_MEMBER(max_no_progress), //
266 PARAMS_MEMBER(print_interval), //
267 PARAMS_MEMBER(print_precision), //
268 PARAMS_MEMBER(quadratic_upperbound_tolerance_factor), //
269 PARAMS_MEMBER(linesearch_tolerance_factor), //
270 PARAMS_MEMBER(update_direction_in_candidate), //
271 PARAMS_MEMBER(recompute_last_prox_step_after_stepsize_change), //
272 PARAMS_MEMBER(eager_gradient_eval), //
274
276 PARAMS_MEMBER(Lipschitz), //
277 PARAMS_MEMBER(max_iter), //
278 PARAMS_MEMBER(max_time), //
279 PARAMS_MEMBER(min_linesearch_coefficient), //
280 PARAMS_MEMBER(force_linesearch), //
281 PARAMS_MEMBER(linesearch_strictness_factor), //
282 PARAMS_MEMBER(L_min), //
283 PARAMS_MEMBER(L_max), //
284 PARAMS_MEMBER(stop_crit), //
285 PARAMS_MEMBER(max_no_progress), //
286 PARAMS_MEMBER(print_interval), //
287 PARAMS_MEMBER(print_precision), //
288 PARAMS_MEMBER(quadratic_upperbound_tolerance_factor), //
289 PARAMS_MEMBER(linesearch_tolerance_factor), //
290 PARAMS_MEMBER(update_direction_in_candidate), //
291 PARAMS_MEMBER(recompute_last_prox_step_after_stepsize_change), //
292 PARAMS_MEMBER(update_direction_from_prox_step), //
294
296 PARAMS_MEMBER(rescale_on_step_size_changes), //
298
300 PARAMS_MEMBER(rescale_on_step_size_changes), //
302
304 PARAMS_MEMBER(hessian_vec_factor), //
305 PARAMS_MEMBER(hessian_vec_finite_differences), //
306 PARAMS_MEMBER(full_augmented_hessian), //
308
310 PARAMS_MEMBER(hessian_vec_factor), //
312 PARAMS_MEMBER(finite_diff_stepsize), //
314
316 PARAMS_MEMBER(tol_scale), //
317 PARAMS_MEMBER(tol_scale_root), //
318 PARAMS_MEMBER(tol_max), //
319 PARAMS_MEMBER(max_iter_factor), //
321
323 PARAMS_MEMBER(min_eig), //
324 PARAMS_MEMBER(print_eig), //
326
328 PARAMS_MEMBER(hessian_vec_factor), //
330
332 PARAMS_MEMBER(tolerance), //
333 PARAMS_MEMBER(dual_tolerance), //
334 PARAMS_MEMBER(penalty_update_factor), //
335 PARAMS_MEMBER(initial_penalty), //
336 PARAMS_MEMBER(initial_penalty_factor), //
337 PARAMS_MEMBER(initial_tolerance), //
338 PARAMS_MEMBER(tolerance_update_factor), //
339 PARAMS_MEMBER(rel_penalty_increase_threshold), //
340 PARAMS_MEMBER(max_multiplier), //
341 PARAMS_MEMBER(max_penalty), //
342 PARAMS_MEMBER(min_penalty), //
343 PARAMS_MEMBER(max_iter), //
344 PARAMS_MEMBER(max_time), //
345 PARAMS_MEMBER(print_interval), //
346 PARAMS_MEMBER(print_precision), //
347 PARAMS_MEMBER(single_penalty_factor), //
349
350#if ALPAQA_WITH_OCP
352 PARAMS_MEMBER(Lipschitz), //
353 PARAMS_MEMBER(max_iter), //
354 PARAMS_MEMBER(max_time), //
355 PARAMS_MEMBER(min_linesearch_coefficient), //
356 PARAMS_MEMBER(linesearch_strictness_factor), //
357 PARAMS_MEMBER(L_min), //
358 PARAMS_MEMBER(L_max), //
359 PARAMS_MEMBER(L_max_inc), //
360 PARAMS_MEMBER(stop_crit), //
361 PARAMS_MEMBER(max_no_progress), //
362 PARAMS_MEMBER(gn_interval), //
363 PARAMS_MEMBER(gn_sticky), //
364 PARAMS_MEMBER(reset_lbfgs_on_gn_step), //
365 PARAMS_MEMBER(lqr_factor_cholesky), //
366 PARAMS_MEMBER(lbfgs_params), //
367 PARAMS_MEMBER(print_interval), //
368 PARAMS_MEMBER(print_precision), //
369 PARAMS_MEMBER(quadratic_upperbound_tolerance_factor), //
370 PARAMS_MEMBER(linesearch_tolerance_factor), //
371 PARAMS_MEMBER(disable_acceleration), //
373#endif
374
375namespace detail {
376
377/// Check if @p A is equal to any of @p Bs.
378template <class A, class... Bs>
379constexpr bool any_is_same() {
380 return (std::is_same_v<A, Bs> || ...);
381}
382
383/// Unused unique type tag for template specializations that were rejected
384/// because some types were not distinct.
385template <class...>
386struct _dummy;
387
388/// If @p NewAlias is not the same type as any of @p PossibleAliases, the result
389/// is @p NewAlias. If @p NewAlias is not distinct from @p PossibleAliases, the
390/// result is a dummy type, uniquely determined by @p NewAlias and
391/// @p PossibleAliases.
392template <class NewAlias, class... PossibleAliases>
394 std::conditional_t<any_is_same<NewAlias, PossibleAliases...>(),
396
397} // namespace detail
398
399template <class... Ts>
400void set_param(detail::_dummy<Ts...> &, ParamString) {}
401
402#define ALPAQA_SET_PARAM_INST(...) \
403 template void ALPAQA_EXPORT set_param( \
404 detail::possible_alias_t<__VA_ARGS__> &, ParamString)
405
408ALPAQA_SET_PARAM_INST(long double, double, float);
409
418
419// Here, we would like to instantiate alpaqa::params::set_param for all standard
420// integer types, but the issue is that they might not be distinct types:
421// For example, on some platforms, int32_t might be a weak alias to int, whereas
422// on other platforms, it could be a distinct type.
423// To resolve this issue, we use some metaprogramming to ensure distinct
424// instantiations with unique dummy types.
425#define ALPAQA_SET_PARAM_INST_INT(...) \
426 ALPAQA_SET_PARAM_INST(__VA_ARGS__, int8_t, uint8_t, int16_t, uint16_t, \
427 int32_t, int64_t, uint32_t, uint64_t)
428
432ALPAQA_SET_PARAM_INST_INT(long long, long, int, short);
433ALPAQA_SET_PARAM_INST_INT(ptrdiff_t, long long, long, int, short);
435ALPAQA_SET_PARAM_INST_INT(unsigned int, unsigned short);
436ALPAQA_SET_PARAM_INST_INT(unsigned long, unsigned int, unsigned short);
437ALPAQA_SET_PARAM_INST_INT(unsigned long long, unsigned long, unsigned int,
438 unsigned short);
439ALPAQA_SET_PARAM_INST_INT(size_t, unsigned long long, unsigned long,
440 unsigned int, unsigned short);
441
442ALPAQA_SET_PARAM_INST(std::chrono::nanoseconds);
443ALPAQA_SET_PARAM_INST(std::chrono::microseconds);
444ALPAQA_SET_PARAM_INST(std::chrono::milliseconds);
445ALPAQA_SET_PARAM_INST(std::chrono::seconds);
446ALPAQA_SET_PARAM_INST(std::chrono::minutes);
447ALPAQA_SET_PARAM_INST(std::chrono::hours);
448
462#if ALPAQA_WITH_OCP
464#endif
465
466} // namespace alpaqa::params
std::string demangled_typename(const std::type_info &t)
Get the pretty name of the given type as a string.
vec finite_diff(const std::function< real_t(crvec)> &f, crvec x)
Parameters for the Augmented Lagrangian solver.
Definition alm.hpp:21
Parameters for the AndersonAccel class.
Definition anderson.hpp:15
Parameters for the AndersonDirection class.
Definition anderson.hpp:12
Parameters for the LBFGSDirection class.
Definition lbfgs.hpp:12
Parameters for the LBFGS class.
Definition lbfgs.hpp:42
Parameters for the estimation of the Lipschitz constant of the gradient of the smooth term of the cos...
Definition lipschitz.hpp:12
Parameters for the NewtonTRDirection class.
Definition newton-tr.hpp:17
Tuning parameters for the PANOC algorithm.
Definition panoc-ocp.hpp:17
Tuning parameters for the PANOC algorithm.
Definition panoc.hpp:25
Tuning parameters for the PANTR algorithm.
Definition pantr.hpp:23
Parameters for SteihaugCG.
Parameters for the StructuredNewtonDirection class.
Parameters for the StructuredNewtonDirection class.
Tuning parameters for the ZeroFPR algorithm.
Definition zerofpr.hpp:24
std::conditional_t< any_is_same< NewAlias, PossibleAliases... >(), _dummy< NewAlias, PossibleAliases... >, NewAlias > possible_alias_t
If NewAlias is not the same type as any of PossibleAliases, the result is NewAlias.
Definition params.cpp:395
constexpr bool any_is_same()
Check if A is equal to any of Bs.
Definition params.cpp:379
void set_param(bool &b, ParamString s)
Definition params.cpp:26
std::string_view full_key
Full key string, used for diagnostics.
Definition params.hpp:18
auto split_key(std::string_view full, char tok='.')
Split the string full on the first occurrence of tok.
Definition params.hpp:32
std::string_view value
The value of the parameter to store.
Definition params.hpp:22
Represents a parameter value encoded as a string in the format abc.def.key=value.
Definition params.hpp:16
@ LBFGSBpp
The stopping criterion used by LBFGS++, see https://lbfgspp.statr.me/doc/classLBFGSpp_1_1LBFGSBParam....
@ ProjGradUnitNorm
∞-norm of the projected gradient with unit step size:
@ ProjGradNorm
∞-norm of the projected gradient with step size γ:
@ Ipopt
The stopping criterion used by Ipopt, see https://link.springer.com/article/10.1007/s10107-004-0559-y...
@ FPRNorm2
2-norm of fixed point residual:
@ ProjGradNorm2
2-norm of the projected gradient with step size γ:
@ ApproxKKT
Find an ε-approximate KKT point in the ∞-norm:
@ FPRNorm
∞-norm of fixed point residual:
@ ApproxKKT2
Find an ε-approximate KKT point in the 2-norm:
@ ProjGradUnitNorm2
2-norm of the projected gradient with unit step size:
typename Conf::length_t length_t
Definition config.hpp:76
typename Conf::cmvec cmvec
Definition config.hpp:68
constexpr const auto inf
Definition config.hpp:85
typename Conf::vec vec
Definition config.hpp:66
LBFGSStepSize
Which method to use to select the L-BFGS step size.
Definition lbfgs.hpp:26
@ BasedOnCurvature
Initial inverse Hessian approximation is set to .
@ BasedOnExternalStepSize
Initial inverse Hessian approximation is set to , where is the forward-backward splitting step size.
#define ALPAQA_SET_PARAM_INST(...)
Definition params.cpp:402
#define ALPAQA_SET_PARAM_INST_INT(...)
Definition params.cpp:425
#define PARAMS_MEMBER(name)
Helper macro to easily initialize a alpaqa::params::dict_to_struct_table_t.
Definition params.tpp:137
#define PARAMS_TABLE(type_,...)
Helper macro to easily specialize alpaqa::params::dict_to_struct_table.
Definition params.tpp:128
Cautious BFGS update.
Definition lbfgs.hpp:18
Parameters for the StructuredLBFGSDirection class.