aGrUM 3.3.2
a C++ library for (probabilistic) graphical models
BayesNetFragment_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
52#include <agrum/BN/BayesNet.h>
54
55namespace gum {
56 template < GUM_Numeric GUM_SCALAR >
61
62 template < GUM_Numeric GUM_SCALAR >
64 GUM_DESTRUCTOR(BayesNetFragment)
65
66 for (auto node: nodes())
67 if (_localCPTs_.exists(node)) uninstallCPT_(node);
68 }
69
70 //============================================================
71 // signals to keep consistency with the referred BayesNet
72 template < GUM_Numeric GUM_SCALAR >
74 // nothing to do
75 }
76
77 template < GUM_Numeric GUM_SCALAR >
81
82 template < GUM_Numeric GUM_SCALAR >
84 // nothing to do
85 }
86
87 template < GUM_Numeric GUM_SCALAR >
89 if (this->internalDag().existsArc(from, to)) uninstallArc_(from, to);
90 }
91
92 //============================================================
93 // IBayesNet interface : BayesNetFragment here is a decorator for the bn
94
95 template < GUM_Numeric GUM_SCALAR >
96 const Tensor< GUM_SCALAR >& BayesNetFragment< GUM_SCALAR >::cpt(NodeId id) const {
97 if (!isInstalledNode(id)) GUM_ERROR(NotFound, "NodeId " << id << " is not installed")
98
99 if (_localCPTs_.exists(id)) return *_localCPTs_[id];
100 else return _bn_.cpt(id);
101 }
102
103 template < GUM_Numeric GUM_SCALAR >
105 return this->_bn_.variableNodeMap();
106 }
107
108 template < GUM_Numeric GUM_SCALAR >
110 if (!isInstalledNode(id)) GUM_ERROR(NotFound, "NodeId " << id << " is not installed")
111
112 return _bn_.variable(id);
113 }
114
115 template < GUM_Numeric GUM_SCALAR >
117 NodeId id = _bn_.nodeId(var);
118
119 if (!isInstalledNode(id)) GUM_ERROR(NotFound, "variable " << var.name() << " is not installed")
120
121 return id;
122 }
123
124 template < GUM_Numeric GUM_SCALAR >
126 NodeId id = _bn_.idFromName(name);
127
128 if (!isInstalledNode(id)) GUM_ERROR(NotFound, "variable " << name << " is not installed")
129
130 return id;
131 }
132
133 template < GUM_Numeric GUM_SCALAR >
134 const DiscreteVariable&
136 NodeId id = idFromName(name);
137
138 if (!isInstalledNode(id)) GUM_ERROR(NotFound, "variable " << name << " is not installed")
139
140 return _bn_.variable(id);
141 }
142
143 //============================================================
144 // specific API for BayesNetFragment
145 template < GUM_Numeric GUM_SCALAR >
147 return this->internalDag().existsNode(id);
148 }
149
150 template < GUM_Numeric GUM_SCALAR >
152 if (!_bn_.internalDag().existsNode(id))
153 GUM_ERROR(NotFound, "Node " << id << " does not exist in referred BayesNet")
154
155 if (!isInstalledNode(id)) {
156 this->dag_.addNodeWithId(id);
157
158 // adding arcs with id as a tail
159 for (auto pa: this->_bn_.parents(id)) {
160 if (isInstalledNode(pa)) this->dag_.addArc(pa, id);
161 }
162
163 // adding arcs with id as a head
164 for (auto son: this->_bn_.children(id))
165 if (isInstalledNode(son)) this->dag_.addArc(id, son);
166 }
167 }
168
169 template < GUM_Numeric GUM_SCALAR >
171 installNode(id);
172
173 // bn is a dag => this will have an end ...
174 for (auto pa: this->_bn_.parents(id))
176 }
177
178 template < GUM_Numeric GUM_SCALAR >
180 if (isInstalledNode(id)) {
181 uninstallCPT(id);
182 this->dag_.eraseNode(id);
183 }
184 }
185
186 template < GUM_Numeric GUM_SCALAR >
188 this->dag_.eraseArc(Arc(from, to));
189 }
190
191 template < GUM_Numeric GUM_SCALAR >
193 this->dag_.addArc(from, to);
194 }
195
196 template < GUM_Numeric GUM_SCALAR >
197 void BayesNetFragment< GUM_SCALAR >::installCPT_(NodeId id, const Tensor< GUM_SCALAR >& pot) {
198 // topology
199 const auto& parents = this->parents(id);
200 for (auto node_it = parents.beginSafe(); node_it != parents.endSafe();
201 ++node_it) // safe iterator needed here
202 uninstallArc_(*node_it, id);
203
204 for (Idx i = 1; i < pot.nbrDim(); i++) {
205 NodeId parent = _bn_.idFromName(pot.variable(i).name());
206
207 if (isInstalledNode(parent)) installArc_(parent, id);
208 }
209
210 // local cpt
211 if (_localCPTs_.exists(id)) uninstallCPT_(id);
212
213 _localCPTs_.insert(id, new gum::Tensor< GUM_SCALAR >(pot));
214 }
215
216 template < GUM_Numeric GUM_SCALAR >
217 void BayesNetFragment< GUM_SCALAR >::installCPT(NodeId id, const Tensor< GUM_SCALAR >& pot) {
218 if (!this->internalDag().existsNode(id))
219 GUM_ERROR(NotFound, "Node " << id << " is not installed in the fragment")
220
221 if (&(pot.variable(0)) != &(variable(id))) {
223 "The tensor is not a marginal for _bn_.variable <" << variable(id).name() << ">")
224 }
225
226 const NodeSet& parents = _bn_.parents(id);
227
228 for (Idx i = 1; i < pot.nbrDim(); i++) {
229 if (!parents.contains(_bn_.idFromName(pot.variable(i).name())))
231 "Variable <" << pot.variable(i).name() << "> is not in the parents of node "
232 << id)
233 }
234
235 installCPT_(id, pot);
236 }
237
238 template < GUM_Numeric GUM_SCALAR >
240 delete _localCPTs_[id];
241 _localCPTs_.erase(id);
242 }
243
244 template < GUM_Numeric GUM_SCALAR >
246 if (_localCPTs_.exists(id)) {
247 uninstallCPT_(id);
248
249 // re-create arcs from referred tensor
250 const Tensor< GUM_SCALAR >& pot = cpt(id);
251
252 for (Idx i = 1; i < pot.nbrDim(); i++) {
253 NodeId parent = _bn_.idFromName(pot.variable(i).name());
254
255 if (isInstalledNode(parent)) installArc_(parent, id);
256 }
257 }
258 }
259
260 template < GUM_Numeric GUM_SCALAR >
261 void BayesNetFragment< GUM_SCALAR >::installMarginal(NodeId id, const Tensor< GUM_SCALAR >& pot) {
262 if (!isInstalledNode(id)) {
263 GUM_ERROR(NotFound, "The node " << id << " is not part of this fragment")
264 }
265
266 if (pot.nbrDim() > 1) {
267 GUM_ERROR(OperationNotAllowed, "The tensor is not a marginal :" << pot)
268 }
269
270 if (&(pot.variable(0)) != &(_bn_.variable(id))) {
272 "The tensor is not a marginal for _bn_.variable <" << _bn_.variable(id).name()
273 << ">")
274 }
275
276 installCPT_(id, pot);
277 }
278
279 template < GUM_Numeric GUM_SCALAR >
281 if (!isInstalledNode(id))
282 GUM_ERROR(NotFound, "The node " << id << " is not part of this fragment")
283
284 const auto& node_cpt = this->cpt(id);
285 NodeSet cpt_parents;
286
287 for (Idx i = 1; i < node_cpt.nbrDim(); i++) {
288 cpt_parents.insert(_bn_.idFromName(node_cpt.variable(i).name()));
289 }
290
291 return (this->parents(id) == cpt_parents);
292 }
293
294 template < GUM_Numeric GUM_SCALAR >
296 for (auto node: nodes())
297 if (!checkConsistency(node)) return false;
298
299 return true;
300 }
301
302 template < GUM_Numeric GUM_SCALAR >
303 std::string BayesNetFragment< GUM_SCALAR >::toDot(const dot::DotOptions& options) const {
304 // the colors of the nodes, which tell what they are for the fragment
305 struct NodeColors {
306 const char* fill;
307 const char* border;
308 const char* font;
309 };
310
311 static constexpr NodeColors inFragment{"#ffffaa", "#000000", "#000000"};
312 static constexpr NodeColors withLocalCPT{"#ffddaa", "#000000", "#000000"};
313 static constexpr NodeColors notConsistent{"#ff0000", "#000000", "#ffff00"};
314 static constexpr NodeColors outFragment{"#f0f0f0", "#f0f0f0", "#000000"};
315
316 const auto style = dot::DotStyle::read();
317 const auto title = "Fragment of " + _bn_.propertyWithDefault("name", "no_name");
318 dot::DotWriter writer(true, title);
319 dot::writePreamble(writer, style, options, title);
320
321 for (const auto node: _bn_.nodes()) {
322 const NodeColors* colors = &outFragment;
323 if (isInstalledNode(node)) {
324 if (!checkConsistency(node)) colors = &notConsistent;
325 else if (_localCPTs_.exists(node)) colors = &withLocalCPT;
326 else colors = &inFragment;
327 }
328
329 const auto& name = _bn_.variable(node).name();
330 auto attributes = dot::nodeAttributes(style,
331 options.node(node),
332 "",
333 "(" + std::to_string(node) + ") " + name);
334 dot::addDefaultAttribute(attributes, "fontcolor", colors->font);
335 dot::addDefaultAttribute(attributes, "color", colors->border);
336 dot::addDefaultAttribute(attributes, "fillcolor", colors->fill);
337 writer.node(name, attributes);
338 }
339
340 for (const auto node: _bn_.nodes()) {
341 for (const auto child: _bn_.children(node)) {
342 auto attributes = dot::arcAttributes(options.arc(node, child));
343 dot::addDefaultAttribute(attributes,
344 "tooltip",
345 std::to_string(node) + "&nbsp;&rarr;&nbsp;"
346 + std::to_string(child));
347 dot::addDefaultAttribute(attributes, "fontsize", "10");
348 dot::addDefaultAttribute(attributes,
349 "color",
350 this->internalDag().existsArc(Arc(node, child)) ? "#000000"
351 : "#f0f0f0");
352 writer.edge(_bn_.variable(node).name(), _bn_.variable(child).name(), attributes);
353 }
354 }
355
356 return writer.str();
357 }
358
359 template < GUM_Numeric GUM_SCALAR >
361 if (!checkConsistency()) {
362 GUM_ERROR(OperationNotAllowed, "The fragment contains un-consistent node(s)")
363 }
365 for (const auto nod: nodes()) {
366 res.add(variable(nod), nod);
367 }
368 for (const auto& arc: this->internalDag().arcs()) {
369 res.addArc(arc.tail(), arc.head());
370 }
371 for (const auto nod: nodes()) {
372 res.cpt(nod).fillWith(cpt(nod));
373 }
374
375 return res;
376 }
377
378 template < GUM_Numeric GUM_SCALAR >
379 const Tensor< GUM_SCALAR >& BayesNetFragment< GUM_SCALAR >::cpt(std::string_view name) const {
380 return cpt(idFromName(name));
381 }
382
383 template < GUM_Numeric GUM_SCALAR >
384 const DiscreteVariable& BayesNetFragment< GUM_SCALAR >::variable(std::string_view name) const {
385 return variable(idFromName(name));
386 }
387
388 template < GUM_Numeric GUM_SCALAR >
389 bool BayesNetFragment< GUM_SCALAR >::isInstalledNode(std::string_view name) const {
390 return isInstalledNode(idFromName(name));
391 }
392
393 template < GUM_Numeric GUM_SCALAR >
395 installNode(_bn_.idFromName(name));
396 }
397
398 template < GUM_Numeric GUM_SCALAR >
400 installAscendants(_bn_.idFromName(name));
401 }
402
403 template < GUM_Numeric GUM_SCALAR >
406 }
407
408 template < GUM_Numeric GUM_SCALAR >
410 const Tensor< GUM_SCALAR >& pot) {
411 installMarginal(_bn_.idFromName(name), pot);
412 }
413
414 template < GUM_Numeric GUM_SCALAR >
416 const Tensor< GUM_SCALAR >& pot) {
417 installCPT(_bn_.idFromName(name), pot);
418 }
419
420 template < GUM_Numeric GUM_SCALAR >
423 }
424
425 template < GUM_Numeric GUM_SCALAR >
426 bool BayesNetFragment< GUM_SCALAR >::checkConsistency(std::string_view name) const {
427 return checkConsistency(idFromName(name));
428 }
429
430} // namespace gum
Class representing Fragment of Bayesian networks.
Class representing Bayesian networks.
Arc(NodeId tail, NodeId head)
basic constructor. Creates tail -> head.
void installNode(NodeId id)
install a node referenced by its nodeId
void installMarginal(NodeId id, const Tensor< GUM_SCALAR > &pot)
install a local marginal BY COPY for a node into the fragment.
const DiscreteVariable & variableFromName(std::string_view name) const final
Getter by name.
void uninstallArc_(NodeId from, NodeId to)
void whenNodeDeleted(const void *src, NodeId id) final
the action to take when a node has just been removed from the graph
void installCPT_(NodeId id, const Tensor< GUM_SCALAR > &pot)
const IBayesNet< GUM_SCALAR > & _bn_
The referred BayesNet.
gum::BayesNet< GUM_SCALAR > toBN() const
create a brand new BayesNet from a fragment.
void installArc_(NodeId from, NodeId to)
void whenNodeAdded(const void *src, NodeId id) final
the action to take when a new node is inserted into the graph
void whenArcDeleted(const void *src, NodeId from, NodeId to) final
the action to take when an arc has just been removed from the graph
NodeId idFromName(std::string_view name) const final
Getter by name.
const DiscreteVariable & variable(NodeId id) const final
Returns a constant reference over a variabe given it's node id.
bool isInstalledNode(NodeId id) const
check if a certain NodeId exists in the fragment
void whenArcAdded(const void *src, NodeId from, NodeId to) final
the action to take when a new arc is inserted into the graph
NodeProperty< const Tensor< GUM_SCALAR > * > _localCPTs_
Mapping between the variable's id and their CPT specific to this Fragment.
bool checkConsistency(NodeId id) const
returns true if the nodeId's (local or not) cpt is consistent with its parents in the fragment
void uninstallNode(NodeId id)
uninstall a node referenced by its nodeId
bool checkConsistency() const
returns true if all nodes in the fragment are consistent
void installAscendants(NodeId id)
install a node and all its ascendants
NodeId nodeId(const DiscreteVariable &var) const final
Return id node from discrete var pointer.
void uninstallCPT(NodeId id)
uninstall a local CPT.
const VariableNodeMap & variableNodeMap() const final
Returns a constant reference to the VariableNodeMap of this BN.
const Tensor< GUM_SCALAR > & cpt(NodeId varId) const final
Returns the CPT of a variable.
void uninstallCPT_(NodeId id)
uninstall a local CPT.
void installCPT(NodeId id, const Tensor< GUM_SCALAR > &pot)
install a local cpt BY COPYfor a node into the fragment.
Class representing a Bayesian network.
Definition BayesNet.h:99
const Tensor< GUM_SCALAR > & cpt(NodeId varId) const final
Returns the CPT of a variable.
void addArc(NodeId tail, NodeId head)
Add an arc in the BN, and update arc.head's CPT.
NodeId add(const DiscreteVariable &var)
Add a variable to the gum::BayesNet.
DAG dag_
The DAG of this Directed Graphical Model.
Definition DAGmodel.h:291
const ArcSet & arcs() const
return true if the arc tail->head exists in the DAGmodel
bool existsArc(const NodeId tail, const NodeId head) const
return true if the arc tail->head exists in the DAGmodel
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...
const DAG & internalDag() const
Returns a const reference to the internal (unnamed) DAG. O(1), no copy. Use for stable references or ...
DiGraphListener(const DiGraph *g)
default constructor
Base class for discrete random variable.
IBayesNet()
Default constructor.
virtual std::string toDot() const
Exception : the element we looked for cannot be found.
Exception : operation not allowed.
bool contains(const Key &k) const
Indicates whether a given elements belong to the set.
Definition set_tpl.h:468
void insert(const Key &k)
Inserts a new element into the set.
Definition set_tpl.h:510
aGrUM's Tensor is a multi-dimensional array with tensor operators.
Definition tensor.h:85
Container used to map discrete variables with nodes.
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
void edge(std::string_view from, std::string_view to, const DotAttributes &attributes={})
an edge from from to to (-> in a directed graph, -- in an undirected one).
std::string str() const
The graph written so far, closed. It can be called at any moment, and the writer can be used after.
void node(std::string_view id, const DotAttributes &attributes={})
a node, whose identifier is id (quoted).
The statements common to the graphs drawn with graphviz : preamble, attributes of nodes and arcs.
#define GUM_ERROR(type, msg)
Definition exceptions.h:76
Size Idx
Type for indexes.
Definition types.h:79
Size NodeId
Type for node ids.
Set< NodeId > NodeSet
Some typdefs and define for shortcuts ...
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
static DotStyle read()
the style of the graphs of the section notebook
Definition dotStyle.cpp:89
Header of the Tensor class.