aGrUM 3.2.0
a C++ library for (probabilistic) graphical models
KTBN.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
53#ifndef GUM_KTBN_H
54#define GUM_KTBN_H
55
56#include <concepts>
57#include <map>
58#include <memory>
59#include <string>
60#include <utility>
61#include <variant>
62#include <vector>
63
64#include <agrum/agrum.h>
65
66#include <agrum/BN/BayesNet.h>
67
68#include <unordered_set>
69
70namespace gum {
71
95 struct GUM_PUBLIC_KTBN KTBNModality {
97 template < std::integral T >
98 KTBNModality(T modality);
99
101 KTBNModality(const char* modality);
102
104 KTBNModality(std::string modality);
105
113 Idx toIndex(const DiscreteVariable& var) const;
114
120 std::string label;
121 };
122
196 template < GUM_Numeric GUM_SCALAR >
197 class KTBN {
198 public:
200 static constexpr int ATEMPORAL = -1;
201
202 // ===========================================================================
204 // ===========================================================================
206
213 explicit KTBN(Size k = 2);
214
216 virtual ~KTBN();
217
219 KTBN(const KTBN< GUM_SCALAR >& source);
220
222 KTBN(KTBN< GUM_SCALAR >&& source) noexcept;
223
225 KTBN< GUM_SCALAR >& operator=(const KTBN< GUM_SCALAR >& source);
226
228 KTBN< GUM_SCALAR >& operator=(KTBN< GUM_SCALAR >&& source) noexcept;
229
231 // ===========================================================================
233 // ===========================================================================
235
237 Size k() const;
238
240 Size size() const;
241
243 Size sizeArcs() const;
244
246 bool empty() const;
247
251 void clear();
252
254 // ===========================================================================
256 // ===========================================================================
258
272 void add(const DiscreteVariable& var, bool temporal = true);
273
276 void add(std::string_view fast_description,
277 bool temporal = true,
278 unsigned int default_nbrmod = 2);
279
281 void addTemporal(const DiscreteVariable& var);
283 void addAtemporal(const DiscreteVariable& var);
284
286 void addTemporal(std::string_view fast_description, unsigned int default_nbrmod = 2);
288 void addAtemporal(std::string_view fast_description, unsigned int default_nbrmod = 2);
289
298 void erase(std::string_view base);
299
310 void changeVariableName(std::string_view oldBase, std::string_view newBase);
311
313 // ===========================================================================
315 // ===========================================================================
317
319 bool exists(std::string_view base) const;
320
322 const std::unordered_set< std::string >& temporalVarNames() const;
323
325 const std::unordered_set< std::string >& atemporalVarNames() const;
326
328 Size nbTemporalVars() const;
329
331 Size nbAtemporalVars() const;
332
334 std::vector< std::pair< std::string, int > > nodes() const;
335
337 std::vector< std::pair< std::string, int > > parents(std::string_view base, int slice) const;
339 std::vector< std::pair< std::string, int > > parents(std::string_view node_name) const;
340
342 std::vector< std::pair< std::string, int > > children(std::string_view base, int slice) const;
344 std::vector< std::pair< std::string, int > > children(std::string_view node_name) const;
345
354 const DiscreteVariable& variable(std::string_view base, int slice) const;
355
358 const DiscreteVariable& variable(std::string_view node_name) const;
359
362 int timeSlice(const DiscreteVariable& var) const;
363
366 std::string baseName(const DiscreteVariable& var) const;
367
369 // ===========================================================================
371 // ===========================================================================
373
390 void addArc(std::string_view tailBase, int tailSlice, std::string_view headBase, int headSlice);
391
397 void addArc(std::string_view tail, std::string_view head);
398
408 void eraseArc(std::string_view tailBase,
409 int tailSlice,
410 std::string_view headBase,
411 int headSlice);
412
415 void eraseArc(std::string_view tail, std::string_view head);
416
418 bool existsArc(std::string_view tailBase,
419 int tailSlice,
420 std::string_view headBase,
421 int headSlice) const;
422
425 bool existsArc(std::string_view tail, std::string_view head) const;
426
428 std::vector< std::pair< std::pair< std::string, int >, std::pair< std::string, int > > >
429 arcs() const;
430
432 // ===========================================================================
434 // ===========================================================================
436
452 const Tensor< GUM_SCALAR >& cpt(std::string_view base, int slice) const;
454 const Tensor< GUM_SCALAR >& cpt(std::string_view node_name) const;
455
494 void fillCPT(std::string_view base,
495 int slice,
496 const std::map< std::pair< std::string, int >, KTBNModality >& parents,
497 const std::vector< GUM_SCALAR >& distribution) const;
498
535 void fillCPT(std::string_view node_name,
536 const std::map< std::variant< std::string, std::pair< std::string, int > >,
538 const std::vector< GUM_SCALAR >& distribution) const;
539
541 void generateCPTs() const;
542
544 void generateCPT(std::string_view base, int slice) const;
546 void generateCPT(std::string_view node_name) const;
547
549 // ===========================================================================
551 // ===========================================================================
553
555 BayesNet< GUM_SCALAR > toBN() const;
556
571 BayesNet< GUM_SCALAR > unroll(Size nbTimeSlices) const;
572
574 // ===========================================================================
576 // ===========================================================================
578
591 void save(std::string_view filename) const;
592
605 static KTBN< GUM_SCALAR > load(std::string_view filename);
606
649 static KTBN< GUM_SCALAR > fromBN(const BayesNet< GUM_SCALAR >& bn,
650 const std::unordered_set< std::string >& atemporalNodes = {},
651 std::vector< std::string >* warnings = nullptr);
652
654 // ===========================================================================
656 // ===========================================================================
658
660 std::string toString() const;
661
663 std::string toDot() const;
664
672 std::string toUnrolledDot(Size T, bool highlightReplicated = false) const;
673
681 std::string bnToDot() const;
682
698 std::string summaryGraph() const;
699
701
702 private:
705
707 BayesNet< GUM_SCALAR > _bn_;
708
710 std::unordered_set< std::string > _temporal_;
711
713 std::unordered_set< std::string > _atemporal_;
714
717 std::string _encode_(std::string_view base, int slice) const;
718
722 std::pair< std::string, int > _decodeName_(std::string_view name) const;
723
727 std::pair< std::string, int > _determineNode_(const std::string& name) const;
728
730 std::vector< std::pair< std::string, int > > _determineNodeSet_(const NodeSet& ids) const;
731
733 NodeId _validateVariable_(std::string_view base, int slice) const;
734
738 void _validateAdd_(const std::string& base, bool temporal) const;
739
742 void _determineNodesFromBN_(const std::unordered_set< std::string >& atemporalNodes,
743 std::vector< std::string >* warnings);
744
749 static std::pair< std::string, bool > _resolveGumFormat_(std::string_view filename);
750
753 std::string _timeSlicesToDot_(const BayesNet< GUM_SCALAR >& bn, bool highlightReplicated) const;
754
757 static std::string _escapeDot_(std::string_view name);
758 };
759
760#ifndef GUM_NO_EXTERN_TEMPLATE_CLASS
761 extern template class GUM_PUBLIC_KTBN KTBN< double >;
762#endif
763
765 template < GUM_Numeric GUM_SCALAR >
766 std::ostream& operator<<(std::ostream& output, const KTBN< GUM_SCALAR >& kdbn);
767
768} // namespace gum
769
770// include the inlined functions if necessary
771#ifndef GUM_NO_INLINE
772# include <agrum/KTBN/KTBN_inl.h>
773#endif /* GUM_NO_INLINE */
774
775#include <agrum/KTBN/KTBN_tpl.h>
776
777#endif /* GUM_KTBN_H */
Class representing Bayesian networks.
Inline implementations of gum::KTBNModality's non-template members.
Template implementation of the gum::KTBN class.
Base class for discrete random variable.
std::vector< std::pair< std::string, int > > children(std::string_view base, int slice) const
Children of a node as (base, slice) pairs (ATEMPORAL if atemporal).
Definition KTBN_tpl.h:369
void clear()
Removes all variables and arcs, keeping the order .
Definition KTBN_tpl.h:204
void addTemporal(const DiscreteVariable &var)
Convenience shortcut for add(var, true).
Definition KTBN_tpl.h:292
const std::unordered_set< std::string > & temporalVarNames() const
Definition KTBN_tpl.h:324
void addAtemporal(const DiscreteVariable &var)
Convenience shortcut for add(var, false).
Definition KTBN_tpl.h:297
BayesNet< GUM_SCALAR > toBN() const
Definition KTBN_tpl.h:692
void addArc(std::string_view tailBase, int tailSlice, std::string_view headBase, int headSlice)
Adds an arc between two (process, slice) endpoints.
Definition KTBN_tpl.h:490
bool empty() const
Definition KTBN_tpl.h:199
std::vector< std::pair< std::pair< std::string, int >, std::pair< std::string, int > > > arcs() const
Definition KTBN_tpl.h:551
std::pair< std::string, int > _decodeName_(std::string_view name) const
Purely syntactic parse of an engine name → (base, slice). Slice is ATEMPORAL when there is no [digits...
Definition KTBN_tpl.h:84
std::vector< std::pair< std::string, int > > nodes() const
Definition KTBN_tpl.h:344
BayesNet< GUM_SCALAR > _bn_
The underlying Bayesian network used as a storage engine for the template.
Definition KTBN.h:707
static KTBN< GUM_SCALAR > load(std::string_view filename)
Loads a k-DBN from a GUM file produced by save().
Definition KTBN_tpl.h:824
void erase(std::string_view base)
Removes a variable and all its incident arcs.
Definition KTBN_tpl.h:382
const DiscreteVariable & variable(std::string_view base, int slice) const
Returns the gum::DiscreteVariable of a (process, slice) couple.
Definition KTBN_tpl.h:462
std::string summaryGraph() const
Returns the Graphviz DOT string of the summary graph: the projection of the transition kernel alone (...
Definition KTBN_tpl.h:1219
bool existsArc(std::string_view tailBase, int tailSlice, std::string_view headBase, int headSlice) const
Definition KTBN_tpl.h:520
void save(std::string_view filename) const
Saves the template in the GUM format (text .jgum or binary .bgum).
Definition KTBN_tpl.h:796
static std::string _escapeDot_(std::string_view name)
Escapes double quotes for a DOT identifier or label. Shared by timeSlicesToDot() and summaryGraph().
Definition KTBN_tpl.h:1131
NodeId _validateVariable_(std::string_view base, int slice) const
Resolves and validates a (base, slice) endpoint into its NodeId.
Definition KTBN_tpl.h:434
std::unordered_set< std::string > _temporal_
Base names of the registered temporal processes.
Definition KTBN.h:710
void eraseArc(std::string_view tailBase, int tailSlice, std::string_view headBase, int headSlice)
Removes an arc between two (process, slice) endpoints.
Definition KTBN_tpl.h:512
std::vector< std::pair< std::string, int > > parents(std::string_view base, int slice) const
Parents of a node as (base, slice) pairs (ATEMPORAL if atemporal).
Definition KTBN_tpl.h:356
const std::unordered_set< std::string > & atemporalVarNames() const
Definition KTBN_tpl.h:329
void generateCPT(std::string_view base, int slice) const
Randomly generates the CPT of a single node.
Definition KTBN_tpl.h:583
Size nbAtemporalVars() const
Definition KTBN_tpl.h:339
std::string _encode_(std::string_view base, int slice) const
Encodes (base, slice) → engine name: base[t], or base if atemporal.
Definition KTBN_tpl.h:78
const Tensor< GUM_SCALAR > & cpt(std::string_view base, int slice) const
Returns the CPT of a (process, slice) couple.
Definition KTBN_tpl.h:566
void generateCPTs() const
Randomly generates every CPT of the template.
Definition KTBN_tpl.h:578
std::unordered_set< std::string > _atemporal_
Base names of the registered atemporal variables.
Definition KTBN.h:713
std::string baseName(const DiscreteVariable &var) const
Returns the base name (without bracket encoding) of var.
Definition KTBN_tpl.h:480
static constexpr int ATEMPORAL
Conventional time-slice value denoting an atemporal (static) variable.
Definition KTBN.h:200
Size sizeArcs() const
Definition KTBN_tpl.h:194
std::string toUnrolledDot(Size T, bool highlightReplicated=false) const
Returns a Graphviz DOT string of the k-DBN unrolled over T time slices.
Definition KTBN_tpl.h:1124
std::string bnToDot() const
Returns the Graphviz DOT string of the underlying storage BayesNet.
Definition KTBN_tpl.h:1214
KTBN< GUM_SCALAR > & operator=(const KTBN< GUM_SCALAR > &source)
Copy assignment operator.
Definition KTBN_tpl.h:156
int timeSlice(const DiscreteVariable &var) const
The time slice of var, or ATEMPORAL if it is atemporal.
Definition KTBN_tpl.h:474
void changeVariableName(std::string_view oldBase, std::string_view newBase)
Renames a variable (temporal process or atemporal variable).
Definition KTBN_tpl.h:398
std::string toDot() const
Returns a Graphviz DOT string with one cluster per time slice.
Definition KTBN_tpl.h:1119
std::pair< std::string, int > _determineNode_(const std::string &name) const
Cache-aware classification of a node name → (base, slice): nodes registered in _atemporal_ (atemporal...
Definition KTBN_tpl.h:109
BayesNet< GUM_SCALAR > unroll(Size nbTimeSlices) const
Unrolls the k-DBN into a standard gum::BayesNet.
Definition KTBN_tpl.h:697
KTBN(Size k=2)
Default constructor.
Definition KTBN_tpl.h:131
void fillCPT(std::string_view base, int slice, const std::map< std::pair< std::string, int >, KTBNModality > &parents, const std::vector< GUM_SCALAR > &distribution) const
Fills one conditional distribution P(node | parent configuration).
Definition KTBN_tpl.h:594
std::string _timeSlicesToDot_(const BayesNet< GUM_SCALAR > &bn, bool highlightReplicated) const
Renders bn as time-slice-clustered DOT. Shared engine behind toDot() (on _bn_) and toUnrolledDot() (o...
Definition KTBN_tpl.h:1146
Size _k_
The order (number of time slices in the template).
Definition KTBN.h:704
Size nbTemporalVars() const
Definition KTBN_tpl.h:334
std::vector< std::pair< std::string, int > > _determineNodeSet_(const NodeSet &ids) const
Maps a set of node ids to (base, slice) pairs (via determineNode).
Definition KTBN_tpl.h:118
bool exists(std::string_view base) const
Definition KTBN_tpl.h:318
void _validateAdd_(const std::string &base, bool temporal) const
Checks that a variable named base can be added.
Definition KTBN_tpl.h:215
Size size() const
Definition KTBN_tpl.h:189
std::string toString() const
Definition KTBN_tpl.h:1084
void add(const DiscreteVariable &var, bool temporal=true)
Adds a variable to the k-DBN.
Definition KTBN_tpl.h:264
static std::pair< std::string, bool > _resolveGumFormat_(std::string_view filename)
Resolves a user filename to (filepath, binary): ensures a .jgum/.bgum extension (....
Definition KTBN_tpl.h:786
Size k() const
Definition KTBN_tpl.h:184
static KTBN< GUM_SCALAR > fromBN(const BayesNet< GUM_SCALAR > &bn, const std::unordered_set< std::string > &atemporalNodes={}, std::vector< std::string > *warnings=nullptr)
Builds a k-DBN from an existing gum::BayesNet, reading its node names under one of two mutually exclu...
Definition KTBN_tpl.h:880
void _determineNodesFromBN_(const std::unordered_set< std::string > &atemporalNodes, std::vector< std::string > *warnings)
Rebuilds the cached name sets from the storage engine content (used by fromBN()/load(); decodes names...
Definition KTBN_tpl.h:890
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.
Set< NodeId > NodeSet
Some typdefs and define for shortcuts ...
gum is the global namespace for all aGrUM entities
Definition agrum.h:46
std::ostream & operator<<(std::ostream &stream, const AVLTree< Val, Cmp > &tree)
display the content of a tree
template class GUM_PUBLIC_KTBN KTBN< double >
Definition KTBN.cpp:53
A parent's value in gum::KTBN::fillCPT(): a modality index or a modality label.
Definition KTBN.h:95
Idx index
The index, when isLabel is false.
Definition KTBN.h:118
std::string label
The label, when isLabel is true.
Definition KTBN.h:120
bool isLabel
Whether the value was spelled as a label rather than an index.
Definition KTBN.h:116
KTBNModality(T modality)
From a modality index.
Definition KTBN_tpl.h:71
KTBNModality(const char *modality)
From a modality label.
KTBNModality(std::string modality)
From a modality label.
Idx toIndex(const DiscreteVariable &var) const
Resolves this value to a modality index of var, looking the label up when one was given.