aGrUM 3.0.0
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 >
57 GumMRFWriter< GUM_SCALAR >::GumMRFWriter(bool binary, int indent) : MRFWriter< GUM_SCALAR >() {
58 _binary_ = binary;
59 _indent_ = (indent < -1) ? -1 : indent;
60 GUM_CONSTRUCTOR(GumMRFWriter);
61 }
62
63 template < GUM_Numeric GUM_SCALAR >
64 GumMRFWriter< GUM_SCALAR >::~GumMRFWriter() {
65 GUM_DESTRUCTOR(GumMRFWriter);
66 }
67
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.")
72
73 ordered_json content;
74 content["type"] = "MRF";
75 content["GumJsonVersion"] = "1.0";
76
77 // nodes (always written, even if empty)
78 content["nodes"] = ordered_json::array();
79 for (const auto& node: mrf.nodes()) {
80 content["nodes"].push_back(mrf.variable(node).toFast());
81 }
82
83 // factors: each factor as an inline object {"vars": [...], "values": [...]}
84 // always written, even if empty, so the section is always present
85 content["factors"] = ordered_json::array();
86 for (const auto& [nodeSet, tensor_ptr]: mrf.factors()) {
87 ordered_json factor;
88 // variable names in tensor axis order (deterministic, matches fillWith order)
89 for (Idx i = 0; i < tensor_ptr->nbrDim(); i++) {
90 factor["vars"].push_back(tensor_ptr->variable(i).name());
91 }
92 // flattened values
93 json vals;
94 Instantiation I(*tensor_ptr);
95 for (I.setFirst(); !I.end(); ++I) {
96 vals.push_back((*tensor_ptr)[I]);
97 }
98 factor["values"] = vals;
99 content["factors"].push_back(factor);
100 }
101
102 // properties
103 for (const auto& prop: mrf.properties()) {
104 content["properties"][prop] = mrf.property(prop);
105 }
106
107 if (_binary_) {
108 _writeVector_(output, json::to_msgpack(content));
109 } else {
110 output << content.dump(_indent_);
111 }
112
113 if (output.fail()) {
114 GUM_ERROR(IOError, "Writing in the ostream failed. Check if the stream is writable.")
115 }
116 }
117
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));
123 }
124
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);
131 write(output, mrf);
132 output.close();
133 if (output.fail()) { GUM_ERROR(IOError, "Writing in the ostream failed.") }
134 }
135
136 template < GUM_Numeric GUM_SCALAR >
137 std::string GumMRFWriter< GUM_SCALAR >::toString(const IMarkovRandomField< GUM_SCALAR >& mrf) {
138 std::ostringstream oss;
139 write(oss, mrf);
140 return oss.str();
141 }
142
143} // namespace gum
144
145#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.
GumMRFWriter(bool binary=false, int indent=-1)
Default constructor.
Exception : input/output problem.
Pure virtual class for writing a MRF to a file.
Definition MRFWriter.h:81
#define GUM_ERROR(type, msg)
Definition exceptions.h:76
gum is the global namespace for all aGrUM entities
Definition agrum.h:46
void _writeVector_(std::ostream &os, const std::vector< uint8_t > &vec)
Writes a length-prefixed byte vector to a binary stream (bgum format).