16#include <nlohmann/json.hpp>
28 std::vector<nlohmann::json> json_storage;
29 nlohmann::json json_out;
33 Options(
int argc,
const char *
const argv[])
36 auto with_at = [](std::string_view s) {
return s.starts_with(
'@'); };
38 auto non_json = std::ranges::stable_partition(
opts_storage, with_at);
42 auto load = [](std::string_view s) {
43 return load_json(std::string(s.substr(1)));
45 auto json_obj = std::views::transform(
json_flags(), load);
46 json_storage =
decltype(json_storage){json_obj.begin(), json_obj.end()};
49 throw std::logic_error(
50 "This version of alpaqa was compiled without JSON support: "
51 "cannot parse options " +
57 [[nodiscard]] std::span<const std::string_view>
json_flags()
const {
60 [[nodiscard]] std::span<const std::string_view>
options()
const {
66 void set_params(T &t, std::string_view prefix);
69 [[nodiscard]] std::span<const nlohmann::json> json_data()
const {
73 [[nodiscard]]
const nlohmann::json &get_json_out()
const {
78 [[nodiscard]]
static nlohmann::json load_json(
const std::string &name) {
80 std::ifstream f{name};
82 throw std::runtime_error(
"Unable to open JSON file '" + name +
"'");
85 }
catch (nlohmann::json::exception &e) {
86 throw std::runtime_error(
"Unable to parse JSON file '" + name +
97 auto json_data = this->json_data();
98 for (
size_t i = 0; i < json_data.size(); ++i)
100 if (
auto j = json_data[i].find(prefix); j != json_data[i].end())
103 std::string fname{this->
json_flags()[i].substr(1)};
104 throw std::invalid_argument(
105 "Error in JSON file '" + fname +
"' at '" +
106 std::string(prefix) +
111 .quote_right =
""}) +
113 }
catch (nlohmann::json::exception &e) {
114 std::string fname{this->
json_flags()[i].substr(1)};
115 throw std::invalid_argument(
"Error in JSON file '" + fname +
122 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