16#include <nlohmann/json.hpp>
26 std::vector<nlohmann::json> json_storage;
27 nlohmann::json json_out;
31 Options(
int argc,
const char *
const argv[])
34 auto with_at = [](std::string_view s) {
return s.starts_with(
'@'); };
36 auto non_json = std::ranges::stable_partition(
opts_storage, with_at);
40 auto load = [](std::string_view s) {
41 return load_json(std::string(s.substr(1)));
43 auto json_obj = std::views::transform(
json_flags(), load);
44 json_storage =
decltype(json_storage){json_obj.begin(), json_obj.end()};
47 throw std::logic_error(
48 "This version of alpaqa was compiled without JSON support: "
49 "cannot parse options " +
55 [[nodiscard]] std::span<const std::string_view>
json_flags()
const {
58 [[nodiscard]] std::span<const std::string_view>
options()
const {
64 void set_params(T &t, std::string_view prefix);
67 [[nodiscard]] std::span<const nlohmann::json> json_data()
const {
71 [[nodiscard]]
const nlohmann::json &get_json_out()
const {
76 [[nodiscard]]
static nlohmann::json load_json(
const std::string &name) {
78 std::ifstream f{name};
80 throw std::runtime_error(
"Unable to open JSON file '" + name +
"'");
83 }
catch (nlohmann::json::exception &e) {
84 throw std::runtime_error(
"Unable to parse JSON file '" + name +
95 auto json_data = this->json_data();
96 for (
size_t i = 0; i < json_data.size(); ++i)
98 if (
auto j = json_data[i].find(prefix); j != json_data[i].end())
101 std::string fname{this->
json_flags()[i].substr(1)};
102 throw std::invalid_argument(
103 "Error in JSON file '" + fname +
"' at '" +
104 std::string(prefix) +
109 .quote_right =
""}) +
111 }
catch (nlohmann::json::exception &e) {
112 std::string fname{this->
json_flags()[i].substr(1)};
113 throw std::invalid_argument(
"Error in JSON file '" + fname +
120 if constexpr (!std::is_same_v<T, vec_from_file>)
std::span< unsigned > used()
std::span< const std::string_view > json_flags() const
std::span< const std::string_view > options() const
std::vector< unsigned > used_storage
void set_params(T &t, std::string_view prefix)
std::vector< std::string_view > opts_storage
Options(int argc, const char *const argv[])
void get_param(const T &, json &j)
Get the first argument as a JSON object j.
void set_param(T &, const json &j)
Update/overwrite the first argument based on the JSON object j.
void set_params(T &t, std::string_view prefix, std::span< const std::string_view > options, std::optional< std::span< unsigned > > used=std::nullopt)
Overwrites t based on the options that start with prefix.
std::string join_quote(std::ranges::input_range auto strings, join_quote_opt opt={})
Join the list of strings into a single string, using the separator given by opt.
void set_params(T &t, std::string_view prefix, Options &opts)
Custom parameter parsing exception.
std::vector< std::string > backtrace