aGrUM 3.0.0
a C++ library for (probabilistic) graphical models
GumMRFReader_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/GumMRFReader.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;
53
54namespace gum {
55 template < GUM_Numeric GUM_SCALAR >
56 GumMRFReader< GUM_SCALAR >::GumMRFReader(MarkovRandomField< GUM_SCALAR >* mrf,
57 std::string_view filename,
58 bool binary) : MRFReader< GUM_SCALAR >(mrf, filename) {
59 GUM_CONSTRUCTOR(GumMRFReader)
60 _mrf_ = mrf;
61 _streamName_ = filename;
62 _parseDone_ = false;
63 _binary_ = binary;
64 }
65
66 template < GUM_Numeric GUM_SCALAR >
67 GumMRFReader< GUM_SCALAR >::GumMRFReader(MarkovRandomField< GUM_SCALAR >* mrf) :
68 MRFReader< GUM_SCALAR >(mrf, "") {
69 GUM_CONSTRUCTOR(GumMRFReader)
70 _mrf_ = mrf;
71 _streamName_ = "";
72 _parseDone_ = false;
73 _binary_ = false;
74 }
75
76 template < GUM_Numeric GUM_SCALAR >
77 GumMRFReader< GUM_SCALAR >::~GumMRFReader() {
78 GUM_DESTRUCTOR(GumMRFReader)
79 }
80
81 template < GUM_Numeric GUM_SCALAR >
82 template < typename JsonType >
83 Size GumMRFReader< GUM_SCALAR >::_proceedFromJson_(const JsonType& content) {
84 Size nberrors = 0;
85
86 if (content.contains("type") && content["type"].template get< std::string >() != "MRF") {
87 addError("Invalid GUM file format: expected 'MRF' type, got '"
88 + content["type"].template get< std::string >() + "'",
89 _streamName_,
90 0,
91 0);
92 return ++nberrors;
93 }
94
95 if (!content.contains("nodes") || !content.contains("factors")) {
96 addError("Invalid GUM file format: missing 'nodes' or 'factors' sections",
97 _streamName_,
98 0,
99 0);
100 return ++nberrors;
101 }
102
103 try {
104 MarkovRandomField< GUM_SCALAR > tmp;
105
106 // add nodes
107 for (const auto& node: content["nodes"]) {
108 tmp.add(node.template get< std::string >());
109 }
110
111 // parse all factor data once, then add topology, then fill values
112 struct FactorData {
113 std::vector< std::string > varnames;
114 std::vector< double > values;
115 };
116
117 std::vector< FactorData > factors;
118 factors.reserve(content["factors"].size());
119 for (const auto& factor: content["factors"]) {
120 factors.push_back({factor["vars"].template get< std::vector< std::string > >(),
121 factor["values"].template get< std::vector< double > >()});
122 }
123
124 tmp.beginTopologyTransformation();
125 for (const auto& fd: factors)
126 tmp.addFactor(fd.varnames);
127 tmp.endTopologyTransformation();
128
129 for (const auto& fd: factors)
130 tmp.factor(fd.varnames).fillWith(fd.values);
131
132 // properties
133 if (content.contains("properties")) {
134 for (const auto& prop: content["properties"].items()) {
135 tmp.setProperty(prop.key(), prop.value().template get< std::string >());
136 }
137 }
138
139 *_mrf_ = std::move(tmp);
140 _parseDone_ = true;
141 } catch (const gum::Exception& e) {
142 addError(e.errorContent(), _streamName_, 0, 0);
143 return ++nberrors;
144 }
145 return nberrors;
146 }
147
148 template < GUM_Numeric GUM_SCALAR >
149 Size GumMRFReader< GUM_SCALAR >::proceed() {
150 if (_parseDone_) { return 0; }
151 if (_streamName_.empty()) {
153 "GumMRFReader was constructed without a filename: use proceedFromString() instead "
154 "of proceed()")
155 }
156 Size nberrors = 0;
157
158 std::ifstream file(_streamName_, _binary_ ? std::ios::binary : std::ios::in);
159 if (!file.is_open()) {
160 addException("No such file " + _streamName_, _streamName_);
161 return ++nberrors;
162 }
163 try {
164 const auto content
165 = _binary_ ? json::from_msgpack(_readVector_(file)) : json::parse(file, nullptr, false);
166 file.close();
167 if (content.is_discarded()) {
168 addException("Error parsing file", _streamName_);
169 return ++nberrors;
170 }
171 return _proceedFromJson_(content);
172 } catch (const std::exception& e) {
173 addException(std::string("Error reading binary file: ") + e.what(), _streamName_);
174 return ++nberrors;
175 }
176 }
177
178 template < GUM_Numeric GUM_SCALAR >
179 Size GumMRFReader< GUM_SCALAR >::proceedFromString(std::string_view content) {
180 if (_parseDone_) { return 0; }
181 const auto j = json::parse(content, nullptr, false);
182 if (j.is_discarded()) {
183 addException("Invalid JSON string", _streamName_);
184 return 1;
185 }
186 return _proceedFromJson_(j);
187 }
188
189 template < GUM_Numeric GUM_SCALAR >
190 void GumMRFReader< GUM_SCALAR >::showElegantErrorsAndWarnings(std::ostream& stream) const {
191 if (_parseDone_ || count() > 0) {
192 elegantErrorsAndWarnings(stream);
193 } else {
194 GUM_ERROR(OperationNotAllowed, "File not parsed yet")
195 }
196 }
197
198 template < GUM_Numeric GUM_SCALAR >
199 void GumMRFReader< GUM_SCALAR >::showErrorCounts(std::ostream& stream) const {
200 if (_parseDone_ || count() > 0) {
201 syntheticResults(stream);
202 } else {
203 GUM_ERROR(OperationNotAllowed, "File not parsed yet")
204 }
205 }
206} // namespace gum
207
208#endif // DOXYGEN_SHOULD_SKIP_THIS
Shared binary I/O helpers for GUM (jgum/bgum) serialization.
Definition of class for reading a MarkovRandomField from a GUM (json) file.
Base class for all aGrUM's exceptions.
Definition exceptions.h:122
GUM_NODISCARD std::string errorContent() const
Returns the message content.
GumMRFReader(MarkovRandomField< GUM_SCALAR > *mrf, std::string_view filename, bool binary=false)
Constructor.
Pure virtual class for reading a MRF from a file.
Definition MRFReader.h:78
Exception : operation not allowed.
#define GUM_ERROR(type, msg)
Definition exceptions.h:76
gum is the global namespace for all aGrUM entities
Definition agrum.h:46
std::vector< uint8_t > _readVector_(std::istream &is)
Reads a length-prefixed byte vector from a binary stream (bgum format).