23namespace shamrock::solvergraph {
25 class SolverGraphSerializable :
public SolverGraph {
27 SolverGraphSerializable()
30 .name =
"SolverGraphSerializable",
31 .node_check = [](
const std::shared_ptr<INode> &) ->
bool {
35 .edge_check = [](
const std::shared_ptr<IEdge> &edge) ->
bool {
39 ~SolverGraphSerializable() =
default;
50 nlohmann::json edges = nlohmann::json::object();
52 for (
const std::string &name : p.get_edge_names()) {
53 const auto &edge_ptr = p.get_edge_ptr_base(name);
57 if (serializable ==
nullptr) {
59 "Edge '{}' is registered in SolverGraphSerializable but is not "
64 nlohmann::json edge_j;
66 edges[name] = std::move(edge_j);
69 j = nlohmann::json{{
"edges", std::move(edges)}};
84 if (!j.is_object() || !j.contains(
"edges") || !j.at(
"edges").is_object()) {
86 "Invalid JSON for SolverGraphSerializable: expected an object with an 'edges' "
91 const auto &edges = j.at(
"edges");
93 for (
const auto &[name, edge_json] : edges.items()) {
95 auto edge = std::dynamic_pointer_cast<IEdge>(serializable);
98 "Deserialized type for edge '{}' does not inherit from IEdge", name));
Polymorphic JSON serialization via a type registry.
void to_json(nlohmann::json &j, const SolverGraphSerializable &p)
Serialize a SolverGraphSerializable to JSON.
void from_json(const nlohmann::json &j, SolverGraphSerializable &p)
Deserialize a SolverGraphSerializable from JSON.
Declare a class to register and retrieve nodes and edges from a unique container.
std::shared_ptr< IEdge > register_edge_ptr_base(const std::string &name, std::shared_ptr< IEdge > edge)
Register an edge with the graph using a shared pointer.
This header file contains utility functions related to exception handling in the code.
void throw_with_loc(std::string message, SourceLocation loc=SourceLocation{})
Throw an exception and append the source location to it.
Base interface for types that can be serialized to and from JSON.
void to_json(nlohmann::json &j) const
Write this object to JSON, including the "type" discriminator.
static std::unique_ptr< JsonSerializable > from_json(const nlohmann::json &j)
Reconstruct a registered type from JSON.