aGrUM 3.3.2
a C++ library for (probabilistic) graphical models
IBayesNet_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
50
51#include <cmath>
52#include <limits>
53
63#include <agrum/BN/IBayesNet.h>
64
65namespace gum {
66 // IBayesNet
67
68 template < GUM_Numeric GUM_SCALAR >
70 GUM_CONSTRUCTOR(IBayesNet)
71 }
72
73 template < GUM_Numeric GUM_SCALAR >
74 IBayesNet< GUM_SCALAR >::IBayesNet(std::string_view name) : DAGmodel() {
75 GUM_CONSTRUCTOR(IBayesNet)
76 this->setProperty("name", name);
77 }
78
79 template < GUM_Numeric GUM_SCALAR >
81 GUM_CONS_CPY(IBayesNet)
82 }
83
84 template < GUM_Numeric GUM_SCALAR >
86 DAGmodel(std::move(source)) {
87 GUM_CONS_MOV(IBayesNet)
88 }
89
90 template < GUM_Numeric GUM_SCALAR >
93 if (this != &source) {
94 DAGmodel::operator=(source);
95 GUM_OP_CPY(IBayesNet);
96 }
97
98 return *this;
99 }
100
101 template < GUM_Numeric GUM_SCALAR >
103 if (this != &source) {
104 DAGmodel::operator=(std::move(source));
105 GUM_OP_MOV(IBayesNet);
106 }
107 return *this;
108 }
109
110 template < GUM_Numeric GUM_SCALAR >
112 GUM_DESTRUCTOR(IBayesNet)
113 }
114
115 template < GUM_Numeric GUM_SCALAR >
117 Size dim = 0;
118
119 for (auto node: nodes()) {
120 Size q = 1;
121
122 for (auto parent: parents(node))
123 q *= variable(parent).domainSize();
124
125 dim += (variable(node).domainSize() - 1) * q;
126 }
127
128 return dim;
129 }
130
131 template < GUM_Numeric GUM_SCALAR >
133 Size res = 0;
134 for (auto node: nodes()) {
135 auto v = variable(node).domainSize();
136 if (v > res) { res = v; }
137 }
138 return res;
139 }
140
141 template < GUM_Numeric GUM_SCALAR >
143 GUM_SCALAR res = 1.0;
144 for (auto node: nodes()) {
145 auto v = cpt(node).min();
146 if (v < res) { res = v; }
148 return res;
149 }
150
151 template < GUM_Numeric GUM_SCALAR >
153 GUM_SCALAR res = 1.0;
154 for (auto node: nodes()) {
155 auto v = cpt(node).max();
156 if (v > res) { res = v; }
157 }
158 return res;
159 }
160
161 template < GUM_Numeric GUM_SCALAR >
163 GUM_SCALAR res = 1.0;
164 for (auto node: nodes()) {
165 auto v = cpt(node).minNonZero();
166 if (v < res) { res = v; }
167 }
168 return res;
169 }
170
171 template < GUM_Numeric GUM_SCALAR >
173 GUM_SCALAR res = 0.0;
174 for (auto node: nodes()) {
175 auto v = cpt(node).maxNonOne();
176 if (v > res) { res = v; }
177 }
178 return res;
179 }
180
181 template < GUM_Numeric GUM_SCALAR >
183 Size usedMem = 0;
184
185 for (auto node: nodes())
186 usedMem += cpt(node).memoryFootprint();
187 return usedMem;
188 }
189
190 template < GUM_Numeric GUM_SCALAR >
192 std::stringstream s;
193 s << std::format("BN{{nodes: {}, arcs: {}, ", size(), dag().sizeArcs());
195 s << "}";
196 return s.str();
197 }
198
199 template < GUM_Numeric GUM_SCALAR >
200 std::string IBayesNet< GUM_SCALAR >::toDot() const {
201 return toDot(dot::DotOptions());
202 }
203
204 template < GUM_Numeric GUM_SCALAR >
205 std::string IBayesNet< GUM_SCALAR >::toDot(const dot::DotOptions& options) const {
206 const auto style = dot::DotStyle::read();
207 dot::DotWriter writer(true, this->propertyWithDefault("name", ""));
208 dot::writePreamble(writer, style, options);
209
210 for (const auto node: nodes()) {
211 const auto& name = variable(node).name();
212 writer.node(name,
214 options.node(node),
215 "",
216 "(" + std::to_string(node) + ") " + name));
217 }
218
219 for (const auto& arc: arcs()) {
220 auto attributes = dot::arcAttributes(options.arc(arc.tail(), arc.head()));
221 dot::addDefaultAttribute(attributes,
222 "tooltip",
223 std::to_string(arc.tail()) + "&nbsp;&rarr;&nbsp;"
224 + std::to_string(arc.head()));
225 dot::addDefaultAttribute(attributes, "fontsize", "10");
226 writer.edge(variable(arc.tail()).name(), variable(arc.head()).name(), attributes);
228
229 return writer.str();
230 }
231
233 /// instantiation
234 /// of the vars)
235 template < GUM_Numeric GUM_SCALAR >
237 auto value = (GUM_SCALAR)1.0;
238
239 GUM_SCALAR tmp;
240
241 for (auto node: nodes()) {
242 if ((tmp = cpt(node)[i]) == (GUM_SCALAR)0) { return (GUM_SCALAR)0; }
243
244 value *= tmp;
246
247 return value;
248 }
249
252 /// of the vars)
253 template < GUM_Numeric GUM_SCALAR >
255 auto value = (GUM_SCALAR)0.0;
256
257 GUM_SCALAR tmp;
258
259 for (auto node: nodes()) {
260 if ((tmp = cpt(node)[i]) == (GUM_SCALAR)0) {
261 return (GUM_SCALAR)(-std::numeric_limits< double >::infinity());
262 }
263
264 value += std::log2(cpt(node)[i]);
265 }
266
267 return value;
268 }
269
270 template < GUM_Numeric GUM_SCALAR >
272 if (size() != from.size()) { return false; }
273
274 if (sizeArcs() != from.sizeArcs()) { return false; }
275
276 for (auto node: nodes()) {
277 const auto& v1 = variable(node);
278 if (!from.exists(v1.name())) { return false; }
279 const auto& v2 = from.variableFromName(v1.name());
280 if (v1 != v2) { return false; }
281 }
282
283 for (auto node: nodes()) {
284 NodeId fromnode = from.idFromName(variable(node).name());
285
286 if (cpt(node).nbrDim() != from.cpt(fromnode).nbrDim()) { return false; }
287
288 if (cpt(node).domainSize() != from.cpt(fromnode).domainSize()) { return false; }
289
290 for (Idx i = 0; i < cpt(node).nbrDim(); ++i) {
291 if (!from.cpt(fromnode).contains(from.variableFromName(cpt(node).variable(i).name()))) {
292 return false;
293 }
294 }
295
296 Instantiation i(cpt(node));
297 Instantiation j(from.cpt(fromnode));
298
300 for (i.setFirst(); !i.end(); i.inc()) {
301 for (Idx indice = 0; indice < cpt(node).nbrDim(); ++indice) {
302 const DiscreteVariable* p = &(i.variable(indice));
303 j.chgVal(j.pos(from.variableFromName(p->name())), i.val(*p));
304 }
305
306 if (cmp(cpt(node).get(i), from.cpt(fromnode).get(j))) { return false; }
307 }
308 }
309
310 return true;
311 }
312
313 template < GUM_Numeric GUM_SCALAR >
314 std::ostream& operator<<(std::ostream& output, const IBayesNet< GUM_SCALAR >& bn) {
315 output << bn.toString();
316 return output;
317 }
318
319 template < GUM_Numeric GUM_SCALAR >
320 std::vector< std::string > IBayesNet< GUM_SCALAR >::check() const {
321 std::vector< std::string > comments;
322
323 const double epsilon = config().epsilonStandard();
324 const double error_epsilon = config().epsilonCoarse();
325
326 // CHECKING domain
327 for (const auto i: nodes())
328 if (variable(i).domainSize() < 2) {
329 std::stringstream s;
330 s << "Variable " << variable(i).name() << ": not consistent (domainSize=1).";
331 comments.push_back(s.str());
332 }
333
334 // CHECKING parameters are probabilities
335 // >0
336 for (const auto i: nodes()) {
337 const auto [amin, minval] = cpt(i).argmin();
338 if (minval < (GUM_SCALAR)0.0) {
339 std::stringstream s;
340 s << "Variable " << variable(i).name() << " : P(" << *(amin.begin()) << ") < 0.0";
341 comments.push_back(s.str());
342 }
343 }
344 // <1
345 for (const auto i: nodes()) {
346 const auto [amax, maxval] = cpt(i).argmax();
347 if (maxval > (GUM_SCALAR)1.0) {
348 std::stringstream s;
349 s << "Variable " << variable(i).name() << " : P(" << *(amax.begin()) << ") > 1.0";
350 comments.push_back(s.str());
351 }
352 }
353
354 // CHECKING distributions sum to 1
355 for (const auto i: nodes()) {
356 const auto p = cpt(i).sumOut({&variable(i)});
357 const auto [amin, minval] = p.argmin();
358 if (minval < (GUM_SCALAR)(1.0 - epsilon)) {
359 std::stringstream s;
360 s << "Variable " << variable(i).name() << " : ";
361 if (!parents(i).empty()) s << "with (at least) parents " << *(amin.begin()) << ", ";
362 s << "the CPT sum to less than 1";
363 if (minval > (GUM_SCALAR)(1.0 - error_epsilon)) s << " (normalization problem ?)";
364 s << ".";
365 comments.push_back(s.str());
366 continue;
367 }
368 const auto [amax, maxval] = p.argmax();
369 if (maxval > (GUM_SCALAR)(1.0 + epsilon)) {
370 std::stringstream s;
371 s << "Variable " << variable(i).name() << " : ";
372 if (!parents(i).empty()) s << "with (at least) parents " << *(amax.begin()) << ", ";
373 s << "the CPT sum to more than 1";
374 if (maxval < (GUM_SCALAR)(1.0 + error_epsilon)) s << " (normalization problem ?)";
375 s << ".";
376 comments.push_back(s.str());
377 }
378 }
379
380 return comments;
381 }
382
383 template < GUM_Numeric GUM_SCALAR >
384 Tensor< GUM_SCALAR > IBayesNet< GUM_SCALAR >::evEq(std::string_view name, double value) const {
385 return Tensor< GUM_SCALAR >::evEq(variableFromName(name), value);
386 }
387
388 template < GUM_Numeric GUM_SCALAR >
389 Tensor< GUM_SCALAR >
390 IBayesNet< GUM_SCALAR >::evIn(std::string_view name, double val1, double val2) const {
391 return Tensor< GUM_SCALAR >::evIn(variableFromName(name), val1, val2);
392 }
393
394 template < GUM_Numeric GUM_SCALAR >
395 Tensor< GUM_SCALAR > IBayesNet< GUM_SCALAR >::evGt(std::string_view name, double val) const {
397 }
398
399 template < GUM_Numeric GUM_SCALAR >
400 Tensor< GUM_SCALAR > IBayesNet< GUM_SCALAR >::evLt(std::string_view name, double val) const {
402 }
403} /* namespace gum */
Class representing the minimal interface for Bayesian network with no numerical data.
and aggregator
const Tensor< GUM_SCALAR > & cpt(NodeId varId) const final
const DiscreteVariable & variable(NodeId id) const override
double epsilonStandard() const noexcept
double epsilonCoarse() const noexcept
The coarse tolerance (key core.epsilonCoarse, 1e-2 by default).
DAGmodel()
Default constructor.
Definition DAGmodel.cpp:49
Size size() const final
DAGmodel & operator=(const DAGmodel &source)
Private copy operator.
Definition DAGmodel.cpp:62
bool exists(NodeId node) const final
Return true if this node exists in this graphical model.
const NodeSet & parents(const NodeId id) const
returns the set of nodes with arc ingoing to a given node
const NodeGraphPart & nodes() const final
Returns a named copy of the internal DAG: each node id is assigned the name of the corresponding vari...
NodeId idFromName(std::string_view name) const override
Returns the NodeId of a variable given its name.
const DiscreteVariable & variableFromName(std::string_view name) const override
Returns a constant reference over a variable given its name.
const DiscreteVariable & variable(NodeId id) const override
Returns a constant reference over a variable given its node id.
Base class for discrete random variable.
void setProperty(std::string_view name, std::string_view value)
Add or change a property of this GraphicalModel.
virtual bool empty() const
Return true if this graphical model is empty.
static std::string spaceCplxToString(double dSize, int dim, Size usedMem)
const std::string & propertyWithDefault(std::string_view name, const std::string &byDefault) const
Class representing the minimal interface for Bayesian network with no numerical data.
Definition IBayesNet.h:79
Tensor< GUM_SCALAR > evGt(std::string_view name, double value) const
GUM_SCALAR minNonZeroParam() const
IBayesNet()
Default constructor.
GUM_SCALAR jointProbability(const Instantiation &i) const
Compute a parameter of the joint probability for the BN (given an instantiation of the vars).
Size dim() const
Returns the dimension (the number of free parameters) in this bayes net.
GUM_SCALAR maxParam() const
std::vector< std::string > check() const
Check if the BayesNet is consistent (variables, CPT).
~IBayesNet() override
Destructor.
Tensor< GUM_SCALAR > evIn(std::string_view name, double val1, double val2) const
Tensor< GUM_SCALAR > evLt(std::string_view name, double value) const
Size memoryFootprint() const
compute the (approximated) footprint in memory of the model (the footprints of CPTs)
Size maxVarDomainSize() const
GUM_SCALAR log2JointProbability(const Instantiation &i) const
Compute a parameter of the log joint probability for the BN (given an instantiation of the vars).
GUM_SCALAR maxNonOneParam() const
std::string toString() const
GUM_SCALAR minParam() const
IBayesNet< GUM_SCALAR > & operator=(const IBayesNet< GUM_SCALAR > &source)
Copy operator.
virtual std::string toDot() const
Tensor< GUM_SCALAR > evEq(std::string_view name, double value) const
bool operator==(const IBayesNet< GUM_SCALAR > &from) const
This operator compares 2 BNs !
virtual const Tensor< GUM_SCALAR > & cpt(NodeId varId) const =0
Returns the CPT of a variable.
Class for assigning/browsing values to tuples of discrete variables.
Instantiation & chgVal(const DiscreteVariable &v, Idx newval)
Assign newval to variable v in the Instantiation.
bool end() const
Returns true if the Instantiation reached the end.
void inc()
Operator increment.
Idx pos(const DiscreteVariable &v) const final
Returns the position of the variable v.
Idx val(Idx i) const
Returns the current value of the variable at position i.
void setFirst()
Assign the first values to the tuple of the Instantiation.
const DiscreteVariable & variable(Idx i) const final
Returns the variable at position i in the tuple.
Idx nbrDim() const final
Returns the number of variables in the Instantiation.
static Tensor< GUM_SCALAR > evEq(const DiscreteVariable &v, double val)
numerical evidence generator
static Tensor< GUM_SCALAR > evGt(const DiscreteVariable &v, double val)
numerical evidence generator
static Tensor< GUM_SCALAR > evIn(const DiscreteVariable &v, double val1, double val2)
numerical evidence generator
static Tensor< GUM_SCALAR > evLt(const DiscreteVariable &v, double val)
numerical evidence generator
const std::string & name() const
returns the name of the variable
The options given to a toDot(const DotOptions&).
Definition dotOptions.h:110
const DotArcOptions * arc(Size tail, Size head) const
the options of the arc from tail to head, or nullptr if none was given for it
const DotNodeOptions * node(Size node) const
the options of a node, or nullptr if none was given for it
Writes a graph in the dot language, statement after statement, in the order of the calls.
Definition dotWriter.h:100
Typed, documented, sectioned configuration singleton read from an .ini content.
The statements common to the graphs drawn with graphviz : preamble, attributes of nodes and arcs.
std::size_t Size
In aGrUM, hashed values are unsigned long int.
Definition types.h:74
Size Idx
Type for indexes.
Definition types.h:79
Size NodeId
Type for node ids.
class for NoisyAND-net implementation as multiDim
class for multiDimNoisyORCompound
class for NoisyOR-net implementation as multiDim
DotAttributes nodeAttributes(const DotStyle &style, const DotNodeOptions *options, std::string_view defaultLabel, std::string_view defaultTooltip)
The attributes of a node : its label and tooltip, and its colors if the options give some.
void writePreamble(DotWriter &writer, const DotStyle &style, const DotOptions &options, std::string_view defaultLabel)
Writes the beginning of a graph, as pyAgrum displays it.
void addDefaultAttribute(DotAttributes &attributes, std::string_view key, std::string_view value)
Adds an attribute at the beginning of the list, unless the list already gives a value for this key : ...
DotAttributes arcAttributes(const DotArcOptions *options)
The attributes of an arc or an edge given by the options : color, penwidth, label,...
gum is the global namespace for all aGrUM entities
Definition agrum.h:46
Configuration & config()
A short name for Configuration::instance() : gum::config().epsilonStandard(). It is not inline so tha...
std::ostream & operator<<(std::ostream &stream, const AVLTree< Val, Cmp > &tree)
display the content of a tree
STL namespace.
or aggregator
Abstract class for generating Conditional Probability Tables.
Indicate whether two elements are (almost) different or not.
Definition utils_misc.h:176
static DotStyle read()
the style of the graphs of the section notebook
Definition dotStyle.cpp:89
Header of the Tensor class.