alpaqa 1.0.0a8
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 <>
26void ALPAQA_EXPORT set_param(bool &b, ParamString s) {
27 assert_key_empty<bool>(s);
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) {
42 assert_key_empty<bool>(s);
43 v = s.value;
44}
45
46template <>
47void ALPAQA_EXPORT set_param(std::string &v, ParamString s) {
48 assert_key_empty<bool>(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) {
55 assert_key_empty<T>(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
65template <>
66void ALPAQA_EXPORT set_param(alpaqa::vec<config_t> &v, ParamString s) {
67 v.resize(std::count(s.value.begin(), s.value.end(), ',') + 1);
68 std::string_view value, remainder = s.value;
69 for (auto &e : v) {
70 std::tie(value, remainder) = split_key(remainder, ',');
71 set_param(e, {.full_key = s.full_key, .key = "", .value = value});
72 }
73}
74
75template <>
77 assert_key_empty<vec_from_file<config_t>>(s);
78 if (s.value.starts_with('@')) {
79 std::string fpath{s.value.substr(1)};
80 std::ifstream f(fpath);
81 if (!f)
82 throw std::invalid_argument("Unable to open file '" + fpath +
83 "' in '" + std::string(s.full_key) +
84 '\'');
85 try {
86 auto r = alpaqa::csv::read_row_std_vector<real_t<config_t>>(f);
87 auto r_size = static_cast<length_t<config_t>>(r.size());
88 if (v.expected_size >= 0 && r_size != v.expected_size)
89 throw std::invalid_argument(
90 "Incorrect size in '" + std::string(s.full_key) +
91 "' (got " + std::to_string(r.size()) + ", expected " +
92 std::to_string(v.expected_size) + ')');
93 v.value.emplace(cmvec<config_t>{r.data(), r_size});
94 } catch (alpaqa::csv::read_error &e) {
95 throw std::invalid_argument(
96 "Unable to read from file '" + fpath + "' in '" +
97 std::string(s.full_key) +
98 "': alpaqa::csv::read_error: " + e.what());
99 }
100 } else {
101 alpaqa::params::set_param(v.value.emplace(), s);
102 if (v.expected_size >= 0 && v.value->size() != v.expected_size)
103 throw std::invalid_argument(
104 "Incorrect size in '" + std::string(s.full_key) + "' (got " +
105 std::to_string(v.value->size()) + ", expected " +
106 std::to_string(v.expected_size) + ')');
107 }
108}
109
110template <class Rep, class Period>
111void set_param(std::chrono::duration<Rep, Period> &t, ParamString s) {
112 using Duration = std::remove_cvref_t<decltype(t)>;
113 assert_key_empty<Duration>(s);
114 const auto *val_end = s.value.data() + s.value.size();
115 double value;
116#if ALPAQA_USE_FROM_CHARS_FLOAT
117 auto [ptr, ec] = std::from_chars(s.value.data(), val_end, value);
118 if (ec != std::errc())
119 throw std::invalid_argument("Invalid value '" +
120 std::string(ptr, val_end) + "' for type '" +
121 demangled_typename(typeid(Duration)) +
122 "' in '" + std::string(s.full_key) +
123 "': " + std::make_error_code(ec).message());
124#else
125#pragma message "Using std::stod as a fallback to replace std::from_chars"
126 size_t end_index;
127 try {
128 value = std::stod(std::string(s.value), &end_index);
129 } catch (std::exception &e) {
130 throw std::invalid_argument(
131 "Invalid value '" + std::string(s.value) + "' for type '" +
132 demangled_typename(typeid(Duration)) + "' in '" +
133 std::string(s.full_key) + "': " + e.what());
134 }
135 const char *ptr = s.value.data() + end_index;
136#endif
137 std::string_view units{ptr, val_end};
138 auto cast = [](auto t) { return std::chrono::duration_cast<Duration>(t); };
139 if (units == "s" || units.empty())
140 t = cast(std::chrono::duration<double, std::ratio<1, 1>>{value});
141 else if (units == "ms")
142 t = cast(std::chrono::duration<double, std::ratio<1, 1000>>{value});
143 else if (units == "us" || units == "µs")
144 t = cast(std::chrono::duration<double, std::ratio<1, 1000000>>{value});
145 else if (units == "ns")
146 t = cast(
147 std::chrono::duration<double, std::ratio<1, 1000000000>>{value});
148 else if (units == "min")
149 t = cast(std::chrono::duration<double, std::ratio<60, 1>>{value});
150 else
151 throw std::invalid_argument("Invalid units '" + std::string(units) +
152 "' in '" + std::string(s.full_key) + "'");
153}
154
155template <>
156void ALPAQA_EXPORT set_param(LBFGSStepSize &t, ParamString s) {
157 if (s.value == "BasedOnExternalStepSize")
159 else if (s.value == "BasedOnCurvature")
161 else
162 throw std::invalid_argument("Invalid value '" + std::string(s.value) +
163 "' for type 'LBFGSStepSize' in '" +
164 std::string(s.full_key) + "'");
165}
166
167template <>
168void ALPAQA_EXPORT set_param(PANOCStopCrit &t, ParamString s) {
169 if (s.value == "ApproxKKT")
171 else if (s.value == "ApproxKKT2")
173 else if (s.value == "ProjGradNorm")
175 else if (s.value == "ProjGradNorm2")
177 else if (s.value == "ProjGradUnitNorm")
179 else if (s.value == "ProjGradUnitNorm2")
181 else if (s.value == "FPRNorm")
183 else if (s.value == "FPRNorm2")
185 else if (s.value == "Ipopt")
187 else if (s.value == "LBFGSBpp")
189 else
190 throw std::invalid_argument("Invalid value '" + std::string(s.value) +
191 "' for type 'PANOCStopCrit' in '" +
192 std::string(s.full_key) + "'");
193}
194
196 PARAMS_MEMBER(memory), //
197 PARAMS_MEMBER(min_div_fac), //
198 PARAMS_MEMBER(min_abs_s), //
199 PARAMS_MEMBER(cbfgs), //
200 PARAMS_MEMBER(force_pos_def), //
201 PARAMS_MEMBER(stepsize), //
203
205 PARAMS_MEMBER(memory), //
206 PARAMS_MEMBER(min_div_fac), //
208
210 PARAMS_MEMBER(α), //
211 PARAMS_MEMBER(ϵ), //
213
215 PARAMS_MEMBER(L_0), //
216 PARAMS_MEMBER(δ), //
217 PARAMS_MEMBER(ε), //
218 PARAMS_MEMBER(Lγ_factor), //
220
222 PARAMS_MEMBER(Lipschitz), //
223 PARAMS_MEMBER(max_iter), //
224 PARAMS_MEMBER(max_time), //
225 PARAMS_MEMBER(L_min), //
226 PARAMS_MEMBER(L_max), //
227 PARAMS_MEMBER(stop_crit), //
228 PARAMS_MEMBER(max_no_progress), //
229 PARAMS_MEMBER(print_interval), //
230 PARAMS_MEMBER(print_precision), //
231 PARAMS_MEMBER(quadratic_upperbound_tolerance_factor), //
232 PARAMS_MEMBER(TR_tolerance_factor), //
233 PARAMS_MEMBER(ratio_threshold_acceptable), //
234 PARAMS_MEMBER(ratio_threshold_good), //
235 PARAMS_MEMBER(radius_factor_rejected), //
236 PARAMS_MEMBER(radius_factor_acceptable), //
237 PARAMS_MEMBER(radius_factor_good), //
238 PARAMS_MEMBER(initial_radius), //
239 PARAMS_MEMBER(min_radius), //
240 PARAMS_MEMBER(compute_ratio_using_new_stepsize), //
241 PARAMS_MEMBER(update_direction_on_prox_step), //
242 PARAMS_MEMBER(recompute_last_prox_step_after_direction_reset), //
243 PARAMS_MEMBER(disable_acceleration), //
244 PARAMS_MEMBER(ratio_approx_fbe_quadratic_model), //
246
248 PARAMS_MEMBER(Lipschitz), //
249 PARAMS_MEMBER(max_iter), //
250 PARAMS_MEMBER(max_time), //
251 PARAMS_MEMBER(min_linesearch_coefficient), //
252 PARAMS_MEMBER(force_linesearch), //
253 PARAMS_MEMBER(linesearch_strictness_factor), //
254 PARAMS_MEMBER(L_min), //
255 PARAMS_MEMBER(L_max), //
256 PARAMS_MEMBER(stop_crit), //
257 PARAMS_MEMBER(max_no_progress), //
258 PARAMS_MEMBER(print_interval), //
259 PARAMS_MEMBER(print_precision), //
260 PARAMS_MEMBER(quadratic_upperbound_tolerance_factor), //
261 PARAMS_MEMBER(linesearch_tolerance_factor), //
262 PARAMS_MEMBER(update_direction_in_candidate), //
263 PARAMS_MEMBER(recompute_last_prox_step_after_lbfgs_flush), //
265
267 PARAMS_MEMBER(Lipschitz), //
268 PARAMS_MEMBER(max_iter), //
269 PARAMS_MEMBER(max_time), //
270 PARAMS_MEMBER(min_linesearch_coefficient), //
271 PARAMS_MEMBER(force_linesearch), //
272 PARAMS_MEMBER(linesearch_strictness_factor), //
273 PARAMS_MEMBER(L_min), //
274 PARAMS_MEMBER(L_max), //
275 PARAMS_MEMBER(stop_crit), //
276 PARAMS_MEMBER(max_no_progress), //
277 PARAMS_MEMBER(print_interval), //
278 PARAMS_MEMBER(print_precision), //
279 PARAMS_MEMBER(quadratic_upperbound_tolerance_factor), //
280 PARAMS_MEMBER(linesearch_tolerance_factor), //
281 PARAMS_MEMBER(update_direction_in_candidate), //
282 PARAMS_MEMBER(recompute_last_prox_step_after_lbfgs_flush), //
283 PARAMS_MEMBER(update_direction_from_prox_step), //
285
287 PARAMS_MEMBER(rescale_on_step_size_changes), //
289
291 PARAMS_MEMBER(rescale_on_step_size_changes), //
293
295 PARAMS_MEMBER(hessian_vec_factor), //
296 PARAMS_MEMBER(hessian_vec_finite_differences), //
297 PARAMS_MEMBER(full_augmented_hessian), //
299
301 PARAMS_MEMBER(rescale_on_step_size_changes), //
302 PARAMS_MEMBER(hessian_vec_factor), //
303 PARAMS_MEMBER(finite_diff), //
304 PARAMS_MEMBER(finite_diff_stepsize), //
306
308 PARAMS_MEMBER(tol_scale), //
309 PARAMS_MEMBER(tol_scale_root), //
310 PARAMS_MEMBER(tol_max), //
311 PARAMS_MEMBER(max_iter_factor), //
313
315 PARAMS_MEMBER(min_eig), //
316 PARAMS_MEMBER(print_eig), //
318
320 PARAMS_MEMBER(hessian_vec_factor), //
322
324 PARAMS_MEMBER(tolerance), //
325 PARAMS_MEMBER(dual_tolerance), //
326 PARAMS_MEMBER(penalty_update_factor), //
327 PARAMS_MEMBER(penalty_update_factor_lower), //
328 PARAMS_MEMBER(min_penalty_update_factor), //
329 PARAMS_MEMBER(initial_penalty), //
330 PARAMS_MEMBER(initial_penalty_factor), //
331 PARAMS_MEMBER(initial_penalty_lower), //
332 PARAMS_MEMBER(initial_tolerance), //
333 PARAMS_MEMBER(initial_tolerance_increase), //
334 PARAMS_MEMBER(tolerance_update_factor), //
335 PARAMS_MEMBER(ρ_increase), //
336 PARAMS_MEMBER(ρ_max), //
337 PARAMS_MEMBER(rel_penalty_increase_threshold), //
338 PARAMS_MEMBER(max_multiplier), //
339 PARAMS_MEMBER(max_penalty), //
340 PARAMS_MEMBER(min_penalty), //
341 PARAMS_MEMBER(max_iter), //
342 PARAMS_MEMBER(max_time), //
343 PARAMS_MEMBER(max_num_initial_retries), //
344 PARAMS_MEMBER(max_num_retries), //
345 PARAMS_MEMBER(max_total_num_retries), //
346 PARAMS_MEMBER(print_interval), //
347 PARAMS_MEMBER(print_precision), //
348 PARAMS_MEMBER(single_penalty_factor), //
350
351#if ALPAQA_WITH_OCP
353 PARAMS_MEMBER(Lipschitz), //
354 PARAMS_MEMBER(max_iter), //
355 PARAMS_MEMBER(max_time), //
356 PARAMS_MEMBER(min_linesearch_coefficient), //
357 PARAMS_MEMBER(linesearch_strictness_factor), //
358 PARAMS_MEMBER(L_min), //
359 PARAMS_MEMBER(L_max), //
360 PARAMS_MEMBER(L_max_inc), //
361 PARAMS_MEMBER(stop_crit), //
362 PARAMS_MEMBER(max_no_progress), //
363 PARAMS_MEMBER(gn_interval), //
364 PARAMS_MEMBER(gn_sticky), //
365 PARAMS_MEMBER(reset_lbfgs_on_gn_step), //
366 PARAMS_MEMBER(lqr_factor_cholesky), //
367 PARAMS_MEMBER(lbfgs_params), //
368 PARAMS_MEMBER(print_interval), //
369 PARAMS_MEMBER(print_precision), //
370 PARAMS_MEMBER(quadratic_upperbound_tolerance_factor), //
371 PARAMS_MEMBER(linesearch_tolerance_factor), //
372 PARAMS_MEMBER(disable_acceleration), //
374#endif
375
376namespace detail {
377
378/// Check if @p A is equal to any of @p Bs.
379template <class A, class... Bs>
380constexpr bool any_is_same() {
381 return (std::is_same_v<A, Bs> || ...);
382}
383
384/// Unused unique type tag for template specializations that were rejected
385/// because some types were not distinct.
386template <class...>
387struct _dummy;
388
389/// If @p NewAlias is not the same type as any of @p PossibleAliases, the result
390/// is @p NewAlias. If @p NewAlias is not distinct from @p PossibleAliases, the
391/// result is a dummy type, uniquely determined by @p NewAlias and
392/// @p PossibleAliases.
393template <class NewAlias, class... PossibleAliases>
395 std::conditional_t<any_is_same<NewAlias, PossibleAliases...>(),
396 _dummy<NewAlias, PossibleAliases...>, NewAlias>;
397
398} // namespace detail
399
400template <class... Ts>
401void set_param(detail::_dummy<Ts...> &, ParamString) {}
402
403#define ALPAQA_SET_PARAM_INST(...) \
404 template void ALPAQA_EXPORT set_param( \
405 detail::possible_alias_t<__VA_ARGS__> &, ParamString)
406
409ALPAQA_SET_PARAM_INST(long double, double, float);
410
419
420// Here, we would like to instantiate alpaqa::params::set_param for all standard
421// integer types, but the issue is that they might not be distinct types:
422// For example, on some platforms, int32_t might be a weak alias to int, whereas
423// on other platforms, it could be a distinct type.
424// To resolve this issue, we use some metaprogramming to ensure distinct
425// instantiations with unique dummy types.
426#define ALPAQA_SET_PARAM_INST_INT(...) \
427 ALPAQA_SET_PARAM_INST(__VA_ARGS__, int8_t, uint8_t, int16_t, uint16_t, \
428 int32_t, int64_t, uint32_t, uint64_t)
429
433ALPAQA_SET_PARAM_INST_INT(long long, long, int, short);
434ALPAQA_SET_PARAM_INST_INT(ptrdiff_t, long long, long, int, short);
436ALPAQA_SET_PARAM_INST_INT(unsigned int, unsigned short);
437ALPAQA_SET_PARAM_INST_INT(unsigned long, unsigned int, unsigned short);
438ALPAQA_SET_PARAM_INST_INT(unsigned long long, unsigned long, unsigned int,
439 unsigned short);
440ALPAQA_SET_PARAM_INST_INT(size_t, unsigned long long, unsigned long,
441 unsigned int, unsigned short);
442
443ALPAQA_SET_PARAM_INST(std::chrono::nanoseconds);
444ALPAQA_SET_PARAM_INST(std::chrono::microseconds);
445ALPAQA_SET_PARAM_INST(std::chrono::milliseconds);
446ALPAQA_SET_PARAM_INST(std::chrono::seconds);
447ALPAQA_SET_PARAM_INST(std::chrono::minutes);
448ALPAQA_SET_PARAM_INST(std::chrono::hours);
449
463#if ALPAQA_WITH_OCP
465#endif
466
467} // namespace alpaqa::params
std::string demangled_typename(const std::type_info &t)
Get the pretty name of the given type as a string.
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:396
constexpr bool any_is_same()
Check if A is equal to any of Bs.
Definition: params.cpp:380
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::optional< vec > value
Definition: params.hpp:70
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:62
typename Conf::cmvec cmvec
Definition: config.hpp:54
typename Conf::vec vec
Definition: config.hpp:52
LBFGSStepSize
Which method to use to select the L-BFGS step size.
@ BasedOnCurvature
Initial inverse Hessian approximation is set to .
@ BasedOnExternalStepSize
Initial inverse Hessian approximation is set to .
Parameters for the Augmented Lagrangian solver.
Definition: alm.hpp:20
Parameters for the AndersonAccel class.
Parameters for the AndersonDirection class.
Parameters for the LBFGSDirection class.
Parameters for the LBFGS class.
Parameters for the NewtonTRDirection class.
Definition: newton-tr.hpp:16
Tuning parameters for the PANOC algorithm.
Definition: panoc-ocp.hpp:16
Tuning parameters for the PANOC algorithm.
Definition: panoc.hpp:24
Tuning parameters for the PANTR algorithm.
Definition: pantr.hpp:22
Parameters for the StructuredNewtonDirection class.
Parameters for the StructuredNewtonDirection class.
Tuning parameters for the ZeroFPR algorithm.
Definition: zerofpr.hpp:23
#define ALPAQA_SET_PARAM_INST(...)
Definition: params.cpp:403
#define ALPAQA_SET_PARAM_INST_INT(...)
Definition: params.cpp:426
#define PARAMS_MEMBER(name)
Helper macro to easily initialize a alpaqa::params::dict_to_struct_table_t.
Definition: params.tpp:132
#define PARAMS_TABLE(type_,...)
Helper macro to easily specialize alpaqa::params::dict_to_struct_table.
Definition: params.tpp:123
Cautious BFGS update.
Parameters for the StructuredLBFGSDirection class.