aGrUM 3.3.2
a C++ library for (probabilistic) graphical models
GumMRFWriter_tpl.h
Go to the documentation of this file.
1/****************************************************************************
2 * This file is part of the aGrUM/pyAgrum library. *
3 * *
4 * Copyright (c) 2005-2026 by *
5 * - Pierre-Henri WUILLEMIN(_at_LIP6) *
6 * - Christophe GONZALES(_at_AMU) *
7 * *
8 * The aGrUM/pyAgrum library is free software; you can redistribute it *
9 * and/or modify it under the terms of either : *
10 * *
11 * - the GNU Lesser General Public License as published by *
12 * the Free Software Foundation, either version 3 of the License, *
13 * or (at your option) any later version, *
14 * - the MIT license (MIT), *
15 * - or both in dual license, as here. *
16 * *
17 * (see https://agrum.gitlab.io/articles/dual-licenses-lgplv3mit.html) *
18 * *
19 * This aGrUM/pyAgrum library is distributed in the hope that it will be *
20 * useful, but WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, *
21 * INCLUDING BUT NOT LIMITED TO THE WARRANTIES MERCHANTABILITY or FITNESS *
22 * FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE *
23 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER *
24 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, *
25 * ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR *
26 * OTHER DEALINGS IN THE SOFTWARE. *
27 * *
28 * See LICENCES for more details. *
29 * *
30 * SPDX-FileCopyrightText: Copyright 2005-2026 *
31 * - Pierre-Henri WUILLEMIN(_at_LIP6) *
32 * - Christophe GONZALES(_at_AMU) *
33 * SPDX-License-Identifier: LGPL-3.0-or-later OR MIT *
34 * *
35 * Contact : info_at_agrum_dot_org *
36 * homepage : http://agrum.gitlab.io *
37 * gitlab : https://gitlab.com/agrumery/agrum *
38 * *
39 ****************************************************************************/
40
41
42#pragma once
43
44#include <agrum/MRF/io/GUM/GumMRFWriter.h> // to ease IDE parser
45#ifndef DOXYGEN_SHOULD_SKIP_THIS
46
47// to ease parsing in IDE
50
51# include <agrum/base/external/json/json.hpp>
52using json = nlohmann::json;
53using ordered_json = nlohmann::ordered_json;
54
55namespace gum {
56 template < GUM_Numeric GUM_SCALAR >
59
60 template < GUM_Numeric GUM_SCALAR >
61 GumMRFWriter< GUM_SCALAR >::GumMRFWriter(bool binary, int indent) : MRFWriter< GUM_SCALAR >() {
62 _binary_ = binary;
63 _indent_ = (indent < -1) ? -1 : indent;
64 GUM_CONSTRUCTOR(GumMRFWriter);
65 }
66
67 template < GUM_Numeric GUM_SCALAR >
68 GumMRFWriter< GUM_SCALAR >::~GumMRFWriter() {
69 GUM_DESTRUCTOR(GumMRFWriter);
70 }
71
72 template < GUM_Numeric GUM_SCALAR >
73 void GumMRFWriter< GUM_SCALAR >::write(std::ostream& output,
74 const IMarkovRandomField< GUM_SCALAR >& mrf) {
75 if (!output.good()) GUM_ERROR(IOError, "Input/Output error : stream not writable.")
76
77 ordered_json content;
78 content["type"] = "MRF";
79 content["GumJsonVersion"] = "1.0";
80
81 // nodes (always written, even if empty)
82 content["nodes"] = ordered_json::array();
83 for (const auto& node: mrf.nodes()) {
84 content["nodes"].push_back(mrf.variable(node).toFast());
85 }
86
87 // factors: each factor as an inline object {"vars": [...], "values": [...]}
88 // always written, even if empty, so the section is always present
89 content["factors"] = ordered_json::array();
90 for (const auto& [nodeSet, tensor_ptr]: mrf.factors()) {
91 ordered_json factor;
92 // variable names in tensor axis order (deterministic, matches fillWith order)
93 for (Idx i = 0; i < tensor_ptr->nbrDim(); i++) {
94 factor["vars"].push_back(tensor_ptr->variable(i).name());
95 }
96 // flattened values
97 json vals;
98 Instantiation I(*tensor_ptr);
99 for (I.setFirst(); !I.end(); ++I) {
100 vals.push_back((*tensor_ptr)[I]);
101 }
102 factor["values"] = vals;
103 content["factors"].push_back(factor);
104 }
105
106 // properties
107 for (const auto& prop: mrf.properties()) {
108 content["properties"][prop] = mrf.property(prop);
109 }
110
111 if (_binary_) {
112 _writeVector_(output, json::to_msgpack(content));
113 } else {
114 output << content.dump(_indent_);
115 }
116
117 if (output.fail()) {
118 GUM_ERROR(IOError, "Writing in the ostream failed. Check if the stream is writable.")
119 }
120 }
121
122 template < GUM_Numeric GUM_SCALAR >
123 void GumMRFWriter< GUM_SCALAR >::write(std::string_view filePath,
124 IMarkovRandomField< GUM_SCALAR >& mrf) {
125 mrf.updateMetaData();
126 write(filePath, static_cast< const IMarkovRandomField< GUM_SCALAR >& >(mrf));
127 }
128
129 template < GUM_Numeric GUM_SCALAR >
130 void GumMRFWriter< GUM_SCALAR >::write(std::string_view filePath,
131 const IMarkovRandomField< GUM_SCALAR >& mrf) {
132 std::ofstream output(std::string(filePath),
133 _binary_ ? (std::ios_base::trunc | std::ios::binary)
134 : std::ios_base::trunc);
135 write(output, mrf);
136 output.close();
137 if (output.fail()) { GUM_ERROR(IOError, "Writing in the ostream failed.") }
138 }
139
140 template < GUM_Numeric GUM_SCALAR >
141 std::string GumMRFWriter< GUM_SCALAR >::toString(const IMarkovRandomField< GUM_SCALAR >& mrf) {
142 std::ostringstream oss;
143 write(oss, mrf);
144 return oss.str();
145 }
146
147} // namespace gum
148
149#endif // DOXYGEN_SHOULD_SKIP_THIS
Shared binary I/O helpers for GUM (jgum/bgum) serialization.
Definition of class for GUM (json) file output for Markov Random Fields.
Writes a MarkovRandomField in the GUM json format.
GumMRFWriter(bool binary=false)
Default constructor.
Exception : input/output problem.
#define GUM_ERROR(type, msg)
Definition exceptions.h:76
gum is the global namespace for all aGrUM entities
Definition agrum.h:46
int defaultJgumIndent()
The indentation used by the GUM writers (jgum text format) when none is given: the value of the key j...
GUM_SHARED_PUBLIC void _writeVector_(std::ostream &os, const std::vector< uint8_t > &vec)
Writes a length-prefixed byte vector to a binary stream (bgum format).