aGrUM 3.1.1
a C++ library for (probabilistic) graphical models
UAIMRFReader_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#pragma once
42
43
44#include <agrum/MRF/io/UAI/UAIMRFReader.h> // to ease IDE parser
45#ifndef DOXYGEN_SHOULD_SKIP_THIS
46
47namespace gum {
48
49 template < GUM_Numeric GUM_SCALAR >
50 UAIMRFReader< GUM_SCALAR >::UAIMRFReader(MarkovRandomField< GUM_SCALAR >* MN,
51 std::string_view filename) :
52 MRFReader< GUM_SCALAR >(MN, filename) {
53 GUM_CONSTRUCTOR(UAIMRFReader);
54 _mn_ = MN;
55 _mn_->clear();
56
57 _streamName_ = filename;
58 _parseDone_ = false;
59
60 _ioerror_ = false;
61
62 try {
63 _scanner_ = new UAIMRF::Scanner(_streamName_.c_str());
64 _parser_ = new UAIMRF::Parser(_scanner_);
65 } catch (IOError const&) { _ioerror_ = true; }
66 }
67
68 template < GUM_Numeric GUM_SCALAR >
69 UAIMRFReader< GUM_SCALAR >::~UAIMRFReader() {
70 GUM_DESTRUCTOR(UAIMRFReader);
71
72 if (!_ioerror_) {
73 // this could lead to memory leak !!
74 if (_parser_) delete (_parser_);
75
76 if (_scanner_) delete (_scanner_);
77 }
78 }
79
80 template < GUM_Numeric GUM_SCALAR >
81 UAIMRF::Scanner& UAIMRFReader< GUM_SCALAR >::scanner() {
82 if (_ioerror_) { GUM_ERROR(gum::IOError, "No such file " + streamName()) }
83
84 return *_scanner_;
85 }
86
87 template < GUM_Numeric GUM_SCALAR >
88 const std::string& UAIMRFReader< GUM_SCALAR >::streamName() const {
89 return _streamName_;
90 }
91
92 template < GUM_Numeric GUM_SCALAR >
93 bool UAIMRFReader< GUM_SCALAR >::trace() const {
94 return _traceScanning_;
95 }
96
97 template < GUM_Numeric GUM_SCALAR >
98 void UAIMRFReader< GUM_SCALAR >::trace(bool b) {
99 _traceScanning_ = b;
100 scanner().setTrace(b);
101 }
102
103 template < GUM_Numeric GUM_SCALAR >
104 Size UAIMRFReader< GUM_SCALAR >::proceed() {
105 if (_ioerror_) { GUM_ERROR(gum::IOError, "No such file " + streamName()) }
106
107 if (!_parseDone_) {
108 try {
109 _parser_->Parse();
110 _parseDone_ = true;
111 buildFromQuartets(_parser_->getQuartets());
112 } catch (gum::Exception& e) {
113 GUM_SHOWERROR(e);
114 return 1 + _parser_->errors().error_count;
115 }
116 }
117
118 return (_parser_->errors().error_count);
119 }
120
121 template < GUM_Numeric GUM_SCALAR >
122 void UAIMRFReader< GUM_SCALAR >::buildFromQuartets(
123 std::vector< std::tuple< float, int, int, int > > quartets) {
124 Idx current;
125 Size max = quartets.size();
126 if (max == 0) {
127 _addWarning_(1, 1, "Empty MarkovRandomField");
128 return;
129 }
130
131 auto isInt = [&]() -> bool { return (std::get< 0 >(quartets[current]) == -1); };
132 auto lig = [&]() -> int { return std::get< 2 >(quartets[current]); };
133 auto col = [&]() -> int { return std::get< 3 >(quartets[current]); };
134
135 auto getInt = [&]() -> int {
136 if (!isInt()) this->_addFatalError_(lig(), col(), "int expected");
137 return std::get< 1 >(quartets[current]);
138 };
139 auto getVal = [&]() -> GUM_SCALAR {
140 return (isInt()) ? (std::get< 1 >(quartets[current])) : (std::get< 0 >(quartets[current]));
141 };
142 auto incCurrent = [&]() {
143 current += 1;
144 if (current >= max) this->_addFatalError_(lig(), col(), "Not enough data in UAI file");
145 };
146
147 current = 0;
148 Size nbrNode = (Size)getInt();
149
150 for (NodeId i = 0; i < nbrNode; i++) {
151 incCurrent();
152 int mod = getInt();
153 if (mod < 2) _addError_(lig(), col(), "Number of modalities should be greater than 2.");
154 _mn_->add(gum::LabelizedVariable(std::to_string(i), "", mod));
155 }
156
157 incCurrent();
158 Size nbrFactors = (Size)getInt();
159
160 std::vector< NodeSet > clicks;
161 for (NodeId i = 0; i < nbrFactors; i++) {
162 incCurrent();
163 Size nbrVar = (Size)getInt();
164 if (nbrVar == 0) _addError_(lig(), col(), "0 is not possible here");
165
166 NodeSet vars;
167 for (NodeId j = 0; j < nbrVar; j++) {
168 incCurrent();
169 NodeId nod = (NodeId)getInt();
170 if (nod >= nbrNode)
171 _addError_(lig(), col(), "Not enough variables in the MarkovRandomField");
172 vars.insert(nod);
173 }
174 _mn_->addFactor(vars);
175 clicks.push_back(vars);
176 }
177
178 for (NodeId i = 0; i < nbrFactors; i++) {
179 incCurrent();
180 Size nbrParam = (Size)getInt();
181 if (nbrParam != _mn_->factor(clicks[i]).domainSize()) {
182 _addFatalError_(lig(), col(), "Size does not fit between clique and parameters");
183 }
184 std::vector< GUM_SCALAR > v;
185 for (Idx j = 0; j < nbrParam; j++) {
186 incCurrent();
187 v.push_back(getVal());
188 }
189 _mn_->factor(clicks[i]).fillWith(v);
190 v.clear();
191 }
192
193 if (current != max - 1) _addError_(lig(), col(), "Too many data in this file");
194 }
195
196 // @{
197 // publishing Errors API
198 template < GUM_Numeric GUM_SCALAR >
199 Idx UAIMRFReader< GUM_SCALAR >::errLine(Idx i) {
200 if (_parseDone_) return _parser_->errors().error(i).line;
201 else { GUM_ERROR(OperationNotAllowed, "UAI file not parsed yet") }
202 }
203
204 template < GUM_Numeric GUM_SCALAR >
205 Idx UAIMRFReader< GUM_SCALAR >::errCol(Idx i) {
206 if (_parseDone_) return _parser_->errors().error(i).column;
207 else { GUM_ERROR(OperationNotAllowed, "UAI file not parsed yet") }
208 }
209
210 template < GUM_Numeric GUM_SCALAR >
211 bool UAIMRFReader< GUM_SCALAR >::errIsError(Idx i) {
212 if (_parseDone_) return _parser_->errors().error(i).is_error;
213 else { GUM_ERROR(OperationNotAllowed, "UAI file not parsed yet") }
214 }
215
216 template < GUM_Numeric GUM_SCALAR >
217 std::string UAIMRFReader< GUM_SCALAR >::errMsg(Idx i) {
218 if (_parseDone_) return _parser_->errors().error(i).msg;
219 else { GUM_ERROR(OperationNotAllowed, "UAI file not parsed yet") }
220 }
221
222 template < GUM_Numeric GUM_SCALAR >
223 void UAIMRFReader< GUM_SCALAR >::showElegantErrors(std::ostream& o) {
224 if (_parseDone_) _parser_->errors().elegantErrors(o);
225 else { GUM_ERROR(OperationNotAllowed, "UAI file not parsed yet") }
226 }
227
228 template < GUM_Numeric GUM_SCALAR >
229 void UAIMRFReader< GUM_SCALAR >::showElegantErrorsAndWarnings(std::ostream& o) {
230 if (_parseDone_) _parser_->errors().elegantErrorsAndWarnings(o);
231 else { GUM_ERROR(OperationNotAllowed, "UAI file not parsed yet") }
232 }
233
234 template < GUM_Numeric GUM_SCALAR >
235 void UAIMRFReader< GUM_SCALAR >::showErrorsAndWarnings(std::ostream& o) {
236 if (_parseDone_) _parser_->errors().simpleErrorsAndWarnings(o);
237 else { GUM_ERROR(OperationNotAllowed, "UAI file not parsed yet") }
238 }
239
240 template < GUM_Numeric GUM_SCALAR >
241 void UAIMRFReader< GUM_SCALAR >::showErrorCounts(std::ostream& o) {
242 if (_parseDone_) _parser_->errors().syntheticResults(o);
243 else { GUM_ERROR(OperationNotAllowed, "UAI file not parsed yet") }
244 }
245
246 template < GUM_Numeric GUM_SCALAR >
247 Size UAIMRFReader< GUM_SCALAR >::errors() {
248 return (!_parseDone_) ? (Size)0 : _parser_->errors().error_count;
249 }
250
251 template < GUM_Numeric GUM_SCALAR >
252 Size UAIMRFReader< GUM_SCALAR >::warnings() {
253 return (!_parseDone_) ? (Size)0 : _parser_->errors().warning_count;
254 }
255
256 template < GUM_Numeric GUM_SCALAR >
257 void UAIMRFReader< GUM_SCALAR >::_addFatalError_(Idx lig, Idx col, std::string_view s) {
258 _parser_->errors().addError(s, _streamName_, lig, col);
259 GUM_ERROR(gum::OperationNotAllowed, s)
260 }
261
262 template < GUM_Numeric GUM_SCALAR >
263 void UAIMRFReader< GUM_SCALAR >::_addError_(Idx lig, Idx col, std::string_view s) {
264 _parser_->errors().addError(s, _streamName_, lig, col);
265 }
266
267 template < GUM_Numeric GUM_SCALAR >
268 void UAIMRFReader< GUM_SCALAR >::_addWarning_(Idx lig, Idx col, std::string_view s) {
269 _parser_->errors().addWarning(s, _streamName_, lig, col);
270 }
271
272 // @}
273} // namespace gum
274
275#endif // DOXYGEN_SHOULD_SKIP_THIS
Definition file for UAI exportation class.
Base class for all aGrUM's exceptions.
Definition exceptions.h:122
Exception : input/output problem.
class LabelizedVariable
Pure virtual class for reading a MRF from a file.
Definition MRFReader.h:78
Exception : operation not allowed.
UAIMRFReader(MarkovRandomField< GUM_SCALAR > *MN, std::string_view filename)
Constructor A reader is defined for reading a defined file.
#define GUM_ERROR(type, msg)
Definition exceptions.h:76
#define GUM_SHOWERROR(e)
Definition exceptions.h:89
Set< NodeId > NodeSet
Some typdefs and define for shortcuts ...
gum is the global namespace for all aGrUM entities
Definition agrum.h:46
STL namespace.