67 using json = nlohmann::ordered_json;
71 std::ifstream ifs(jsonPath);
73 LOG(error) <<
" <!> comment_ids: cannot open " << jsonPath;
78 }
catch (
const std::exception& e) {
79 LOG(error) <<
" <!> comment_ids: cannot parse " << jsonPath <<
": " << e.what();
83 if (!entries.is_array()
84 || std::any_of(entries.begin(), entries.end(), [](
const json& e) { return !e.is_object(); }))
86 LOG(error) <<
" <!> comment_ids: " << jsonPath <<
" is not an array of objects";
92 for (json& entry : entries) {
93 std::vector<Int_t> ids;
94 auto take = [&ids](
const json& id) {
95 if (
id.is_number_integer() && std::find(ids.begin(), ids.end(),
id.get<
Int_t>()) == ids.end())
96 ids.push_back(
id.get<Int_t>());
98 if (entry.contains(
"ID") && entry[
"ID"].is_array())
99 for (
const json&
id : entry[
"ID"])
101 if (entry.contains(
"DetectorID"))
102 take(entry[
"DetectorID"]);
103 if (entry.contains(
"Coefficients") && entry[
"Coefficients"].is_array())
104 for (
const json& coef : entry[
"Coefficients"])
105 if (coef.is_object() && coef.contains(
"DetectorID"))
106 take(coef[
"DetectorID"]);
110 json lines = json::array();
111 for (
const Int_t id : ids)
112 lines.push_back(std::string(
Form(
"%9d = %s",
id, model.
DecodeID(
id).c_str())));
113 const std::string anchor{entry.contains(
"ID") ?
"ID"
114 : entry.contains(
"Coefficients") ?
"Coefficients"
117 json rebuilt = json::object();
118 for (
auto it = entry.begin(); it != entry.end(); ++it) {
119 if (it.key() == ID_KEY)
121 rebuilt[it.key()] = it.value();
122 if (it.key() == anchor)
123 rebuilt[ID_KEY] = lines;
129 LOG(info) <<
" " << jsonPath <<
" names no detector ID, left as it is";
133 std::function<std::string(
const json&)> inline_ = [&inline_](
const json&
v) -> std::string {
134 if (!
v.is_array() && !
v.is_object())
137 for (
auto it =
v.begin(); it !=
v.end(); ++it)
138 items += (items.empty() ?
"" :
", ") + (
v.is_object() ? json(it.key()).dump() +
": " : std::string())
139 + inline_(it.value());
140 return v.is_array() ?
"[" + items +
"]" :
"{" + items +
"}";
142 std::string text{
"[\n"};
143 for (std::size_t e = 0; e < entries.size(); e++) {
144 const json& entry{entries[e]};
147 for (
auto it = entry.begin(); it != entry.end(); ++it, ++key) {
149 if ((it.key() ==
"Coefficients" || it.key() == ID_KEY) && it.value().is_array()) {
151 for (std::size_t c = 0; c < it.value().size(); c++)
152 value +=
" " + inline_(it.value()[c]) + (c + 1 < it.value().size() ?
",\n" :
"\n");
155 value = inline_(it.value());
156 text +=
" " + json(it.key()).dump() +
": " + value + (key + 1 < entry.size() ?
",\n" :
"\n");
158 text += e + 1 < entries.size() ?
" },\n" :
" }\n";
162 std::ofstream ofs(jsonPath);
163 if (!ofs.good() || !(ofs << text)) {
164 LOG(error) <<
" <!> comment_ids: cannot write " << jsonPath;
167 LOG(info) <<
" " << jsonPath <<
" : " << annotated <<
" entrie(s) got their detector IDs in " << ID_KEY;