45#ifndef DOXYGEN_SHOULD_SKIP_THIS
51# include <agrum/base/external/json/json.hpp>
52using json = nlohmann::json;
53using ordered_json = nlohmann::ordered_json;
56 template < GUM_Numeric GUM_SCALAR >
59 _indent_ = (indent < -1) ? -1 : indent;
60 GUM_CONSTRUCTOR(GumMRFWriter);
63 template < GUM_Numeric GUM_SCALAR >
64 GumMRFWriter< GUM_SCALAR >::~GumMRFWriter() {
65 GUM_DESTRUCTOR(GumMRFWriter);
68 template < GUM_Numeric GUM_SCALAR >
69 void GumMRFWriter< GUM_SCALAR >::write(std::ostream& output,
70 const IMarkovRandomField< GUM_SCALAR >& mrf) {
71 if (!output.good())
GUM_ERROR(
IOError,
"Input/Output error : stream not writable.")
74 content[
"type"] =
"MRF";
75 content[
"GumJsonVersion"] =
"1.0";
78 content[
"nodes"] = ordered_json::array();
79 for (const auto& node: mrf.nodes()) {
80 content[
"nodes"].push_back(mrf.variable(node).toFast());
85 content[
"factors"] = ordered_json::array();
86 for (
const auto& [nodeSet, tensor_ptr]: mrf.factors()) {
89 for (Idx i = 0; i < tensor_ptr->nbrDim(); i++) {
90 factor[
"vars"].push_back(tensor_ptr->variable(i).name());
94 Instantiation I(*tensor_ptr);
95 for (I.setFirst(); !I.end(); ++I) {
96 vals.push_back((*tensor_ptr)[I]);
98 factor[
"values"] = vals;
99 content[
"factors"].push_back(factor);
103 for (
const auto& prop: mrf.properties()) {
104 content[
"properties"][prop] = mrf.property(prop);
110 output << content.dump(_indent_);
114 GUM_ERROR(
IOError,
"Writing in the ostream failed. Check if the stream is writable.")
118 template < GUM_Numeric GUM_SCALAR >
119 void GumMRFWriter< GUM_SCALAR >::write(std::string_view filePath,
120 IMarkovRandomField< GUM_SCALAR >& mrf) {
121 mrf.updateMetaData();
122 write(filePath,
static_cast< const IMarkovRandomField< GUM_SCALAR >&
>(mrf));
125 template < GUM_Numeric GUM_SCALAR >
126 void GumMRFWriter< GUM_SCALAR >::write(std::string_view filePath,
127 const IMarkovRandomField< GUM_SCALAR >& mrf) {
128 std::ofstream output(std::string(filePath),
129 _binary_ ? (std::ios_base::trunc | std::ios::binary)
130 : std::ios_base::trunc);
136 template < GUM_Numeric GUM_SCALAR >
137 std::string GumMRFWriter< GUM_SCALAR >::toString(
const IMarkovRandomField< GUM_SCALAR >& mrf) {
138 std::ostringstream oss;
Shared binary I/O helpers for GUM (jgum/bgum) serialization.
Definition of class for GUM (json) file output for Markov Random Fields.
GumMRFWriter(bool binary=false, int indent=-1)
Default constructor.
Exception : input/output problem.
Pure virtual class for writing a MRF to a file.
#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).