aGrUM 3.0.0
a C++ library for (probabilistic) graphical models
BIFXMLBNReader_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/BN/io/BIFXML/BIFXMLBNReader.h> // to ease IDE parser
45#ifndef DOXYGEN_SHOULD_SKIP_THIS
47
49
50namespace gum {
51 /*
52 * Constructor
53 * A reader is created to reading a defined file.
54 * Note that an BN as to be created before and given in parameter.
55 */
56 template < GUM_Numeric GUM_SCALAR >
58 std::string_view filePath) :
59 BNReader< GUM_SCALAR >(bn, filePath) {
60 GUM_CONSTRUCTOR(BIFXMLBNReader);
61 _bn_ = bn;
62 _filePath_ = filePath;
63 }
64
65 /*
66 * Constructor from an input stream.
67 */
68 template < GUM_Numeric GUM_SCALAR >
69 BIFXMLBNReader< GUM_SCALAR >::BIFXMLBNReader(BayesNet< GUM_SCALAR >* bn, std::istream& stream) :
70 BNReader< GUM_SCALAR >(bn, "<stream>") {
71 GUM_CONSTRUCTOR(BIFXMLBNReader);
72 _bn_ = bn;
73 _isFromStream_ = true;
74 _xmlContent_
75 = std::string(std::istreambuf_iterator< char >(stream), std::istreambuf_iterator< char >());
76 }
77
78 /*
79 * Default destructor.
80 */
81 template < GUM_Numeric GUM_SCALAR >
82 BIFXMLBNReader< GUM_SCALAR >::~BIFXMLBNReader() {
83 GUM_DESTRUCTOR(BIFXMLBNReader);
84 }
85
86 /*
87 * Reads the bayes net from the file referenced by filePath given at the
88 * creation
89 * of class
90 * @return Returns the number of errors during the parsing (0 if none).
91 */
92 template < GUM_Numeric GUM_SCALAR >
93 Size BIFXMLBNReader< GUM_SCALAR >::proceed() {
94 try {
95 // Loading file or parsing string
96 std::string status = _isFromStream_ ? "Parsing XML content ..." : "Loading File ...";
97 GUM_EMIT2(onProceed, 0, status);
98
99 ticpp::Document xmlDoc;
100 if (_isFromStream_) {
101 xmlDoc.Parse(_xmlContent_);
102 } else {
103 xmlDoc = ticpp::Document(_filePath_);
104 xmlDoc.LoadFile();
105 }
106
107 if (xmlDoc.NoChildren()) {
108 GUM_ERROR(IOError, ": Loading fail, please check the file for any syntax error.")
109 }
110
111 // Finding BIF element
112 status = "File loaded. Now looking for BIF element ...";
113 GUM_EMIT2(onProceed, 4, status);
114
115 ticpp::Element* bifElement = xmlDoc.FirstChildElement("BIF");
116
117 // Finding network element
118 status = "BIF Element reached. Now searching network ...";
119 GUM_EMIT2(onProceed, 7, status);
120
121 ticpp::Element* networkElement = bifElement->FirstChildElement("NETWORK");
122
123 // Reading network name (optional)
124 ticpp::Element* nameElement = networkElement->FirstChildElement("NAME", false);
125 if (nameElement != nullptr) { _bn_->setProperty("name", nameElement->GetTextOrDefault("")); }
126
127 // Finding id variables
128 status = "Network found. Now proceeding variables instantiation...";
129 GUM_EMIT2(onProceed, 10, status);
130
131 _parsingVariables_(networkElement);
132
133 // Filling diagram
134 status = "All variables have been instantiated. Now filling up diagram...";
135 GUM_EMIT2(onProceed, 55, status);
136
137 _fillingBN_(networkElement);
138
139 status = "Instantiation of network completed";
140 GUM_EMIT2(onProceed, 100, status);
141
142 return 0;
143 } catch (ticpp::Exception& tinyexception) { GUM_ERROR(IOError, tinyexception.what()) }
144 }
145
146 template < GUM_Numeric GUM_SCALAR >
147 void BIFXMLBNReader< GUM_SCALAR >::_parsingVariables_(ticpp::Element* parentNetwork) {
148 int nbVar = 0;
149 ticpp::Iterator< ticpp::Element > varIte("VARIABLE");
150
151 for (varIte = varIte.begin(parentNetwork); varIte != varIte.end(); ++varIte)
152 nbVar++;
153
154 // Iterating on variable element
155 int nbIte = 0;
156
157 for (varIte = varIte.begin(parentNetwork); varIte != varIte.end(); ++varIte) {
158 ticpp::Element* currentVar = varIte.Get();
159
160 // Getting variable name
161 ticpp::Element* varNameElement = currentVar->FirstChildElement("NAME");
162 std::string varName = varNameElement->GetTextOrDefault("");
163
164 std::string description = "";
165 std::string fast = "";
166 // Getting variable description and/or fast syntax
167 ticpp::Iterator< ticpp::Element > varPropertiesIte("PROPERTY");
168 for (varPropertiesIte = varPropertiesIte.begin(currentVar);
169 varPropertiesIte != varPropertiesIte.end();
170 ++varPropertiesIte) {
171 const auto pair = gum::split(varPropertiesIte->GetTextOrDefault(""), "=");
172 if (pair.size() == 2) {
173 const auto property = gum::toLower(gum::trim_copy(pair[0]));
174 const auto value = gum::trim_copy(pair[1]);
175 // check for descritpion and fast
176 if (property == "description") {
177 description = value;
178 } else if (property == "fast") {
179 fast = value;
180 }
181 }
182 }
183
184 if (fast == "") {
185 // if no fast syntax, we create a variable with the default}
186 // Instanciation de la variable
187 auto newVar = new LabelizedVariable(varName, description, 0);
188
189 // Getting variable outcomes
190 ticpp::Iterator< ticpp::Element > varOutComesIte("OUTCOME");
191
192 for (varOutComesIte = varOutComesIte.begin(currentVar);
193 varOutComesIte != varOutComesIte.end();
194 ++varOutComesIte)
195 newVar->addLabel(varOutComesIte->GetTextOrDefault(""));
196
197 // Add the variable to the bn and then delete newVar (add makes a copy)
198 _bn_->add(*newVar);
199 delete newVar;
200 } else {
201 auto newVar = gum::fastVariable(fast, 2);
202 newVar->setDescription(description);
203 // we could check if varName is OK
204 if (newVar->name() != varName) {
206 "Variable name (" << varName << ") and fast syntax (" << fast
207 << ") are not compatible. Please check the syntax.")
208 }
209 // Add the variable to the bn and then delete newVar (add makes a copy)
210 _bn_->add(*newVar);
211 }
212
213 // Emitting progress.
214 std::string status = "Network found. Now proceedind variables instanciation...";
215 int progress = (int)((float)nbIte / (float)nbVar * 45) + 10;
216 GUM_EMIT2(onProceed, progress, status);
217 nbIte++;
218 }
219 }
220
221 template < GUM_Numeric GUM_SCALAR >
222
223
224 void BIFXMLBNReader< GUM_SCALAR >::_fillingBN_(ticpp::Element* parentNetwork) {
225 // Counting the number of variable for the signal
226 int nbDef = 0;
227 ticpp::Iterator< ticpp::Element > definitionIte("DEFINITION");
228
229 for (definitionIte = definitionIte.begin(parentNetwork); definitionIte != definitionIte.end();
230 ++definitionIte)
231 nbDef++;
232
233 // Iterating on definition nodes
234 int nbIte = 0;
235
236 for (definitionIte = definitionIte.begin(parentNetwork); definitionIte != definitionIte.end();
237 ++definitionIte) {
238 ticpp::Element* currentVar = definitionIte.Get();
239
240 // Considered Node
241 std::string currentVarName = currentVar->FirstChildElement("FOR")->GetTextOrDefault("");
242 NodeId currentVarId = _bn_->idFromName(currentVarName);
243
244 // Get Node's parents
245 ticpp::Iterator< ticpp::Element > givenIte("GIVEN");
246 List< NodeId > parentList;
247
248 for (givenIte = givenIte.begin(currentVar); givenIte != givenIte.end(); ++givenIte) {
249 std::string parentNode = givenIte->GetTextOrDefault("");
250 NodeId parentId = _bn_->idFromName(parentNode);
251 parentList.pushBack(parentId);
252 }
253
254 for (List< NodeId >::iterator_safe parentListIte = parentList.rbeginSafe();
255 parentListIte != parentList.rendSafe();
256 --parentListIte)
257 _bn_->addArc(*parentListIte, currentVarId);
258
259 // Recuperating tables values
260 ticpp::Element* tableElement = currentVar->FirstChildElement("TABLE");
261 std::istringstream issTableString(tableElement->GetTextOrDefault(""));
262 std::list< GUM_SCALAR > tablelist;
263 GUM_SCALAR value;
264
265 while (!issTableString.eof()) {
266 issTableString >> value;
267 tablelist.push_back(value);
268 }
269
270 std::vector< GUM_SCALAR > tablevector(tablelist.begin(), tablelist.end());
271
272 // Filling tables
273 _bn_->cpt(currentVarId).fillWith(tablevector);
274
275 // Emitting progress.
276 std::string status = "All variables have been instancied. Now filling up diagram...";
277 int progress = (int)((float)nbIte / (float)nbDef * 45) + 55;
278 GUM_EMIT2(onProceed, progress, status);
279 nbIte++;
280 }
281 }
282} /* namespace gum */
283
284#endif // DOXYGEN_SHOULD_SKIP_THIS
classe for import of bayes net from a XML file written with BIF Format
BIFXMLBNReader(BayesNet< GUM_SCALAR > *bn, std::string_view filePath)
Constructor A reader is created to reading a defined file.
Pure virtual class for reading a BN from a file.
Definition BNReader.h:78
Class representing a Bayesian network.
Definition BayesNet.h:93
Exception : input/output problem.
Wrapper around TiXmlDocument.
Definition ticpp.h:1409
void LoadFile(TiXmlEncoding encoding=TIXML_DEFAULT_ENCODING)
Load a file using the current document value.
Definition ticpp.cpp:705
void Parse(const std::string &xml, bool throwIfParseError=true, TiXmlEncoding encoding=TIXML_DEFAULT_ENCODING)
Parse the given xml data.
Definition ticpp.cpp:735
Wrapper around TiXmlElement.
Definition ticpp.h:1500
std::string GetTextOrDefault(const std::string &defaultValue) const
Gets the text of an Element, if it doesn't exist it will return the defaultValue.
Definition ticpp.h:1636
This is a ticpp exception class.
Definition ticpp.h:74
const char * what() const
Override std::exception::what() to return m_details.
Definition ticpp.cpp:920
Iterator for conveniently stepping through Nodes and Attributes.
Definition ticpp.h:1112
Element * FirstChildElement(bool throwIfNoChildren=true) const
The first child element of this node.
Definition ticpp.cpp:501
bool NoChildren() const
Check if this node has no children.
Definition ticpp.cpp:555
#define GUM_ERROR(type, msg)
Definition exceptions.h:76
std::string toLower(std::string_view str)
Returns the lowercase version of str.
std::vector< std::string > split(std::string_view str, std::string_view delim)
Split str using the delimiter.
std::string trim_copy(std::string_view s)
trim from both ends (copying)
gum is the global namespace for all aGrUM entities
Definition agrum.h:46
std::unique_ptr< DiscreteVariable > fastVariable(std::string var_description, Size default_domain_size)
Create a pointer on a Discrete Variable from a "fast" syntax.
#define GUM_EMIT2(signal, arg1, arg2)
Definition signaler.h:290
Utilities for manipulating strings.