alpaqa 1.0.0a17
Nonconvex constrained optimization
Loading...
Searching...
No Matches
dl-problem.hpp
Go to the documentation of this file.
1#pragma once
2
4#include <alpaqa/dl-loader-export.h>
9
10#include <filesystem>
11#include <memory>
12#include <span>
13#include <stdexcept>
14#include <string>
15#include <string_view>
16#include <type_traits>
17
18namespace alpaqa::dl {
19
20struct DL_LOADER_EXPORT invalid_abi_error : std::runtime_error {
21 using std::runtime_error::runtime_error;
22};
23
24struct DL_LOADER_EXPORT function_load_error : std::runtime_error {
25 using std::runtime_error::runtime_error;
26};
27
29 public:
30 /// Unique type for calling an extra function that is a member function.
31 struct instance_t;
32
33 ExtraFuncs() = default;
34 ExtraFuncs(std::shared_ptr<function_dict_t> &&extra_funcs)
35 : extra_functions(std::move(extra_funcs)) {}
36
37 /// An associative array of additional functions exposed by the problem.
38 std::shared_ptr<function_dict_t> extra_functions;
39
40 template <class Signature>
41 requires std::is_function_v<Signature>
42 const std::function<Signature> &extra_func(const std::string &name) const {
43 if (!extra_functions)
44 throw std::out_of_range("DLProblem: no extra functions");
45 auto it = extra_functions->dict.find(name);
46 if (it == extra_functions->dict.end())
47 throw std::out_of_range("DLProblem: no extra function named \"" +
48 name + '"');
49 try {
51 return std::any_cast<const func_t &>(it->second).function;
52 } catch (const std::bad_any_cast &) {
53 throw std::logic_error(
54 "DLProblem: incorrect type for extra function \"" + name +
55 "\" (stored type: " + demangled_typename(it->second.type()) +
56 ')');
57 }
58 }
59
60 template <class Func>
61 struct FuncTag {};
62
63 template <class Ret, class... FArgs, class... Args>
64 decltype(auto)
65 call_extra_func_helper(const void *instance,
66 FuncTag<Ret(const instance_t *, FArgs...)>,
67 const std::string &name, Args &&...args) const {
68 return extra_func<Ret(const void *, FArgs...)>(name)(
69 instance, std::forward<Args>(args)...);
70 }
71
72 template <class Ret, class... FArgs, class... Args>
73 decltype(auto)
74 call_extra_func_helper(void *instance, FuncTag<Ret(instance_t *, FArgs...)>,
75 const std::string &name, Args &&...args) {
76 return extra_func<Ret(void *, FArgs...)>(name)(
77 instance, std::forward<Args>(args)...);
78 }
79
80 template <class Ret, class... FArgs, class... Args>
81 decltype(auto) call_extra_func_helper(const void *, FuncTag<Ret(FArgs...)>,
82 const std::string &name,
83 Args &&...args) const {
84 return extra_func<Ret(FArgs...)>(name)(std::forward<Args>(args)...);
85 }
86};
87
88/// Class that loads a problem using `dlopen`.
89///
90/// The shared library should export a C function with the name @c function_name
91/// that accepts a void pointer with user data, and returns a struct of type
92/// @ref alpaqa_problem_register_t that contains all data to represent the
93/// problem, as well as function pointers for all required operations.
94/// See @ref C++/DLProblem/main.cpp and
95/// @ref problems/sparse-logistic-regression.cpp for examples.
96///
97/// @note Copies are shallow, they all share the same problem instance, take
98/// that into account when using multiple threads.
99///
100/// @ingroup grp_Problems
101/// @see @ref TypeErasedProblem
102/// @see @ref alpaqa_problem_functions_t
103/// @see @ref alpaqa_problem_register_t
104class DL_LOADER_EXPORT DLProblem : public BoxConstrProblem<DefaultConfig> {
105 public:
108
109 /// Load a problem from a shared library.
110 DLProblem(
111 /// Filename of the shared library to load.
112 const std::filesystem::path &so_filename,
113 /// Name of the problem registration function.
114 /// Should have signature
115 /// `alpaqa_problem_register_t(alpaqa_register_arg_t user_param)`.
116 const std::string &function_name = "register_alpaqa_problem",
117 /// Pointer to custom user data to pass to the registration function.
118 alpaqa_register_arg_t user_param = {});
119 /// Load a problem from a shared library.
120 DLProblem(
121 /// Filename of the shared library to load.
122 const std::filesystem::path &so_filename,
123 /// Name of the problem registration function.
124 /// Should have signature
125 /// `alpaqa_problem_register_t(alpaqa_register_arg_t user_param)`.
126 const std::string &function_name,
127 /// Custom user data to pass to the registration function.
128 std::any &user_param);
129 /// Load a problem from a shared library.
130 DLProblem(
131 /// Filename of the shared library to load.
132 const std::filesystem::path &so_filename,
133 /// Name of the problem registration function.
134 /// Should have signature
135 /// `alpaqa_problem_register_t(alpaqa_register_arg_t user_param)`.
136 const std::string &function_name,
137 /// Custom string arguments to pass to the registration function.
138 std::span<std::string_view> user_param);
139
140 private:
141 /// Path to the shared module file.
142 std::filesystem::path file;
143 /// Handle to the shared module defining the problem.
144 std::shared_ptr<void> handle;
145 /// Problem instance created by the registration function, including the
146 /// deleter to destroy it.
147 std::shared_ptr<void> instance;
148 /// Pointer to the struct of function pointers for evaluating the objective,
149 /// constraints, their gradients, etc.
150 problem_functions_t *functions = nullptr;
151 /// Dictionary of extra functions that were registered by the problem.
153
154 public:
155 // clang-format off
156 void eval_proj_diff_g(crvec z, rvec e) const;
157 void eval_proj_multipliers(rvec y, real_t M) const;
158 real_t eval_prox_grad_step(real_t γ, crvec x, crvec grad_ψ, rvec x̂, rvec p) const;
159 index_t eval_inactive_indices_res_lna(real_t γ, crvec x, crvec grad_ψ, rindexvec J) const;
160 real_t eval_f(crvec x) const;
161 void eval_grad_f(crvec x, rvec grad_fx) const;
162 void eval_g(crvec x, rvec gx) const;
163 void eval_grad_g_prod(crvec x, crvec y, rvec grad_gxy) const;
164 void eval_jac_g(crvec x, rvec J_values) const;
165 Sparsity get_jac_g_sparsity() const;
166 void eval_grad_gi(crvec x, index_t i, rvec grad_gi) const;
167 void eval_hess_L_prod(crvec x, crvec y, real_t scale, crvec v, rvec Hv) const;
168 void eval_hess_L(crvec x, crvec y, real_t scale, rvec H_values) const;
169 Sparsity get_hess_L_sparsity() const;
170 void eval_hess_ψ_prod(crvec x, crvec y, crvec Σ, real_t scale, crvec v, rvec Hv) const;
171 void eval_hess_ψ(crvec x, crvec y, crvec Σ, real_t scale, rvec H_values) const;
172 Sparsity get_hess_ψ_sparsity() const;
173 real_t eval_f_grad_f(crvec x, rvec grad_fx) const;
174 real_t eval_f_g(crvec x, rvec g) const;
175 void eval_grad_f_grad_g_prod(crvec x, crvec y, rvec grad_f, rvec grad_gxy) const;
176 void eval_grad_L(crvec x, crvec y, rvec grad_L, rvec work_n) const;
177 real_t eval_ψ(crvec x, crvec y, crvec Σ, rvec ŷ) const;
178 void eval_grad_ψ(crvec x, crvec y, crvec Σ, rvec grad_ψ, rvec work_n, rvec work_m) const;
179 real_t eval_ψ_grad_ψ(crvec x, crvec y, crvec Σ, rvec grad_ψ, rvec work_n, rvec work_m) const;
180 std::string get_name() const;
181
182 [[nodiscard]] bool provides_eval_f() const;
183 [[nodiscard]] bool provides_eval_grad_f() const;
184 [[nodiscard]] bool provides_eval_g() const;
185 [[nodiscard]] bool provides_eval_grad_g_prod() const;
186 [[nodiscard]] bool provides_eval_jac_g() const;
187 [[nodiscard]] bool provides_get_jac_g_sparsity() const;
188 [[nodiscard]] bool provides_eval_grad_gi() const;
189 [[nodiscard]] bool provides_eval_hess_L_prod() const;
190 [[nodiscard]] bool provides_eval_hess_L() const;
191 [[nodiscard]] bool provides_get_hess_L_sparsity() const;
192 [[nodiscard]] bool provides_eval_hess_ψ_prod() const;
193 [[nodiscard]] bool provides_eval_hess_ψ() const;
194 [[nodiscard]] bool provides_get_hess_ψ_sparsity() const;
195 [[nodiscard]] bool provides_eval_f_grad_f() const;
196 [[nodiscard]] bool provides_eval_f_g() const;
197 [[nodiscard]] bool provides_eval_grad_f_grad_g_prod() const;
198 [[nodiscard]] bool provides_eval_grad_L() const;
199 [[nodiscard]] bool provides_eval_ψ() const;
200 [[nodiscard]] bool provides_eval_grad_ψ() const;
201 [[nodiscard]] bool provides_eval_ψ_grad_ψ() const;
202 [[nodiscard]] bool provides_get_box_C() const;
203 [[nodiscard]] bool provides_get_box_D() const;
204 [[nodiscard]] bool provides_eval_inactive_indices_res_lna() const;
205 // clang-format on
206
207 using instance_t = ExtraFuncs::instance_t;
208
209 template <class Signature, class... Args>
210 decltype(auto) call_extra_func(const std::string &name,
211 Args &&...args) const {
212 return call_extra_func_helper(instance.get(),
214 std::forward<Args>(args)...);
215 }
216
217 template <class Signature, class... Args>
218 decltype(auto) call_extra_func(const std::string &name, Args &&...args) {
219 return extra_funcs.call_extra_func_helper(
220 instance.get(), ExtraFuncs::FuncTag<Signature>{}, name,
221 std::forward<Args>(args)...);
222 }
223};
224
225#if ALPAQA_WITH_OCP
226
227/// Class that loads an optimal control problem using `dlopen`.
228///
229/// The shared library should export a C function with the name @c function_name
230/// that accepts a void pointer with user data, and returns a struct of type
231/// @ref alpaqa_control_problem_register_t that contains all data to represent
232/// the problem, as well as function pointers for all required operations.
233///
234/// @note Copies are shallow, they all share the same problem instance, take
235/// that into account when using multiple threads.
236///
237/// @ingroup grp_Problems
238/// @see @ref TypeErasedControlProblem
240 public:
243
244 /// Load a problem from a shared library.
246 /// Filename of the shared library to load.
247 const std::filesystem::path &so_filename,
248 /// Name of the problem registration function.
249 /// Should have signature
250 /// `alpaqa_control_problem_register_t(alpaqa_register_arg_t user_param)`.
251 const std::string &function_name = "register_alpaqa_control_problem",
252 /// Pointer to custom user data to pass to the registration function.
253 alpaqa_register_arg_t user_param = {});
254
255 private:
256 /// Handle to the shared module defining the problem.
257 std::shared_ptr<void> handle;
258 /// Problem instance created by the registration function, including the
259 /// deleter to destroy it.
260 std::shared_ptr<void> instance;
261 /// Pointer to the struct of function pointers for evaluating the objective,
262 /// constraints, their gradients, etc.
263 control_problem_functions_t *functions = nullptr;
264 /// Dictionary of extra functions that were registered by the problem.
266
267 public:
268 length_t get_N() const { return functions->N; }
269 length_t get_nx() const { return functions->nx; }
270 length_t get_nu() const { return functions->nu; }
271 length_t get_nh() const { return functions->nh; }
272 length_t get_nh_N() const { return functions->nh_N; }
273 length_t get_nc() const { return functions->nc; }
274 length_t get_nc_N() const { return functions->nc_N; }
275
276 void check() const {} // TODO
277
278 // clang-format off
279 void get_U(Box &U) const;
280 void get_D(Box &D) const;
281 void get_D_N(Box &D) const;
282 void get_x_init(rvec x_init) const;
283 void eval_f(index_t timestep, crvec x, crvec u, rvec fxu) const;
284 void eval_jac_f(index_t timestep, crvec x, crvec u, rmat J_fxu) const;
285 void eval_grad_f_prod(index_t timestep, crvec x, crvec u, crvec p, rvec grad_fxu_p) const;
286 void eval_h(index_t timestep, crvec x, crvec u, rvec h) const;
287 void eval_h_N(crvec x, rvec h) const;
288 [[nodiscard]] real_t eval_l(index_t timestep, crvec h) const;
289 [[nodiscard]] real_t eval_l_N(crvec h) const;
290 void eval_qr(index_t timestep, crvec xu, crvec h, rvec qr) const;
291 void eval_q_N(crvec x, crvec h, rvec q) const;
292 void eval_add_Q(index_t timestep, crvec xu, crvec h, rmat Q) const;
293 void eval_add_Q_N(crvec x, crvec h, rmat Q) const;
294 void eval_add_R_masked(index_t timestep, crvec xu, crvec h, crindexvec mask, rmat R, rvec work) const;
295 void eval_add_S_masked(index_t timestep, crvec xu, crvec h, crindexvec mask, rmat S, rvec work) const;
296 void eval_add_R_prod_masked(index_t timestep, crvec xu, crvec h, crindexvec mask_J, crindexvec mask_K, crvec v, rvec out, rvec work) const;
297 void eval_add_S_prod_masked(index_t timestep, crvec xu, crvec h, crindexvec mask_K, crvec v, rvec out, rvec work) const;
298 [[nodiscard]] length_t get_R_work_size() const;
299 [[nodiscard]] length_t get_S_work_size() const;
300 void eval_constr(index_t timestep, crvec x, rvec c) const;
301 void eval_constr_N(crvec x, rvec c) const;
302 void eval_grad_constr_prod(index_t timestep, crvec x, crvec p, rvec grad_cx_p) const;
303 void eval_grad_constr_prod_N(crvec x, crvec p, rvec grad_cx_p) const;
304 void eval_add_gn_hess_constr(index_t timestep, crvec x, crvec M, rmat out) const;
305 void eval_add_gn_hess_constr_N(crvec x, crvec M, rmat out) const;
306
307 [[nodiscard]] bool provides_get_D() const;
308 [[nodiscard]] bool provides_get_D_N() const;
309 [[nodiscard]] bool provides_eval_add_Q_N() const;
310 [[nodiscard]] bool provides_eval_add_R_prod_masked() const;
311 [[nodiscard]] bool provides_eval_add_S_prod_masked() const;
312 [[nodiscard]] bool provides_get_R_work_size() const;
313 [[nodiscard]] bool provides_get_S_work_size() const;
314 [[nodiscard]] bool provides_eval_constr() const;
315 [[nodiscard]] bool provides_eval_constr_N() const;
316 [[nodiscard]] bool provides_eval_grad_constr_prod() const;
317 [[nodiscard]] bool provides_eval_grad_constr_prod_N() const;
318 [[nodiscard]] bool provides_eval_add_gn_hess_constr() const;
319 [[nodiscard]] bool provides_eval_add_gn_hess_constr_N() const;
320 // clang-format on
321
322 using instance_t = ExtraFuncs::instance_t;
323
324 template <class Signature, class... Args>
325 decltype(auto) call_extra_func(const std::string &name,
326 Args &&...args) const {
327 return extra_funcs.call_extra_func_helper(
328 instance.get(), ExtraFuncs::FuncTag<Signature>{}, name,
329 std::forward<Args>(args)...);
330 }
331
332 template <class Signature, class... Args>
333 decltype(auto) call_extra_func(const std::string &name, Args &&...args) {
334 return extra_funcs.call_extra_func_helper(
335 instance.get(), ExtraFuncs::FuncTag<Signature>{}, name,
336 std::forward<Args>(args)...);
337 }
338};
339
340#endif
341
342} // namespace alpaqa::dl
Implements common problem functions for minimization problems with box constraints.
Class that loads an optimal control problem using dlopen.
ExtraFuncs::instance_t instance_t
std::shared_ptr< void > instance
Problem instance created by the registration function, including the deleter to destroy it.
decltype(auto) call_extra_func(const std::string &name, Args &&...args) const
decltype(auto) call_extra_func(const std::string &name, Args &&...args)
std::shared_ptr< void > handle
Handle to the shared module defining the problem.
ExtraFuncs extra_funcs
Dictionary of extra functions that were registered by the problem.
Class that loads a problem using dlopen.
ExtraFuncs::instance_t instance_t
std::shared_ptr< void > instance
Problem instance created by the registration function, including the deleter to destroy it.
decltype(auto) call_extra_func(const std::string &name, Args &&...args) const
std::filesystem::path file
Path to the shared module file.
decltype(auto) call_extra_func(const std::string &name, Args &&...args)
std::shared_ptr< void > handle
Handle to the shared module defining the problem.
ExtraFuncs extra_funcs
Dictionary of extra functions that were registered by the problem.
decltype(auto) call_extra_func_helper(const void *instance, FuncTag< Ret(const instance_t *, FArgs...)>, const std::string &name, Args &&...args) const
decltype(auto) call_extra_func_helper(void *instance, FuncTag< Ret(instance_t *, FArgs...)>, const std::string &name, Args &&...args)
const std::function< Signature > & extra_func(const std::string &name) const
std::shared_ptr< function_dict_t > extra_functions
An associative array of additional functions exposed by the problem.
ExtraFuncs(std::shared_ptr< function_dict_t > &&extra_funcs)
decltype(auto) call_extra_func_helper(const void *, FuncTag< Ret(FArgs...)>, const std::string &name, Args &&...args) const
#define USING_ALPAQA_CONFIG(Conf)
Definition config.hpp:77
std::string demangled_typename(const std::type_info &t)
Get the pretty name of the given type as a string.
User-provided argument that is passed to the problem registration functions.
Definition dl-problem.h:65
std::function< Signature > function
Definition dl-problem.h:700
Custom type for which we can export the RTTI to support std::any across shared library boundaries whe...
Definition dl-problem.h:699
typename Conf::rmat rmat
Definition config.hpp:96
typename Conf::real_t real_t
Definition config.hpp:86
typename Conf::rindexvec rindexvec
Definition config.hpp:106
typename Conf::index_t index_t
Definition config.hpp:104
typename Conf::length_t length_t
Definition config.hpp:103
constexpr const auto inf
Definition config.hpp:112
typename Conf::rvec rvec
Definition config.hpp:91
typename Conf::crvec crvec
Definition config.hpp:92
typename Conf::crindexvec crindexvec
Definition config.hpp:107
Result(const MemberGetter &) func_t
Double-precision double configuration.
Definition config.hpp:174
Stores any of the supported sparsity patterns.
Definition sparsity.hpp:106
C API providing function pointers to problem functions.
Definition dl-problem.h:210