alpaqa no-casadi-dep
Nonconvex constrained optimization
Loading...
Searching...
No Matches
CasADiLoader-util.hpp
Go to the documentation of this file.
1#pragma once
2
6#include <alpaqa/util/dl.hpp>
7
8#include <array>
9#include <optional>
10#include <stdexcept>
11#include <utility>
12
13#if ALPAQA_WITH_EXTERNAL_CASADI
14#include <casadi/core/casadi_types.hpp>
15#else
17#endif
18
19namespace alpaqa::inline ALPAQA_CASADI_LOADER_NAMESPACE::casadi_loader {
20
21template <class Loader, class F>
22auto wrap_load(Loader &&loader, const char *name, F f) {
23 try {
24 return f();
25 } catch (const invalid_argument_dimensions &e) {
26 throw std::invalid_argument(
27 "Unable to load function '" + loader.format_name(name) +
28 "': " + demangled_typename(typeid(e)) + ": " + e.what());
29 }
30}
31
32template <class T, class Loader, class... Args>
33auto wrapped_load(Loader &&loader, const char *name, Args &&...args) {
34 return wrap_load(loader, name, [&] {
35 return T(loader(name), std::forward<Args>(args)...);
36 });
37}
38
39template <class T, class Loader, class... Args>
40std::optional<T> try_load(Loader &&loader, const char *name, Args &&...args) {
41 try {
42 return std::make_optional(wrapped_load<T>(
43 std::forward<Loader>(loader), name, std::forward<Args>(args)...));
44#if ALPAQA_WITH_EXTERNAL_CASADI
45 } catch (casadi::CasadiException &) {
46 return std::nullopt;
47#else
48 } catch (util::dynamic_load_error &e) {
49 return std::nullopt;
50#endif
51 } catch (std::out_of_range &) {
52 // TODO: can be made more robust against false positives
53 return std::nullopt;
54 }
55}
56
57using dim = std::pair<casadi_int, casadi_int>;
58inline constexpr auto dims(auto... a) {
59 if constexpr ((... && std::is_constructible_v<dim, decltype(a)>))
60 return std::array{a...};
61 else
62 return std::array{dim{a, 1}...};
63}
64
65} // namespace alpaqa::inline ALPAQA_CASADI_LOADER_NAMESPACE::casadi_loader
#define ALPAQA_CASADI_LOADER_NAMESPACE
std::string demangled_typename(const std::type_info &t)
Get the pretty name of the given type as a string.
constexpr const auto inf
Definition config.hpp:112
auto wrapped_load(Loader &&loader, const char *name, Args &&...args)
std::optional< T > try_load(Loader &&loader, const char *name, Args &&...args)
constexpr auto dims(auto... a)
std::pair< casadi_int, casadi_int > dim
auto wrap_load(Loader &&loader, const char *name, F f)