aGrUM 3.1.1
a C++ library for (probabilistic) graphical models
BIFXMLIDReader_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/ID/io/BIFXML/BIFXMLIDReader.h> // to ease IDE parser
45#ifndef DOXYGEN_SHOULD_SKIP_THIS
46
47# include <fstream>
48# include <iostream>
49# include <sstream>
50
52
54
55namespace gum {
56 /*
57 * Constructor
58 * A reader is created to reading a defined file.
59 * Note that an ID as to be created before and given in parameter.
60 */
61 template < GUM_Numeric GUM_SCALAR >
63 std::string_view filePath) :
64 IDReader< GUM_SCALAR >(infdiag, filePath) {
65 GUM_CONSTRUCTOR(BIFXMLIDReader);
66 _infdiag_ = infdiag;
67 _filePath_ = filePath;
68 }
69
70 /*
71 * Default destructor.
72 */
73 template < GUM_Numeric GUM_SCALAR >
74 BIFXMLIDReader< GUM_SCALAR >::~BIFXMLIDReader() {
75 GUM_DESTRUCTOR(BIFXMLIDReader);
76 }
77
78 /*
79 * Reads the influence diagram from the file referenced by filePath given at
80 * the
81 * creation of class
82 * @return Returns the number of error during the parsing (0 if none).
83 */
84 template < GUM_Numeric GUM_SCALAR >
85 Size BIFXMLIDReader< GUM_SCALAR >::proceed() {
86 try {
87 // Loading file
88 std::string status = "Loading File ...";
89 GUM_EMIT2(onProceed, 0, status);
90
91 ticpp::Document xmlDoc(_filePath_);
92 xmlDoc.LoadFile();
93
94 if (xmlDoc.NoChildren()) {
95 GUM_ERROR(IOError, ": Loading fail, please check the file for any syntax error.")
96 }
97
98 // Finding BIF element
99 status = "File loaded. Now looking for BIF element ...";
100 GUM_EMIT2(onProceed, 4, status);
101
102 ticpp::Element* bifElement = xmlDoc.FirstChildElement("BIF");
103
104 // Finding network element
105 status = "BIF Element reached. Now searching network ...";
106 GUM_EMIT2(onProceed, 7, status);
107
108 ticpp::Element* networkElement = bifElement->FirstChildElement("NETWORK");
109
110 // Finding id variables
111 status = "Network found. Now proceeding variables instanciation...";
112 GUM_EMIT2(onProceed, 10, status);
113
114 _parsingVariables_(networkElement);
115
116 // Filling diagram
117 status = "All variables have been instancied. Now filling up diagram...";
118 GUM_EMIT2(onProceed, 55, status);
119
120 _fillingDiagram_(networkElement);
121
122 status = "Instanciation of network completed";
123 GUM_EMIT2(onProceed, 100, status);
124 } catch (ticpp::Exception& tinyexception) { GUM_ERROR(IOError, tinyexception.what()) }
125 return 0;
126 }
127
128 template < GUM_Numeric GUM_SCALAR >
129 void BIFXMLIDReader< GUM_SCALAR >::_parsingVariables_(ticpp::Element* parentNetwork) {
130 // Counting the number of variable for the signal
131 int nbVar = 0;
132 ticpp::Iterator< ticpp::Element > varIte("VARIABLE");
133
134 for (varIte = varIte.begin(parentNetwork); varIte != varIte.end(); ++varIte)
135 nbVar++;
136
137 // Iterating on variable element
138 int nbIte = 0;
139
140 for (varIte = varIte.begin(parentNetwork); varIte != varIte.end(); ++varIte) {
141 ticpp::Element* currentVar = varIte.Get();
142
143 // Getting variable name
144 ticpp::Element* varNameElement = currentVar->FirstChildElement("NAME");
145 std::string varName = varNameElement->GetTextOrDefault("");
146
147 std::string description = "";
148 std::string fast = "";
149
150 // Getting variable description and/or fast syntax
151 ticpp::Iterator< ticpp::Element > varPropertiesIte("PROPERTY");
152 for (varPropertiesIte = varPropertiesIte.begin(currentVar);
153 varPropertiesIte != varPropertiesIte.end();
154 ++varPropertiesIte) {
155 const auto pair = gum::split(varPropertiesIte->GetTextOrDefault(""), "=");
156 if (pair.size() == 2) {
157 const auto property = gum::toLower(gum::trim_copy(pair[0]));
158 const auto value = gum::trim_copy(pair[1]);
159 // check for descritpion and fast
160 if (property == "description") {
161 description = value;
162 } else if (property == "fast") {
163 fast = value;
164 }
165 }
166 }
167 // Getting variable type
168 const auto nodeType = currentVar->GetAttribute< std::string >("TYPE");
169 if (fast == "") {
170 // if no fast syntax, we create a variable with the default}
171 // Instanciation de la variable
172 auto newVar = new LabelizedVariable(varName, description, 0);
173
174 // Getting variable outcomes
175 ticpp::Iterator< ticpp::Element > varOutComesIte("OUTCOME");
176
177 for (varOutComesIte = varOutComesIte.begin(currentVar);
178 varOutComesIte != varOutComesIte.end();
179 ++varOutComesIte)
180 newVar->addLabel(varOutComesIte->GetTextOrDefault(""));
181
182
183 // Add the variable to the id
184 if (nodeType == "decision") _infdiag_->addDecisionNode(*newVar);
185 else if (nodeType == "utility") _infdiag_->addUtilityNode(*newVar);
186 else _infdiag_->addChanceNode(*newVar);
187 delete newVar;
188 } else {
189 auto newVar = gum::fastVariable(fast, (nodeType == "utility") ? 1 : 2);
190 newVar->setDescription(description);
191 // we could check if varName is OK
192 if (newVar->name() != varName) {
194 "Variable name (" << varName << ") and fast syntax (" << fast
195 << ") are not compatible. Please check the syntax.")
196 }
197
198 // Add the variable to the id
199 if (nodeType == "decision") _infdiag_->addDecisionNode(*newVar);
200 else if (nodeType == "utility") _infdiag_->addUtilityNode(*newVar);
201 else _infdiag_->addChanceNode(*newVar);
202 ;
203 }
204
205 // Emitting progress.
206 std::string status = "Network found. Now proceedind variables instanciation...";
207 int progress = (int)((float)nbIte / (float)nbVar * 45) + 10;
208 GUM_EMIT2(onProceed, progress, status);
209 nbIte++;
210 }
211 }
212
213 template < GUM_Numeric GUM_SCALAR >
214 void BIFXMLIDReader< GUM_SCALAR >::_fillingDiagram_(ticpp::Element* parentNetwork) {
215 // Counting the number of variable for the signal
216 int nbDef = 0;
217 ticpp::Iterator< ticpp::Element > definitionIte("DEFINITION");
218
219 for (definitionIte = definitionIte.begin(parentNetwork); definitionIte != definitionIte.end();
220 ++definitionIte)
221 nbDef++;
222
223 // Iterating on definition nodes
224 int nbIte = 0;
225
226 for (definitionIte = definitionIte.begin(parentNetwork); definitionIte != definitionIte.end();
227 ++definitionIte) {
228 ticpp::Element* currentVar = definitionIte.Get();
229
230 // Considered Node
231 std::string currentVarName = currentVar->FirstChildElement("FOR")->GetTextOrDefault("");
232 NodeId currentVarId = _infdiag_->idFromName(currentVarName);
233
234 // Get Node's parents
235 ticpp::Iterator< ticpp::Element > givenIte("GIVEN");
236 List< NodeId > parentList;
237
238 for (givenIte = givenIte.begin(currentVar); givenIte != givenIte.end(); ++givenIte) {
239 std::string parentNode = givenIte->GetTextOrDefault("");
240 NodeId parentId = _infdiag_->idFromName(parentNode);
241 parentList.pushBack(parentId);
242 }
243
244 for (List< NodeId >::iterator_safe parentListIte = parentList.rbeginSafe();
245 parentListIte != parentList.rendSafe();
246 --parentListIte)
247 _infdiag_->addArc(*parentListIte, currentVarId);
248
249 // Recuperating tables values
250 if (!_infdiag_->isDecisionNode(currentVarId)) {
251 ticpp::Element* tableElement = currentVar->FirstChildElement("TABLE");
252 std::istringstream issTableString(tableElement->GetTextOrDefault(""));
253 std::list< GUM_SCALAR > tablelist;
254 GUM_SCALAR value;
255
256 while (!issTableString.eof()) {
257 issTableString >> value;
258 tablelist.push_back(value);
259 }
260
261 std::vector< GUM_SCALAR > tablevector(tablelist.begin(), tablelist.end());
262
263 // Filling tables
264 if (_infdiag_->isChanceNode(currentVarId)) {
265 const Tensor< GUM_SCALAR >* table = &_infdiag_->cpt(currentVarId);
266 table->populate(tablevector);
267 } else if (_infdiag_->isUtilityNode(currentVarId)) {
268 const Tensor< GUM_SCALAR >* table = &_infdiag_->utility(currentVarId);
269 table->populate(tablevector);
270 }
271 }
272
273 // Emitting progress.
274 std::string status = "All variables have been instancied. Now filling up diagram...";
275 int progress = (int)((float)nbIte / (float)nbDef * 45) + 55;
276 GUM_EMIT2(onProceed, progress, status);
277 nbIte++;
278 }
279 }
280} /* namespace gum */
281
282#endif // DOXYGEN_SHOULD_SKIP_THIS
classe for import of Influence Diagram from a XML file written with BIF Format
BIFXMLIDReader(InfluenceDiagram< GUM_SCALAR > *infdiag, std::string_view filePath)
Constructor A reader is created to reading a defined file.
Pure virtual class for importing an ID from a file.
Definition IDReader.h:76
Exception : input/output problem.
Class representing an Influence Diagram.
Wrapper around TiXmlDocument.
Definition ticpp.h:1409
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
T GetAttribute(const std::string &name, bool throwIfNotFound=true) const
Returns an attribute of name from an element.
Definition ticpp.h:1799
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
#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.