aGrUM 3.3.2
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
72 namespace dot {
73 class DotOptions;
74 } // namespace dot
75
99 struct GUM_PUBLIC_KTBN KTBNModality {
101 template < std::integral T >
102 KTBNModality(T modality);
103
105 KTBNModality(const char* modality);
106
108 KTBNModality(std::string modality);
109
117 Idx toIndex(const DiscreteVariable& var) const;
118
124 std::string label;
125 };
126
200 template < GUM_Numeric GUM_SCALAR >
201 class KTBN {
202 public:
204 static constexpr int ATEMPORAL = -1;
205
206 // ===========================================================================
208 // ===========================================================================
210
217 explicit KTBN(Size k = 2);
218
220 virtual ~KTBN();
221
223 KTBN(const KTBN< GUM_SCALAR >& source);
224
226 KTBN(KTBN< GUM_SCALAR >&& source) noexcept;
227
229 KTBN< GUM_SCALAR >& operator=(const KTBN< GUM_SCALAR >& source);
230
232 KTBN< GUM_SCALAR >& operator=(KTBN< GUM_SCALAR >&& source) noexcept;
233
235 // ===========================================================================
237 // ===========================================================================
239
241 Size k() const;
242
244 Size size() const;
245
247 Size sizeArcs() const;
248
250 bool empty() const;
251
255 void clear();
256
258 // ===========================================================================
260 // ===========================================================================
262
276 void add(const DiscreteVariable& var, bool temporal = true);
277
280 void add(std::string_view fast_description,
281 bool temporal = true,
282 unsigned int default_nbrmod = 2);
283
285 void addTemporal(const DiscreteVariable& var);
287 void addAtemporal(const DiscreteVariable& var);
288
290 void addTemporal(std::string_view fast_description, unsigned int default_nbrmod = 2);
292 void addAtemporal(std::string_view fast_description, unsigned int default_nbrmod = 2);
293
302 void erase(std::string_view base);
303
314 void changeVariableName(std::string_view oldBase, std::string_view newBase);
315
317 // ===========================================================================
319 // ===========================================================================
321
323 bool exists(std::string_view base) const;
324
326 const std::unordered_set< std::string >& temporalVarNames() const;
327
329 const std::unordered_set< std::string >& atemporalVarNames() const;
330
332 Size nbTemporalVars() const;
333
335 Size nbAtemporalVars() const;
336
338 std::vector< std::pair< std::string, int > > nodes() const;
339
341 std::vector< std::pair< std::string, int > > parents(std::string_view base, int slice) const;
343 std::vector< std::pair< std::string, int > > parents(std::string_view node_name) const;
344
346 std::vector< std::pair< std::string, int > > children(std::string_view base, int slice) const;
348 std::vector< std::pair< std::string, int > > children(std::string_view node_name) const;
349
358 const DiscreteVariable& variable(std::string_view base, int slice) const;
359
362 const DiscreteVariable& variable(std::string_view node_name) const;
363
366 int timeSlice(const DiscreteVariable& var) const;
367
370 std::string baseName(const DiscreteVariable& var) const;
371
373 // ===========================================================================
375 // ===========================================================================
377
394 void addArc(std::string_view tailBase, int tailSlice, std::string_view headBase, int headSlice);
395
401 void addArc(std::string_view tail, std::string_view head);
402
412 void eraseArc(std::string_view tailBase,
413 int tailSlice,
414 std::string_view headBase,
415 int headSlice);
416
419 void eraseArc(std::string_view tail, std::string_view head);
420
422 bool existsArc(std::string_view tailBase,
423 int tailSlice,
424 std::string_view headBase,
425 int headSlice) const;
426
429 bool existsArc(std::string_view tail, std::string_view head) const;
430
432 std::vector< std::pair< std::pair< std::string, int >, std::pair< std::string, int > > >
433 arcs() const;
434
436 // ===========================================================================
438 // ===========================================================================
440
456 const Tensor< GUM_SCALAR >& cpt(std::string_view base, int slice) const;
458 const Tensor< GUM_SCALAR >& cpt(std::string_view node_name) const;
459
498 void fillCPT(std::string_view base,
499 int slice,
500 const std::map< std::pair< std::string, int >, KTBNModality >& parents,
501 const std::vector< GUM_SCALAR >& distribution) const;
502
539 void fillCPT(std::string_view node_name,
540 const std::map< std::variant< std::string, std::pair< std::string, int > >,
542 const std::vector< GUM_SCALAR >& distribution) const;
543
545 void generateCPTs() const;
546
548 void generateCPT(std::string_view base, int slice) const;
550 void generateCPT(std::string_view node_name) const;
551
553 // ===========================================================================
555 // ===========================================================================
557
559 BayesNet< GUM_SCALAR > toBN() const;
560
575 BayesNet< GUM_SCALAR > unroll(Size nbTimeSlices) const;
576
578 // ===========================================================================
580 // ===========================================================================
582
595 void save(std::string_view filename) const;
596
609 static KTBN< GUM_SCALAR > load(std::string_view filename);
610
653 static KTBN< GUM_SCALAR > fromBN(const BayesNet< GUM_SCALAR >& bn,
654 const std::unordered_set< std::string >& atemporalNodes = {},
655 std::vector< std::string >* warnings = nullptr);
656
658 // ===========================================================================
660 // ===========================================================================
662
664 std::string toString() const;
665
667 std::string toDot() const;
668
676 std::string toUnrolledDot(Size T, bool highlightReplicated = false) const;
677
685 std::string
686 toUnrolledDot(Size T, bool highlightReplicated, const dot::DotOptions& options) const;
687
695 std::string bnToDot() const;
696
712 std::string summaryGraph() const;
713
715
716 private:
719
721 BayesNet< GUM_SCALAR > _bn_;
722
724 std::unordered_set< std::string > _temporal_;
725
727 std::unordered_set< std::string > _atemporal_;
728
731 std::string _encode_(std::string_view base, int slice) const;
732
736 std::pair< std::string, int > _decodeName_(std::string_view name) const;
737
741 std::pair< std::string, int > _determineNode_(const std::string& name) const;
742
744 std::vector< std::pair< std::string, int > > _determineNodeSet_(const NodeSet& ids) const;
745
747 NodeId _validateVariable_(std::string_view base, int slice) const;
748
752 void _validateAdd_(const std::string& base, bool temporal) const;
753
756 void _determineNodesFromBN_(const std::unordered_set< std::string >& atemporalNodes,
757 std::vector< std::string >* warnings);
758
763 static std::pair< std::string, bool > _resolveGumFormat_(std::string_view filename);
764
767 std::string _timeSlicesToDot_(const BayesNet< GUM_SCALAR >& bn,
768 bool highlightReplicated,
769 const dot::DotOptions& options) const;
770
772 static std::string _escapeDot_(std::string_view name);
773 };
774
775#ifndef GUM_NO_EXTERN_TEMPLATE_CLASS
776 extern template class GUM_PUBLIC_KTBN KTBN< double >;
777#endif
778
780 template < GUM_Numeric GUM_SCALAR >
781 std::ostream& operator<<(std::ostream& output, const KTBN< GUM_SCALAR >& kdbn);
782
783} // namespace gum
784
785// include the inlined functions if necessary
786#ifndef GUM_NO_INLINE
787# include <agrum/KTBN/KTBN_inl.h>
788#endif /* GUM_NO_INLINE */
789
790#include <agrum/KTBN/KTBN_tpl.h>
791
792#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:370
void clear()
Removes all variables and arcs, keeping the order .
Definition KTBN_tpl.h:205
void addTemporal(const DiscreteVariable &var)
Convenience shortcut for add(var, true).
Definition KTBN_tpl.h:293
const std::unordered_set< std::string > & temporalVarNames() const
Definition KTBN_tpl.h:325
void addAtemporal(const DiscreteVariable &var)
Convenience shortcut for add(var, false).
Definition KTBN_tpl.h:298
BayesNet< GUM_SCALAR > toBN() const
Definition KTBN_tpl.h:693
std::string _timeSlicesToDot_(const BayesNet< GUM_SCALAR > &bn, bool highlightReplicated, const dot::DotOptions &options) const
Renders bn as time-slice-clustered DOT. Shared engine behind toDot() (on _bn_) and toUnrolledDot() (o...
Definition KTBN_tpl.h:1143
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:491
bool empty() const
Definition KTBN_tpl.h:200
std::vector< std::pair< std::pair< std::string, int >, std::pair< std::string, int > > > arcs() const
Definition KTBN_tpl.h:552
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:85
std::vector< std::pair< std::string, int > > nodes() const
Definition KTBN_tpl.h:345
BayesNet< GUM_SCALAR > _bn_
The underlying Bayesian network used as a storage engine for the template.
Definition KTBN.h:721
static KTBN< GUM_SCALAR > load(std::string_view filename)
Loads a k-DBN from a GUM file produced by save().
Definition KTBN_tpl.h:825
void erase(std::string_view base)
Removes a variable and all its incident arcs.
Definition KTBN_tpl.h:383
const DiscreteVariable & variable(std::string_view base, int slice) const
Returns the gum::DiscreteVariable of a (process, slice) couple.
Definition KTBN_tpl.h:463
std::string summaryGraph() const
Returns the Graphviz DOT string of the summary graph: the projection of the transition kernel alone (...
Definition KTBN_tpl.h:1228
bool existsArc(std::string_view tailBase, int tailSlice, std::string_view headBase, int headSlice) const
Definition KTBN_tpl.h:521
void save(std::string_view filename) const
Saves the template in the GUM format (text .jgum or binary .bgum).
Definition KTBN_tpl.h:797
static std::string _escapeDot_(std::string_view name)
Escapes double quotes for a DOT identifier or label. Used by summaryGraph().
Definition KTBN_tpl.h:1212
NodeId _validateVariable_(std::string_view base, int slice) const
Resolves and validates a (base, slice) endpoint into its NodeId.
Definition KTBN_tpl.h:435
std::unordered_set< std::string > _temporal_
Base names of the registered temporal processes.
Definition KTBN.h:724
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:513
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:357
const std::unordered_set< std::string > & atemporalVarNames() const
Definition KTBN_tpl.h:330
void generateCPT(std::string_view base, int slice) const
Randomly generates the CPT of a single node.
Definition KTBN_tpl.h:584
Size nbAtemporalVars() const
Definition KTBN_tpl.h:340
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:79
const Tensor< GUM_SCALAR > & cpt(std::string_view base, int slice) const
Returns the CPT of a (process, slice) couple.
Definition KTBN_tpl.h:567
void generateCPTs() const
Randomly generates every CPT of the template.
Definition KTBN_tpl.h:579
std::unordered_set< std::string > _atemporal_
Base names of the registered atemporal variables.
Definition KTBN.h:727
std::string baseName(const DiscreteVariable &var) const
Returns the base name (without bracket encoding) of var.
Definition KTBN_tpl.h:481
static constexpr int ATEMPORAL
Conventional time-slice value denoting an atemporal (static) variable.
Definition KTBN.h:204
Size sizeArcs() const
Definition KTBN_tpl.h:195
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:1125
std::string bnToDot() const
Returns the Graphviz DOT string of the underlying storage BayesNet.
Definition KTBN_tpl.h:1223
KTBN< GUM_SCALAR > & operator=(const KTBN< GUM_SCALAR > &source)
Copy assignment operator.
Definition KTBN_tpl.h:157
int timeSlice(const DiscreteVariable &var) const
The time slice of var, or ATEMPORAL if it is atemporal.
Definition KTBN_tpl.h:475
void changeVariableName(std::string_view oldBase, std::string_view newBase)
Renames a variable (temporal process or atemporal variable).
Definition KTBN_tpl.h:399
std::string toDot() const
Returns a Graphviz DOT string with one cluster per time slice.
Definition KTBN_tpl.h:1120
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:110
BayesNet< GUM_SCALAR > unroll(Size nbTimeSlices) const
Unrolls the k-DBN into a standard gum::BayesNet.
Definition KTBN_tpl.h:698
KTBN(Size k=2)
Default constructor.
Definition KTBN_tpl.h:132
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:595
Size _k_
The order (number of time slices in the template).
Definition KTBN.h:718
Size nbTemporalVars() const
Definition KTBN_tpl.h:335
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:119
bool exists(std::string_view base) const
Definition KTBN_tpl.h:319
void _validateAdd_(const std::string &base, bool temporal) const
Checks that a variable named base can be added.
Definition KTBN_tpl.h:216
Size size() const
Definition KTBN_tpl.h:190
std::string toString() const
Definition KTBN_tpl.h:1085
void add(const DiscreteVariable &var, bool temporal=true)
Adds a variable to the k-DBN.
Definition KTBN_tpl.h:265
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:787
Size k() const
Definition KTBN_tpl.h:185
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:881
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:891
The options given to a toDot(const DotOptions&).
Definition dotOptions.h:110
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:99
Idx index
The index, when isLabel is false.
Definition KTBN.h:122
std::string label
The label, when isLabel is true.
Definition KTBN.h:124
bool isLabel
Whether the value was spelled as a label rather than an index.
Definition KTBN.h:120
KTBNModality(T modality)
From a modality index.
Definition KTBN_tpl.h:72
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.