45#ifndef DOXYGEN_SHOULD_SKIP_THIS
51# include <agrum/base/external/json/json.hpp>
52using json = nlohmann::json;
53using ordered_json = nlohmann::ordered_json;
57 template < GUM_Numeric GUM_SCALAR >
60 _indent_ = (indent < -1) ? -1 : indent;
61 GUM_CONSTRUCTOR(GumBNWriter);
65 template < GUM_Numeric GUM_SCALAR >
66 GumBNWriter< GUM_SCALAR >::~GumBNWriter() {
67 GUM_DESTRUCTOR(GumBNWriter);
76 template < GUM_Numeric GUM_SCALAR >
77 void GumBNWriter< GUM_SCALAR >::_doWrite(std::ostream& output,
78 const IBayesNet< GUM_SCALAR >& bn) {
79 if (!output.good())
GUM_ERROR(
IOError,
"Input/Output error : stream not writable.");
82 content[
"type"] =
"BN";
83 content[
"GumJsonVersion"] =
"1.0";
86 content[
"nodes"] = ordered_json::array();
87 for (
const auto& node: bn.nodes()) {
88 content[
"nodes"].push_back(bn.variable(node).toFast());
91 content[
"parents"] = ordered_json::object();
92 for (
const auto& node: bn.nodes()) {
93 ordered_json parentList = ordered_json::array();
94 const auto& cpt = bn.cpt(node);
95 for (Idx i = 1; i < cpt.nbrDim(); i++)
96 parentList.push_back(cpt.variable(i).name());
97 content[
"parents"][bn.variable(node).name()] = parentList;
100 content[
"cpt"] = ordered_json::object();
101 for (
const auto& node: bn.nodes()) {
103 const auto& cpt = bn.cpt(node);
104 Instantiation I(cpt);
105 for (I.setFirst(); !I.end(); ++I) {
106 cptValues.push_back(cpt[I]);
108 content[
"cpt"][bn.variable(node).name()] = cptValues;
111 for (
const auto& prop: bn.properties()) {
112 content[
"properties"][prop] = bn.property(prop);
121 output << content.dump(_indent_);
125 GUM_ERROR(
IOError,
"Writing in the ostream failed. Check if the stream is writable.")
136 template < GUM_Numeric GUM_SCALAR >
137 void GumBNWriter< GUM_SCALAR >::_doWrite(std::string_view filePath,
138 const IBayesNet< GUM_SCALAR >& bn) {
139 std::ofstream output(std::string(filePath),
140 _binary_ ? (std::ios_base::trunc | std::ios::binary)
141 : std::ios_base::trunc);
143 _doWrite(output, bn);
Definition of classe for GUM (json) file output manipulation.
Shared binary I/O helpers for GUM (jgum/bgum) serialization.
virtual class for writing a BN to a file.
GumBNWriter(bool binary=false, int indent=-1)
Default constructor.
Exception : input/output problem.
#define GUM_ERROR(type, msg)
gum is the global namespace for all aGrUM entities
void _writeVector_(std::ostream &os, const std::vector< uint8_t > &vec)
Writes a length-prefixed byte vector to a binary stream (bgum format).