ppap4lmp  0.7.2
add_child_ids.cpp
Go to the documentation of this file.
1 
9 #include "add_child_ids.h"
10 #include "../utils/map_to_index.h"
11 #include "../utils/runtime_error.h"
12 
13 namespace ut = utils;
14 
15 /* ------------------------------------------------------------------ */
16 
18  const ElPtr &elem,
19  const Str &child_name_,
20  const Str &key_for_parent_id_)
21 {
22  ext_generator = elem;
23  child_name = child_name_;
24  key_for_parent_id = key_for_parent_id_;
25 }
26 
27 /* ------------------------------------------------------------------ */
28 
30  Json &data,
31  JsonToVoidFunc check_required_keys,
32  JsonToBoolFunc check_optional_keys)
33 {
34  check_required_keys("id");
35 
36  auto el_children = ext_generator->get_element();
37 
38  el_children->check_required_keys({"id", key_for_parent_id});
39 
40  auto key_for_child_ids = child_name + "-ids";
41 
42  if (check_optional_keys(key_for_child_ids))
43  {
44  ut::runtime_error("Key '" + key_for_child_ids + "' already exists");
45  }
46 
47  auto id2index = ut::map_to_index(data, "id");
48 
49  for (const auto &child : el_children->get_data())
50  {
51  auto mol_index = id2index[child[key_for_parent_id]];
52  data[mol_index][key_for_child_ids].push_back(child["id"]);
53  }
54 }
ShPtr< Element > ElPtr
An alias for a shared pointer of Element class.
Definition: element.h:378
std::function< bool(const Json &)> JsonToBoolFunc
An alias for a function accepts a Json object and returns a bool.
Definition: updater.h:20
std::string Str
Str is an alias for string.
Definition: std.h:21
nlohmann::json Json
Json is an alias for nlohmann::json.
Definition: json.h:22
ShPtr< Generator > ext_generator
Definition: updater.h:64
void runtime_error(const Str &msg)
Raise (for Python) and throw (for C++) a runtime error.
This file has a definition of AddChildIDs class, which is a subclass of Adder class.
Namespace for utility functions.
Definition: join.h:14
virtual void compute_impl(Json &data, JsonToVoidFunc check_required_keys, JsonToBoolFunc check_optional_keys) override
This method overrides Updater::compute_impl.
Str key_for_parent_id
Definition: add_child_ids.h:42
std::function< void(const Json &)> JsonToVoidFunc
An alias for a function accepts a Json object.
Definition: updater.h:18
AddChildIDs(const ElPtr &elem, const Str &child_name_, const Str &key_for_parent_id_)
Constructor of AddChildIDs class.
Map< Json, int > map_to_index(const Json &data, const Str &key)
Create a Map object from values of selected property in an array Json object to corresponding index i...