aGrUM 2.3.2
a C++ library for (probabilistic) graphical models
XDSLBNReader_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-2025 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-2025 *
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#pragma once
41
42
43#ifndef DOXYGEN_SHOULD_SKIP_THIS
45
47
48namespace gum {
49 /*
50 * Constructor
51 * A reader is created to reading a defined file.
52 * Note that an BN has to be created before and given in parameter.
53 */
54 template < typename GUM_SCALAR >
56 const std::string& filePath) :
57 BNReader< GUM_SCALAR >(bn, filePath) {
58 GUM_CONSTRUCTOR(XDSLBNReader);
59 _bn_ = bn;
60 _filePath_ = filePath;
61 }
62
63 /*
64 * Default destructor.
65 */
66 template < typename GUM_SCALAR >
67 INLINE XDSLBNReader< GUM_SCALAR >::~XDSLBNReader() {
68 GUM_DESTRUCTOR(XDSLBNReader);
69 }
70
71 /*
72 * Reads the bayes net from the file referenced by filePath given at the
73 * creation
74 * of class
75 * @return Returns the number of error during the parsing (0 if none).
76 */
77 template < typename GUM_SCALAR >
78 Size XDSLBNReader< GUM_SCALAR >::proceed() {
79 try {
80 // Loading file
81 std::string status = "Loading File ...";
82 GUM_EMIT2(onProceed, 0, status);
83
84 ticpp::Document xmlDoc(_filePath_);
85 xmlDoc.LoadFile();
86
87 if (xmlDoc.NoChildren()) {
88 GUM_ERROR(IOError, ": Loading fail, please check the file for any syntax error.")
89 }
90
91 // Finding BIF element
92 status = "File loaded. Now looking for DSL element ...";
93 GUM_EMIT2(onProceed, 4, status);
94
95 ticpp::Element* bifElement = xmlDoc.FirstChildElement("smile");
96 std::string netName = "unnamedBN";
97 bifElement->GetAttribute("id", &netName, false);
98 _bn_->setProperty("name", netName);
99
100 // Finding network element
101 status = "smile Element reached. Now searching network ...";
102 GUM_EMIT2(onProceed, 7, status);
103
104 ticpp::Element* nodesElement = bifElement->FirstChildElement("nodes");
105
106 // Finding id variables
107 status = "Network found. Now proceeding variables instantiation...";
108 GUM_EMIT2(onProceed, 10, status);
109
110 _parsingCpts_(nodesElement);
111
112 // Filling diagram
113 status = "All variables have been instantiated. Now filling up diagram...";
114 GUM_EMIT2(onProceed, 55, status);
115
116 ticpp::Element* extensionsElement
117 = bifElement->FirstChildElement("extensions")->FirstChildElement("genie");
118
119 // Filling diagram
120 _parsingExtension_(extensionsElement);
121 status = "All variables have been renamed. Now filling up diagram...";
122 GUM_EMIT2(onProceed, 85, status);
123
124
125 status = "Instantiation of network completed";
126 GUM_EMIT2(onProceed, 100, status);
127
128 return 0;
129 } catch (ticpp::Exception& tinyexception) { GUM_ERROR(IOError, tinyexception.what()) }
130 }
131
132 template < typename GUM_SCALAR >
133 Size XDSLBNReader< GUM_SCALAR >::_parsingCpts_(ticpp::Element* cptsNetwork) {
134 // Counting the number of variable for the signal
135 Size nbVar = Size(0);
137
138 for (varIte = varIte.begin(cptsNetwork); varIte != varIte.end(); ++varIte)
139 nbVar++;
140 nbVar = 3 * nbVar; // 3 loops on vars
141 std::string status = "Network found. Now proceeding variables instantiation...";
142
143 // Iterating on variable element
144 int nbIte = 0;
145
146 // definition of the variables
147 for (varIte = varIte.begin(cptsNetwork); varIte != varIte.end(); ++varIte) {
148 ticpp::Element* currentVar = varIte.Get();
149
150 // Getting variable name
151 std::string varName = currentVar->GetAttribute("id");
152 std::string varDescription = varName;
153
154 // Instanciation de la variable
155 auto newVar = new LabelizedVariable(varName, varDescription, 0);
156
157 // Getting variable outcomes
158 ticpp::Iterator< ticpp::Element > varOutComesIte("state");
159
160 for (varOutComesIte = varOutComesIte.begin(currentVar);
161 varOutComesIte != varOutComesIte.end();
162 ++varOutComesIte)
163 newVar->addLabel(varOutComesIte->GetAttribute("id"));
164
165 // Add the variable to the bn and then delete newVar (add makes a copy)
166 _bn_->add(*newVar);
167 delete (newVar);
168
169 // Emitting progress.
170 int progress = (int)((float)nbIte / (float)nbVar * 45) + 10;
171 GUM_EMIT2(onProceed, progress, status);
172 nbIte++;
173 }
174
175 // ADDING ARCS and then CPTS
176 for (varIte = varIte.begin(cptsNetwork); varIte != varIte.end(); ++varIte) {
177 ticpp::Element* currentVar = varIte.Get();
178 std::string varName = currentVar->GetAttribute("id");
179
180 auto elt = currentVar->FirstChildElement("parents", false);
181 if (elt != nullptr) {
182 // iteration in the list of parents in reverse order
183 const auto& strvec = split(elt->GetTextOrDefault(""), " ");
184 for (auto rit = strvec.begin(); rit != strvec.end(); ++rit)
185 _bn_->addArc(*rit, varName);
186 }
187
188 std::istringstream issTableString(
189 currentVar->FirstChildElement("probabilities")->GetTextOrDefault(""));
190 std::vector< GUM_SCALAR > tablevector;
191 GUM_SCALAR value;
192
193 while (!issTableString.eof()) {
194 issTableString >> value;
195 tablevector.push_back(value);
196 }
197
198 // Filling tables
199 _bn_->cpt(varName).fillWith(tablevector);
200 }
201
202 //
203 return nbIte;
204 }
205
206 template < typename GUM_SCALAR >
207 void XDSLBNReader< GUM_SCALAR >::_parsingExtension_(ticpp::Element* nodesNetwork) {
209 for (varIte = varIte.begin(nodesNetwork); varIte != varIte.end(); ++varIte) {
210 ticpp::Element* currentVar = varIte.Get();
211 std::string varName = currentVar->GetAttribute("id");
212 std::string descName = currentVar->FirstChildElement("name")->GetTextOrDefault("");
213 if (descName != varName) _bn_->changeVariableName(varName, descName);
214 }
215 }
216} /* namespace gum */
217
218#endif // DOXYGEN_SHOULD_SKIP_THIS
classe for import of bayes net from a XML file written with BIF Format
Pure virtual class for reading a BN from a file.
Definition BNReader.h:76
Class representing a Bayesian network.
Definition BayesNet.h:93
Exception : input/output problem.
XDSLBNReader(BayesNet< GUM_SCALAR > *bn, const std::string &filePath)
Constructor A reader is created to reading a defined file.
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:72
std::vector< std::string > split(const std::string &str, const std::string &delim)
Split str using the delimiter.
gum is the global namespace for all aGrUM entities
Definition agrum.h:46
#define GUM_EMIT2(signal, arg1, arg2)
Definition signaler2.h:61
Utilities for manipulating strings.