aGrUM 3.3.2
a C++ library for (probabilistic) graphical models
gum::KTBN< GUM_SCALAR > Class Template Reference

Class representing a k-order dynamic Bayesian network (k-DBN). More...

#include <agrum/KTBN/KTBN.h>

Public Member Functions

Constructors and Destructor
 KTBN (Size k=2)
 Default constructor.
virtual ~KTBN ()
 Destructor.
 KTBN (const KTBN< GUM_SCALAR > &source)
 Copy constructor.
 KTBN (KTBN< GUM_SCALAR > &&source) noexcept
 Move constructor.
KTBN< GUM_SCALAR > & operator= (const KTBN< GUM_SCALAR > &source)
 Copy assignment operator.
KTBN< GUM_SCALAR > & operator= (KTBN< GUM_SCALAR > &&source) noexcept
 Move assignment operator.
Accessors
Size k () const
Size size () const
Size sizeArcs () const
bool empty () const
void clear ()
 Removes all variables and arcs, keeping the order \(k\).
Variable management
void add (const DiscreteVariable &var, bool temporal=true)
 Adds a variable to the k-DBN.
void add (std::string_view fast_description, bool temporal=true, unsigned int default_nbrmod=2)
 Adds a variable using the "fast" textual description syntax.
void addTemporal (const DiscreteVariable &var)
 Convenience shortcut for add(var, true).
void addAtemporal (const DiscreteVariable &var)
 Convenience shortcut for add(var, false).
void addTemporal (std::string_view fast_description, unsigned int default_nbrmod=2)
 Convenience shortcut for add(fast_description, true, default_nbrmod).
void addAtemporal (std::string_view fast_description, unsigned int default_nbrmod=2)
 Convenience shortcut for add(fast_description, false, default_nbrmod).
void erase (std::string_view base)
 Removes a variable and all its incident arcs.
void changeVariableName (std::string_view oldBase, std::string_view newBase)
 Renames a variable (temporal process or atemporal variable).
Variable queries
bool exists (std::string_view base) const
const std::unordered_set< std::string > & temporalVarNames () const
const std::unordered_set< std::string > & atemporalVarNames () const
Size nbTemporalVars () const
Size nbAtemporalVars () const
std::vector< std::pair< std::string, int > > nodes () const
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).
std::vector< std::pair< std::string, int > > parents (std::string_view node_name) const
 Returns the parents using an engine name ("X[1]", "C", …).
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).
std::vector< std::pair< std::string, int > > children (std::string_view node_name) const
 Returns the children using an engine name ("X[1]", "C", …).
const DiscreteVariable & variable (std::string_view base, int slice) const
 Returns the gum::DiscreteVariable of a (process, slice) couple.
const DiscreteVariable & variable (std::string_view node_name) const
 Same, using an engine name: resolved via _determineNode_, so "X[1]" and bare "C" are both accepted.
int timeSlice (const DiscreteVariable &var) const
 The time slice of var, or ATEMPORAL if it is atemporal.
std::string baseName (const DiscreteVariable &var) const
 Returns the base name (without bracket encoding) of var.
Arc management
void addArc (std::string_view tailBase, int tailSlice, std::string_view headBase, int headSlice)
 Adds an arc between two (process, slice) endpoints.
void addArc (std::string_view tail, std::string_view head)
 Adds an arc using internal engine names (bracket notation: "X[0]", "C", …).
void eraseArc (std::string_view tailBase, int tailSlice, std::string_view headBase, int headSlice)
 Removes an arc between two (process, slice) endpoints.
void eraseArc (std::string_view tail, std::string_view head)
 Removes an arc using internal engine names (bracket notation).
bool existsArc (std::string_view tailBase, int tailSlice, std::string_view headBase, int headSlice) const
bool existsArc (std::string_view tail, std::string_view head) const
std::vector< std::pair< std::pair< std::string, int >, std::pair< std::string, int > > > arcs () const
Conditional probability tables
const Tensor< GUM_SCALAR > & cpt (std::string_view base, int slice) const
 Returns the CPT of a (process, slice) couple.
const Tensor< GUM_SCALAR > & cpt (std::string_view node_name) const
 Returns the CPT using an engine name ("X[1]", "C", …).
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).
void fillCPT (std::string_view node_name, const std::map< std::variant< std::string, std::pair< std::string, int > >, KTBNModality > &parents, const std::vector< GUM_SCALAR > &distribution) const
 Fills one conditional distribution using internal bracket-notation engine name for the target node — the bracket notation visible in toDot() and toString(): "X[t]" for a temporal variable at slice t, and the bare variable name for an atemporal variable (e.g.
void generateCPTs () const
 Randomly generates every CPT of the template.
void generateCPT (std::string_view base, int slice) const
 Randomly generates the CPT of a single node.
void generateCPT (std::string_view node_name) const
 Same, using an engine name ("X[1]", "C", …).
Transformations
BayesNet< GUM_SCALAR > toBN () const
BayesNet< GUM_SCALAR > unroll (Size nbTimeSlices) const
 Unrolls the k-DBN into a standard gum::BayesNet.
Various
std::string toString () const
std::string toDot () const
 Returns a Graphviz DOT string with one cluster per time slice.
std::string toUnrolledDot (Size T, bool highlightReplicated=false) const
 Returns a Graphviz DOT string of the k-DBN unrolled over T time slices.
std::string toUnrolledDot (Size T, bool highlightReplicated, const dot::DotOptions &options) const
 Returns a Graphviz DOT string of the k-DBN unrolled over T time slices, with the options given by the caller (the look is the one of the section dynamicBN of the configuration : size of the graph, colors of the clusters).
std::string bnToDot () const
 Returns the Graphviz DOT string of the underlying storage BayesNet.
std::string summaryGraph () const
 Returns the Graphviz DOT string of the summary graph: the projection of the transition kernel alone (the pattern that actually repeats through time when unrolling), not the whole template.

Static Public Attributes

static constexpr int ATEMPORAL = -1
 Conventional time-slice value denoting an atemporal (static) variable.

Private Member Functions

std::string _encode_ (std::string_view base, int slice) const
 Encodes (base, slice) → engine name: base[t], or base if atemporal.
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] suffix. Does not consult the cached name sets, so a bracket-named atemporal node decodes as temporal here.
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 and orphan-bracket) map to ATEMPORAL, every other name is parsed by decodeName.
std::vector< std::pair< std::string, int > > _determineNodeSet_ (const NodeSet &ids) const
 Maps a set of node ids to (base, slice) pairs (via determineNode).
NodeId _validateVariable_ (std::string_view base, int slice) const
 Resolves and validates a (base, slice) endpoint into its NodeId.
void _validateAdd_ (const std::string &base, bool temporal) const
 Checks that a variable named base can be added.
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 once).
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() (on unroll(T)).

Static Private Member Functions

static std::pair< std::string, bool > _resolveGumFormat_ (std::string_view filename)
 Resolves a user filename to (filepath, binary): ensures a .jgum/.bgum extension (.bgum appended by default) and reports whether the format is binary. Single source of truth for the GUM format convention shared by save() and load().
static std::string _escapeDot_ (std::string_view name)
 Escapes double quotes for a DOT identifier or label. Used by summaryGraph().

Private Attributes

Size _k_
 The order (number of time slices in the template).
BayesNet< GUM_SCALAR > _bn_
 The underlying Bayesian network used as a storage engine for the template.
std::unordered_set< std::string > _temporal_
 Base names of the registered temporal processes.
std::unordered_set< std::string > _atemporal_
 Base names of the registered atemporal variables.

Persistence and conversion

void save (std::string_view filename) const
 Saves the template in the GUM format (text .jgum or binary .bgum).
static KTBN< GUM_SCALAR > load (std::string_view filename)
 Loads a k-DBN from a GUM file produced by save().
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 exclusive conventions.

Detailed Description

template<GUM_Numeric GUM_SCALAR>
class gum::KTBN< GUM_SCALAR >

Class representing a k-order dynamic Bayesian network (k-DBN).

A k-order dynamic Bayesian network (k-DBN, sometimes called a k-Time-slice Bayesian Network or k-TBN) generalizes the classical 2-TBN: the conditional distribution of a variable at time \(t\) may depend on the \(k\) most recent time slices \(t, t-1, \ldots, t-k+1\) instead of a single step backward.

Rather than storing an (infinite) unrolled network, a KTBN only stores a template made of exactly \(k\) time slices. This template captures both:

  • the initial distribution, encoded by slices \(0, \ldots, k-2\) (the initial slices, where the full \(k\)-history is not yet available), and
  • the transition kernel, encoded by slice \(k-1\) as a function of slices \(0, \ldots, k-1\). Because the process is time-homogeneous, this kernel is reused for every \(t \geq k-1\) when unrolling.

Two kinds of random variables are distinguished:

  • temporal variables (also called processes here), which evolve through time and are therefore represented by \(k\) instances (one per slice) in the template;
  • atemporal variables, which are constant through time (e.g. a static context parameter) and are represented by a single instance.
Node identity: the bracket notation
The identity of a node in the underlying engine is its name. Temporal nodes are stored using bracket notation: the \(t\)-th instance of a process base is named base[t] (e.g. "X[0]", "X[1]", ...). Atemporal variables keep their bare name. The class holds no gum::NodeId index table: a (process, slice) couple is resolved to its node by encoding it and asking the engine, and a node's slice is recovered by decoding its name. The public API is always expressed in terms of (process, slice) couples; the bracket encoding is an internal detail.
Internal storage
Structure and parameters are stored in an underlying gum::BayesNet (the template) used purely as a storage engine, so that gum::Tensor CPTs, cycle detection, topological ordering and the existing I/O readers/writers are reused as-is. The gum::BayesNet is the single source of truth; the class only caches two name sets (the temporal processes and the atemporal variables) for fast O(1) membership queries. These sets are std::unordered_set, so their iteration order is unspecified; methods that need a deterministic order must sort explicitly.
Name collision rule
All base names must be globally unique: a name cannot be used for both a temporal process and an atemporal variable simultaneously. In addition, an atemporal variable named "X[0]" is forbidden when a temporal process "X" exists (and vice-versa), because both would map to the same BN node "X[0]". The reservation covers every bracket-suffixed name over an existing process, not only the slices that process actually holds: "X[999]" is refused for \(k=3\) as well, since the slice index is parsed without an upper bound and such a name would otherwise shadow the process. add() and changeVariableName() enforce these rules and throw DuplicateLabel or InvalidArgument on violation.
Arc semantics
Arcs must respect temporal causality. For an arc \(u \rightarrow v\):
  • if v is atemporal, then u must be atemporal too (a static variable cannot depend on a time-varying one);
  • if v is temporal at slice \(t_v\) and u is temporal at slice \(t_u\), then \(t_u \leq t_v\) (no arc from the future to the past). The lag of the arc is \(t_v - t_u \in [0, k-1]\);
  • an atemporal u may point to a temporal v at any slice.
Warning
Unlike the Python prototype, unroll() correctly handles arcs of arbitrary lag (e.g. an arc X[0] -> X[2] for \(k=3\)), not only arcs between consecutive slices.

Definition at line 201 of file KTBN.h.

Constructor & Destructor Documentation

◆ KTBN() [1/3]

template<GUM_Numeric GUM_SCALAR>
gum::KTBN< GUM_SCALAR >::KTBN ( Size k = 2)
explicit

Default constructor.

Parameters
kThe order of the k-DBN, i.e. the number of time slices stored in the template. Must be \(\geq 1\).
Exceptions
InvalidArgumentif k is 0.

Definition at line 132 of file KTBN_tpl.h.

132 : _k_(k) {
133 if (k == 0) GUM_ERROR(InvalidArgument, "A k-DBN must have an order k >= 1.")
135 }
Class representing a k-order dynamic Bayesian network (k-DBN).
Definition KTBN.h:201
KTBN(Size k=2)
Default constructor.
Definition KTBN_tpl.h:132
Size _k_
The order (number of time slices in the template).
Definition KTBN.h:718
Size k() const
Definition KTBN_tpl.h:185

References KTBN(), _k_, GUM_ERROR, and k().

Referenced by KTBN(), KTBN(), KTBN(), ~KTBN(), operator=(), and operator=().

Here is the call graph for this function:
Here is the caller graph for this function:

◆ ~KTBN()

template<GUM_Numeric GUM_SCALAR>
gum::KTBN< GUM_SCALAR >::~KTBN ( )
virtual

Destructor.

Definition at line 138 of file KTBN_tpl.h.

138 {
140 }

References KTBN().

Here is the call graph for this function:

◆ KTBN() [2/3]

template<GUM_Numeric GUM_SCALAR>
gum::KTBN< GUM_SCALAR >::KTBN ( const KTBN< GUM_SCALAR > & source)

Copy constructor.

Definition at line 143 of file KTBN_tpl.h.

143 :
147 }
BayesNet< GUM_SCALAR > _bn_
The underlying Bayesian network used as a storage engine for the template.
Definition KTBN.h:721
std::unordered_set< std::string > _temporal_
Base names of the registered temporal processes.
Definition KTBN.h:724
std::unordered_set< std::string > _atemporal_
Base names of the registered atemporal variables.
Definition KTBN.h:727

References KTBN(), _atemporal_, _bn_, _k_, and _temporal_.

Here is the call graph for this function:

◆ KTBN() [3/3]

template<GUM_Numeric GUM_SCALAR>
gum::KTBN< GUM_SCALAR >::KTBN ( KTBN< GUM_SCALAR > && source)
noexcept

Move constructor.

Definition at line 150 of file KTBN_tpl.h.

References KTBN(), _atemporal_, _bn_, _k_, and _temporal_.

Here is the call graph for this function:

Member Function Documentation

◆ _decodeName_()

template<GUM_Numeric GUM_SCALAR>
std::pair< std::string, int > gum::KTBN< GUM_SCALAR >::_decodeName_ ( std::string_view name) const
private

Purely syntactic parse of an engine name → (base, slice). Slice is ATEMPORAL when there is no [digits] suffix. Does not consult the cached name sets, so a bracket-named atemporal node decodes as temporal here.

Definition at line 85 of file KTBN_tpl.h.

85 {
86 const std::size_t bracketPos = name.rfind('[');
88
90 if (bracketContent.empty() || bracketContent.back() != ']')
91 return {std::string{name}, ATEMPORAL};
92
94 if (digits.empty()) return {std::string{name}, ATEMPORAL};
95 for (const char c: digits)
96 if (std::isdigit(static_cast< unsigned char >(c)) == 0) return {std::string{name}, ATEMPORAL};
97
98 int slice{};
99 try {
101 } catch (const std::out_of_range&) {
103 "Node name '" << name << "' has a slice index too large to represent as int.")
104 }
105 return {std::string{name.substr(0, bracketPos)}, slice};
106 }
bool empty() const
Definition KTBN_tpl.h:200
static constexpr int ATEMPORAL
Conventional time-slice value denoting an atemporal (static) variable.
Definition KTBN.h:204
Size size() const
Definition KTBN_tpl.h:190

References ATEMPORAL, and GUM_ERROR.

Referenced by _determineNode_(), _determineNodesFromBN_(), _timeSlicesToDot_(), _validateAdd_(), changeVariableName(), and summaryGraph().

Here is the caller graph for this function:

◆ _determineNode_()

template<GUM_Numeric GUM_SCALAR>
INLINE std::pair< std::string, int > gum::KTBN< GUM_SCALAR >::_determineNode_ ( const std::string & name) const
private

Cache-aware classification of a node name → (base, slice): nodes registered in _atemporal_ (atemporal and orphan-bracket) map to ATEMPORAL, every other name is parsed by decodeName.

Definition at line 110 of file KTBN_tpl.h.

110 {
111 // Atemporal and orphan-bracket nodes are registered in _atemporal_ and map to ATEMPORAL;
112 // any other name is a temporal "base[t]" parsed by _decodeName_.
113 if (_atemporal_.contains(name)) return {name, ATEMPORAL};
114 return _decodeName_(name);
115 }
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

References _atemporal_, _decodeName_(), and ATEMPORAL.

Referenced by _determineNodeSet_(), _determineNodesFromBN_(), addArc(), arcs(), baseName(), children(), cpt(), eraseArc(), existsArc(), generateCPT(), parents(), timeSlice(), and variable().

Here is the call graph for this function:
Here is the caller graph for this function:

◆ _determineNodeSet_()

template<GUM_Numeric GUM_SCALAR>
std::vector< std::pair< std::string, int > > gum::KTBN< GUM_SCALAR >::_determineNodeSet_ ( const NodeSet & ids) const
private

Maps a set of node ids to (base, slice) pairs (via determineNode).

Definition at line 119 of file KTBN_tpl.h.

119 {
121 result.reserve(ids.size());
122 for (const NodeId id: ids)
123 result.push_back(_determineNode_(_bn_.variable(id).name()));
124 return result;
125 }
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

References _bn_, _determineNode_(), and gum::Set< Key >::size().

Referenced by children(), and parents().

Here is the call graph for this function:
Here is the caller graph for this function:

◆ _determineNodesFromBN_()

template<GUM_Numeric GUM_SCALAR>
void gum::KTBN< GUM_SCALAR >::_determineNodesFromBN_ ( const std::unordered_set< std::string > & atemporalNodes,
std::vector< std::string > * warnings )
private

Rebuilds the cached name sets from the storage engine content (used by fromBN()/load(); decodes names once).

Definition at line 891 of file KTBN_tpl.h.

893 {
894 _temporal_.clear();
895 _atemporal_.clear();
896
897 // a declared name must be a node of the BN: checked before any mutation, so
898 // a typo cannot leave the object half-built
899 for (const std::string& name: atemporalNodes)
900 if (!_bn_.exists(name))
901 GUM_ERROR(NotFound, "fromBN: '" << name << "' is not a node of the BN.")
902
903 const auto warn = [warnings](const std::string& message) {
904 if (warnings != nullptr) warnings->push_back(message);
905 };
906
907 // fromBN()'s bracket-free convention: a name ending in a run of digits
908 // denotes a temporal variable at the timeslice given by that integer (base =
909 // everything before the run); a name with no trailing digit is atemporal.
910 // Purely syntactic, like _decodeName_, but that one expects the engine's own
911 // base[t] convention. Used below only when the source BN carries no bracket
912 // at all (see hasBracket).
915 while (pos > 0 && std::isdigit(static_cast< unsigned char >(name[pos - 1])))
916 --pos;
917 if (pos == name.size()) return {std::string{name}, ATEMPORAL};
918
919 const std::string_view digits = name.substr(pos);
920 int slice{};
921 try {
923 } catch (const std::out_of_range&) {
925 "Node name '" << name << "' has a slice index too large to represent as int.")
926 }
927 return {std::string{name.substr(0, pos)}, slice};
928 };
929
930 // The two conventions never mix within one graph: if any node name already
931 // carries the engine's own base[t] bracket notation, the WHOLE graph is read
932 // that way (legacy behaviour -- what KTBNLearner and toBN() round-trips
933 // produce); only when no node carries a bracket at all does every node get
934 // read via the trailing-integer convention above. Nodes declared in
935 // atemporalNodes are skipped here: their shape says nothing about the rest
936 // of the graph's convention, so a bracket-shaped one (e.g. an orphan
937 // "Y[0]" named atemporal on purpose, see below) must not force
938 // bracket-reading onto otherwise bracket-free temporal nodes.
939 bool hasBracket = false;
940 for (const NodeId n: _bn_.nodes()) {
941 const std::string& name = _bn_.variable(n).name();
942 if (atemporalNodes.contains(name)) continue;
944 hasBracket = true;
945 break;
946 }
947 }
948
949 // first pass: determine every node, collecting the slices seen per process
950 std::vector< std::string > discovered; // temporal bases, in order
952 int maxSlice = -1;
953
954 for (const NodeId n: _bn_.nodes()) {
955 const std::string& name = _bn_.variable(n).name();
956
957 // an explicitly declared node is atemporal whatever its shape, trailing
958 // digits included: it never enters slicesPerProcess, so the completeness
959 // rules below never see it and never warn about it
960 if (atemporalNodes.contains(name)) {
961 _atemporal_.insert(name);
962 continue;
963 }
964
966
967 if (slice == ATEMPORAL) {
968 _atemporal_.insert(base);
969 } else {
972 discovered.push_back(base);
973 }
974
977 "Two variables map to process '" << base << "' at slice " << slice << ".")
978
980
982 }
983 }
984
985 _k_ = (maxSlice < 0) ? Size(1) : Size(maxSlice + 1);
986
987 // second pass: register the complete processes. A group that does not cover
988 // every slice 0..k-1 is NOT rejected: each of its nodes becomes an atemporal
989 // variable, original name kept, and a warning is recorded. Only a base used
990 // BOTH bare and temporal-shaped stays an error -- there the two readings
991 // collide on one name, and no reclassification can resolve that.
992 const char* const conventionNoun = hasBracket ? "bracket" : "digit-suffixed";
995
996 if (_atemporal_.contains(base))
998 "Base name '" << base << "' is used both as an atemporal variable (bare node '"
999 << base << "') and as a temporal process (via " << conventionNoun
1000 << " nodes). " << "Rename one of them before calling fromBN().")
1001
1003 for (Size t = 0; t < _k_; ++t)
1004 if (!sliceMap.exists(static_cast< int >(t))) {
1005 if (!missing.empty()) missing += ", ";
1006 missing += std::to_string(t);
1007 }
1008
1009 if (missing.empty()) {
1010 // Every slice of a process must carry the SAME variable. add() cannot
1011 // break this -- it clones one variable into k instances -- so fromBN()
1012 // is the only way in, and nothing downstream re-checks: KTBNInference
1013 // sizes every ring slot of a process from the kernel slice alone, so a
1014 // slice with a divergent domain would be triangulated against the wrong
1015 // size and then filled with a tensor of another dimension.
1016 // Names necessarily differ between slices, and Variable::operator==
1017 // compares them, so the reference is renamed onto each slice in turn.
1018 const DiscreteVariable& ref = _bn_.variable(sliceMap[0]);
1019 std::unique_ptr< DiscreteVariable > probe(ref.clone());
1020 for (Size t = 1; t < _k_; ++t) {
1021 const DiscreteVariable& other = _bn_.variable(sliceMap[static_cast< int >(t)]);
1022 probe->setName(other.name());
1023 if (!(*probe == other))
1024 GUM_ERROR(OperationNotAllowed,
1025 "The temporal process '"
1026 << base << "' has mismatched slice variables: '" << ref.name() << "' is "
1027 << ref.domain() << " but '" << other.name() << "' is " << other.domain()
1028 << ". Every slice of a process must have the same type and domain.")
1029 }
1030 _temporal_.insert(base);
1031 if (!hasBracket) {
1032 // Under the trailing-integer convention the slices just matched above
1033 // carry no bracket notation yet: rename them onto the engine's
1034 // canonical base[t] form -- the invariant every other method (add(),
1035 // unroll(), rename(), ...) relies on. Under the bracket convention
1036 // source names are already canonical, so nothing to do here.
1037 for (Size t = 0; t < _k_; ++t)
1038 _bn_.changeVariableName(_bn_.variable(sliceMap[static_cast< int >(t)]).name(),
1039 _encode_(base, static_cast< int >(t)));
1040 }
1041 continue;
1042 }
1043
1045 for (auto it = sliceMap.cbegin(); it != sliceMap.cend(); ++it) {
1046 const std::string& nodeName = _bn_.variable(it.val()).name();
1047 _atemporal_.insert(nodeName);
1048 if (!reclassified.empty()) reclassified += ", ";
1049 reclassified += "'" + nodeName + "'";
1050 }
1051 warn("Node(s) " + reclassified + " look temporal (base='" + base + "', " + conventionNoun
1052 + " convention) but the process is missing slice(s) " + missing
1053 + " for k=" + std::to_string(_k_)
1054 + ": they are classified as atemporal variables, original name kept. Pass them in "
1055 "fromBN()'s atemporalNodes argument to make that explicit and silence this warning.");
1056 }
1057
1058 // Every surviving process holds exactly the slices 0..k-1, so k is still the
1059 // one the first pass computed -- unless none survived, in which case the
1060 // largest slice index was contributed by a group that is now atemporal and
1061 // k has nothing left to describe.
1062 if (_temporal_.empty()) _k_ = Size(1);
1063
1064
1065 // third pass: validate temporal causality of the foreign arcs.
1066 for (const auto& arc: _bn_.arcs()) {
1067 const int tailSlice = _determineNode_(_bn_.variable(arc.tail()).name()).second;
1068 const int headSlice = _determineNode_(_bn_.variable(arc.head()).name()).second;
1071 "The network has a temporal->atemporal arc into '"
1072 << _bn_.variable(arc.head()).name() << "'.")
1075 "The network has a future->past arc " << _bn_.variable(arc.tail()).name() << "->"
1076 << _bn_.variable(arc.head()).name() << ".")
1077 }
1078 }
std::vector< std::pair< std::pair< std::string, int >, std::pair< std::string, int > > > arcs() const
Definition KTBN_tpl.h:552
std::vector< std::pair< std::string, int > > nodes() const
Definition KTBN_tpl.h:345
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 _encode_(std::string_view base, int slice) const
Encodes (base, slice) → engine name: base[t], or base if atemporal.
Definition KTBN_tpl.h:79
bool exists(std::string_view base) const
Definition KTBN_tpl.h:319
const std::string & name() const
returns the name of the variable

References _atemporal_, _bn_, _decodeName_(), _determineNode_(), _encode_(), _k_, _temporal_, ATEMPORAL, gum::HashTable< Key, Val >::cbegin(), gum::HashTable< Key, Val >::cend(), gum::DiscreteVariable::clone(), gum::DiscreteVariable::domain(), gum::HashTable< Key, Val >::exists(), exists(), GUM_ERROR, gum::HashTable< Key, Val >::insert(), and gum::Variable::name().

Here is the call graph for this function:

◆ _encode_()

template<GUM_Numeric GUM_SCALAR>
INLINE std::string gum::KTBN< GUM_SCALAR >::_encode_ ( std::string_view base,
int slice ) const
private

Encodes (base, slice) → engine name: base[t], or base if atemporal.

Definition at line 79 of file KTBN_tpl.h.

79 {
80 if (slice == ATEMPORAL) return std::string{base};
81 return std::string{base} + '[' + std::to_string(slice) + ']';
82 }

References ATEMPORAL.

Referenced by _determineNodesFromBN_(), _timeSlicesToDot_(), _validateAdd_(), _validateVariable_(), add(), changeVariableName(), erase(), fillCPT(), and unroll().

Here is the caller graph for this function:

◆ _escapeDot_()

template<GUM_Numeric GUM_SCALAR>
std::string gum::KTBN< GUM_SCALAR >::_escapeDot_ ( std::string_view name)
staticprivate

Escapes double quotes for a DOT identifier or label. Used by summaryGraph().

Definition at line 1212 of file KTBN_tpl.h.

1212 {
1214 out.reserve(name.size());
1215 for (const char c: name) {
1216 if (c == '"') out += '\\';
1217 out += c;
1218 }
1219 return out;
1220 }

Referenced by summaryGraph().

Here is the caller graph for this function:

◆ _resolveGumFormat_()

template<GUM_Numeric GUM_SCALAR>
std::pair< std::string, bool > gum::KTBN< GUM_SCALAR >::_resolveGumFormat_ ( std::string_view filename)
staticprivate

Resolves a user filename to (filepath, binary): ensures a .jgum/.bgum extension (.bgum appended by default) and reports whether the format is binary. Single source of truth for the GUM format convention shared by save() and load().

Definition at line 787 of file KTBN_tpl.h.

787 {
788 // The extension selects the format: ".jgum" is text, anything else is binary
789 // and gets a ".bgum" extension appended if missing.
791 const bool text = filepath.ends_with(".jgum");
792 if (!text && !filepath.ends_with(".bgum")) filepath += ".bgum";
793 return {std::move(filepath), !text}; // .second = binary
794 }

Referenced by load(), and save().

Here is the caller graph for this function:

◆ _timeSlicesToDot_()

template<GUM_Numeric GUM_SCALAR>
std::string gum::KTBN< GUM_SCALAR >::_timeSlicesToDot_ ( const BayesNet< GUM_SCALAR > & bn,
bool highlightReplicated,
const dot::DotOptions & options ) const
private

Renders bn as time-slice-clustered DOT. Shared engine behind toDot() (on _bn_) and toUnrolledDot() (on unroll(T)).

Definition at line 1143 of file KTBN_tpl.h.

1145 {
1146 const auto style = dot::DynamicBNDotStyle::read();
1147
1148 // Group (node, full name, base label) by timeslice. std::map keeps keys sorted, and
1149 // ATEMPORAL == -1 so atemporal variables naturally sort first, followed by
1150 // increasing slice indices — mirroring pyAgrum's noTimeCluster-then-slices order.
1152 for (const NodeId n: bn.nodes()) {
1153 const std::string& name = bn.variable(n).name();
1154 const auto [base, slice] = _decodeName_(name);
1155 timeslices[slice].emplace_back(name, base, n);
1156 }
1157
1158 dot::DotWriter writer(true, "KTBN");
1159 writer.graphAttributes({{"bgcolor", "transparent"},
1160 {"size", options.size().empty() ? style.size : options.size()},
1161 {"rankdir", "LR"},
1162 {"splines", "ortho"}});
1163 writer.nodeDefaults({{"color", "#000000"},
1164 {"fillcolor", "white"},
1165 {"fontcolor", "black"},
1166 {"style", "filled"}});
1167
1168 for (auto& [slice, nodes]: timeslices) {
1169 std::sort(nodes.begin(), nodes.end());
1170 if (slice == ATEMPORAL) {
1171 writer.beginSubgraph(
1172 "cluster_atemporal",
1173 {{"label", "atemporal"}, {"style", "filled"}, {"bgcolor", style.atemporalBgColor}});
1174 } else {
1175 const bool replicated = highlightReplicated && Size(slice) >= _k_;
1176 writer.beginSubgraph(
1177 "cluster_" + std::to_string(slice),
1178 {{"label", "Time slice " + std::to_string(slice)},
1179 {"style", "filled"},
1180 {"bgcolor", replicated ? style.replicatedSliceBgColor : style.timeSliceBgColor}});
1181 }
1182 for (const auto& [full, label, node]: nodes)
1184 writer.endSubgraph();
1185 }
1186
1187 writer.edgeDefaults({{"color", "black"}, {"constraint", "false"}});
1188 for (const auto& arc: bn.arcs())
1189 writer.edge(bn.variable(arc.tail()).name(),
1190 bn.variable(arc.head()).name(),
1191 dot::arcAttributes(options.arc(arc.tail(), arc.head())));
1192
1193 writer.edgeDefaults({{"style", "invis"}, {"constraint", "true"}});
1194 if (const auto it0 = timeslices.find(0); it0 != timeslices.end()) {
1195 for (const auto& node0: it0->second) {
1197 int prec = ATEMPORAL;
1198 bool first = true;
1199 for (const auto& [slice, nodes]: timeslices) {
1200 if (slice == ATEMPORAL) continue;
1201 if (!first) writer.edge(_encode_(label, prec), _encode_(label, slice));
1202 prec = slice;
1203 first = false;
1204 }
1205 }
1206 }
1207
1208 return writer.str();
1209 }
static DynamicBNDotStyle read()
Definition dotStyle.cpp:168

References _decodeName_(), _encode_(), _k_, gum::dot::DotOptions::arc(), gum::dot::arcAttributes(), ATEMPORAL, gum::dot::DotWriter::beginSubgraph(), gum::dot::DotWriter::edge(), gum::dot::DotWriter::edgeDefaults(), gum::dot::DotWriter::endSubgraph(), gum::dot::DotWriter::graphAttributes(), gum::dot::DotOptions::node(), gum::dot::DotWriter::node(), gum::dot::nodeAttributes(), gum::dot::DotWriter::nodeDefaults(), nodes(), gum::dot::DynamicBNDotStyle::read(), gum::dot::DotOptions::size(), and gum::dot::DotWriter::str().

Referenced by toDot(), and toUnrolledDot().

Here is the call graph for this function:
Here is the caller graph for this function:

◆ _validateAdd_()

template<GUM_Numeric GUM_SCALAR>
void gum::KTBN< GUM_SCALAR >::_validateAdd_ ( const std::string & base,
bool temporal ) const
private

Checks that a variable named base can be added.

Parameters
temporaltrue for a temporal process, false for an atemporal variable.
Exceptions
DuplicateLabel/ InvalidArgument on a name collision (see add()).

Definition at line 216 of file KTBN_tpl.h.

216 {
217 const auto& ownSet = temporal ? _temporal_ : _atemporal_;
218 const auto& otherSet = temporal ? _atemporal_ : _temporal_;
219
220 if (ownSet.contains(base))
222 (temporal ? "A temporal process '" : "An atemporal variable '")
223 << base << "' already exists.")
226 (temporal ? "Cannot add temporal process '" : "Cannot add atemporal variable '")
227 << base << "': " << (temporal ? "an atemporal variable" : "a temporal process")
228 << " with that name already exists.")
229
230 if (temporal) {
231 for (Size t = 0; t < _k_; ++t) {
232 const std::string encoded = _encode_(base, static_cast< int >(t));
233 if (_atemporal_.contains(encoded))
235 "Temporal process '" << base << "' at slice " << t << " would produce node '"
236 << encoded << "' which conflicts with atemporal variable '"
237 << encoded << "'.")
238 }
239 } else {
240 const auto [decodedBase, decodedSlice] = _decodeName_(base);
241 if (decodedSlice != ATEMPORAL && _temporal_.contains(decodedBase)) {
242 // Bracket notation over an existing temporal process is reserved in
243 // FULL, whatever the index: _decodeName_ has no upper bound, so
244 // "X[999]" decodes to (X, 999) and would shadow the process even though
245 // no such node exists. Only the in-range case can claim an actual node
246 // collision -- promising one for an out-of-range index would send the
247 // caller looking for a node that was never there.
248 if (Size(decodedSlice) < _k_)
250 "Atemporal variable name '" << base << "' conflicts with temporal process '"
251 << decodedBase
252 << "': that name is already used by its slice "
253 "nodes.")
255 "Atemporal variable name '"
256 << base << "' is invalid: '" << decodedBase
257 << "' is a temporal process, so every bracket-suffixed name over it is "
258 "reserved -- including slice "
259 << decodedSlice << ", beyond the current order k=" << _k_ << ".")
260 }
261 }
262 }

References _atemporal_, _decodeName_(), _encode_(), _k_, _temporal_, ATEMPORAL, and GUM_ERROR.

Referenced by add().

Here is the call graph for this function:
Here is the caller graph for this function:

◆ _validateVariable_()

template<GUM_Numeric GUM_SCALAR>
NodeId gum::KTBN< GUM_SCALAR >::_validateVariable_ ( std::string_view base,
int slice ) const
private

Resolves and validates a (base, slice) endpoint into its NodeId.

Definition at line 435 of file KTBN_tpl.h.

435 {
436 const std::string baseStr{base};
437
438 if (slice == ATEMPORAL) {
439 if (!_atemporal_.contains(baseStr)) {
440 if (_temporal_.contains(baseStr))
442 "'" << baseStr << "' is a temporal process but is used as atemporal.")
443 GUM_ERROR(NotFound, "There is no atemporal variable named '" << baseStr << "'.")
444 }
446 }
447
449 if (_atemporal_.contains(baseStr))
451 "'" << baseStr << "' is an atemporal variable but is used at slice " << slice
452 << ".")
453 GUM_ERROR(NotFound, "There is no temporal process named '" << baseStr << "'.")
454 }
455 if (slice < 0 || Size(slice) >= _k_)
457 "Slice " << slice << " is out of [0," << (_k_ - 1) << "] for process '" << baseStr
458 << "'.")
460 }

References _atemporal_, _bn_, _encode_(), _k_, _temporal_, ATEMPORAL, and GUM_ERROR.

Referenced by addArc(), children(), cpt(), eraseArc(), existsArc(), fillCPT(), generateCPT(), parents(), and variable().

Here is the call graph for this function:
Here is the caller graph for this function:

◆ add() [1/2]

template<GUM_Numeric GUM_SCALAR>
void gum::KTBN< GUM_SCALAR >::add ( const DiscreteVariable & var,
bool temporal = true )

Adds a variable to the k-DBN.

A temporal variable (process) is cloned into \(k\) instances (one per slice); an atemporal variable is added once.

Parameters
varThe variable to add (added by copy).
temporalWhether the variable is temporal.
Exceptions
DuplicateLabelif a variable with that base name already exists (any kind — base names are globally unique).
InvalidArgumentif a temporal base[t] would collide with an existing atemporal node of that encoded name, or vice-versa.

Definition at line 265 of file KTBN_tpl.h.

265 {
266 const std::string base = var.name();
267
268 if (temporal) {
269 _validateAdd_(base, true);
270 for (Size t = 0; t < _k_; ++t) {
271 // clone() to rename; BayesNet::add() clones again internally (unavoidable via public API).
273 clone->setName(_encode_(base, static_cast< int >(t)));
274 _bn_.add(*clone);
275 }
276 _temporal_.insert(base);
277 } else {
278 _validateAdd_(base, false);
279 _bn_.add(var);
280 _atemporal_.insert(base);
281 }
282 }
void _validateAdd_(const std::string &base, bool temporal) const
Checks that a variable named base can be added.
Definition KTBN_tpl.h:216
void add(const DiscreteVariable &var, bool temporal=true)
Adds a variable to the k-DBN.
Definition KTBN_tpl.h:265

References _atemporal_, _bn_, _encode_(), _k_, _temporal_, _validateAdd_(), gum::DiscreteVariable::clone(), and gum::Variable::name().

Referenced by add(), addAtemporal(), addAtemporal(), addTemporal(), and addTemporal().

Here is the call graph for this function:
Here is the caller graph for this function:

◆ add() [2/2]

template<GUM_Numeric GUM_SCALAR>
void gum::KTBN< GUM_SCALAR >::add ( std::string_view fast_description,
bool temporal = true,
unsigned int default_nbrmod = 2 )

Adds a variable using the "fast" textual description syntax.

See also
gum::BayesNet::add(std::string_view,unsigned int)

Definition at line 285 of file KTBN_tpl.h.

References add(), and gum::fastVariable().

Here is the call graph for this function:

◆ addArc() [1/2]

template<GUM_Numeric GUM_SCALAR>
void gum::KTBN< GUM_SCALAR >::addArc ( std::string_view tail,
std::string_view head )

Adds an arc using internal engine names (bracket notation: "X[0]", "C", …).

See also
fillCPT(node_name, …) for the same naming convention.
Exceptions
NotFoundif an endpoint name is not in the template.
OutOfBounds/ OperationNotAllowed / DuplicateElement / InvalidDirectedCycle — same conditions as the (base, slice) overload.

Definition at line 530 of file KTBN_tpl.h.

530 {
531 const auto [tb, ts] = _determineNode_(std::string{tail});
532 const auto [hb, hs] = _determineNode_(std::string{head});
533 addArc(tb, ts, hb, hs);
534 }
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

References _determineNode_(), and addArc().

Here is the call graph for this function:

◆ addArc() [2/2]

template<GUM_Numeric GUM_SCALAR>
void gum::KTBN< GUM_SCALAR >::addArc ( std::string_view tailBase,
int tailSlice,
std::string_view headBase,
int headSlice )

Adds an arc between two (process, slice) endpoints.

Parameters
tailBaseBase name of the tail variable.
tailSliceSlice of the tail (KTBN::ATEMPORAL for an atemporal tail).
headBaseBase name of the head variable.
headSliceSlice of the head (KTBN::ATEMPORAL for an atemporal head).
Exceptions
NotFoundif an endpoint does not exist.
OutOfBoundsif a slice argument is out of \([0,k-1]\) for a temporal endpoint.
OperationNotAllowedif the arc violates temporal causality (a temporal variable pointing to an atemporal one, or an arc from a future slice to a past slice).
DuplicateElementif the arc already exists.
InvalidDirectedCycleif the arc would create a cycle.

Definition at line 491 of file KTBN_tpl.h.

494 {
497
498 if (headSlice == ATEMPORAL) {
499 if (tailSlice != ATEMPORAL)
501 "A temporal variable cannot be a parent of the atemporal variable '" << headBase
502 << "'.")
503 } else if (tailSlice != ATEMPORAL && tailSlice > headSlice) {
505 "An arc cannot go from a future slice (" << tailSlice << ") to a past slice ("
506 << headSlice << ").")
507 }
508
509 _bn_.addArc(tail, head);
510 }
NodeId _validateVariable_(std::string_view base, int slice) const
Resolves and validates a (base, slice) endpoint into its NodeId.
Definition KTBN_tpl.h:435

References _bn_, _validateVariable_(), ATEMPORAL, and GUM_ERROR.

Referenced by addArc().

Here is the call graph for this function:
Here is the caller graph for this function:

◆ addAtemporal() [1/2]

template<GUM_Numeric GUM_SCALAR>
INLINE void gum::KTBN< GUM_SCALAR >::addAtemporal ( const DiscreteVariable & var)

Convenience shortcut for add(var, false).

Definition at line 298 of file KTBN_tpl.h.

298 {
299 add(var, false);
300 }

References add().

Here is the call graph for this function:

◆ addAtemporal() [2/2]

template<GUM_Numeric GUM_SCALAR>
INLINE void gum::KTBN< GUM_SCALAR >::addAtemporal ( std::string_view fast_description,
unsigned int default_nbrmod = 2 )

Convenience shortcut for add(fast_description, false, default_nbrmod).

Definition at line 309 of file KTBN_tpl.h.

310 {
312 }

References add().

Here is the call graph for this function:

◆ addTemporal() [1/2]

template<GUM_Numeric GUM_SCALAR>
INLINE void gum::KTBN< GUM_SCALAR >::addTemporal ( const DiscreteVariable & var)

Convenience shortcut for add(var, true).

Definition at line 293 of file KTBN_tpl.h.

293 {
294 add(var, true);
295 }

References add().

Here is the call graph for this function:

◆ addTemporal() [2/2]

template<GUM_Numeric GUM_SCALAR>
INLINE void gum::KTBN< GUM_SCALAR >::addTemporal ( std::string_view fast_description,
unsigned int default_nbrmod = 2 )

Convenience shortcut for add(fast_description, true, default_nbrmod).

Definition at line 303 of file KTBN_tpl.h.

304 {
306 }

References add().

Here is the call graph for this function:

◆ arcs()

template<GUM_Numeric GUM_SCALAR>
std::vector< std::pair< std::pair< std::string, int >, std::pair< std::string, int > > > gum::KTBN< GUM_SCALAR >::arcs ( ) const
Returns
All arcs as (tail, head) pairs of (base, slice).

Definition at line 552 of file KTBN_tpl.h.

552 {
554 result.reserve(_bn_.sizeArcs());
555 for (const auto& arc: _bn_.arcs()) {
556 result.emplace_back(_determineNode_(_bn_.variable(arc.tail()).name()),
557 _determineNode_(_bn_.variable(arc.head()).name()));
558 }
559 return result;
560 }

References _bn_, and _determineNode_().

Referenced by toString().

Here is the call graph for this function:
Here is the caller graph for this function:

◆ atemporalVarNames()

template<GUM_Numeric GUM_SCALAR>
INLINE const std::unordered_set< std::string > & gum::KTBN< GUM_SCALAR >::atemporalVarNames ( ) const
Returns
The set of atemporal variable base names.

Definition at line 330 of file KTBN_tpl.h.

330 {
331 return _atemporal_;
332 }

References _atemporal_.

◆ baseName()

template<GUM_Numeric GUM_SCALAR>
INLINE std::string gum::KTBN< GUM_SCALAR >::baseName ( const DiscreteVariable & var) const

Returns the base name (without bracket encoding) of var.

Exceptions
NotFoundif var is not a node of this k-DBN.

Definition at line 481 of file KTBN_tpl.h.

481 {
482 _bn_.idFromName(var.name()); // throws NotFound if var is not in this k-DBN
483 return _determineNode_(var.name()).first;
484 }

References _bn_, _determineNode_(), and gum::Variable::name().

Here is the call graph for this function:

◆ bnToDot()

template<GUM_Numeric GUM_SCALAR>
INLINE std::string gum::KTBN< GUM_SCALAR >::bnToDot ( ) const

Returns the Graphviz DOT string of the underlying storage BayesNet.

Nodes are labelled with their internal engine names (bracket notation: base[t] for temporal nodes, bare name for atemporal nodes). No time-slice clustering is applied.

Definition at line 1223 of file KTBN_tpl.h.

1223 {
1224 return _bn_.toDot();
1225 }

References _bn_.

◆ changeVariableName()

template<GUM_Numeric GUM_SCALAR>
void gum::KTBN< GUM_SCALAR >::changeVariableName ( std::string_view oldBase,
std::string_view newBase )

Renames a variable (temporal process or atemporal variable).

The kind is determined automatically from the registered name sets. For a temporal process all \(k\) slice names are re-encoded with the new base.

Exceptions
NotFoundif no variable named oldBase exists.
DuplicateLabelif a variable named newBase already exists (any kind).
InvalidArgumentif newBase is empty or would create a BN node-name collision.

Definition at line 399 of file KTBN_tpl.h.

399 {
402
403 if (oldStr == newStr) return;
404 if (newStr.empty()) GUM_ERROR(InvalidArgument, "New base name must not be empty.")
405
407 GUM_ERROR(NotFound, "No variable named '" << oldStr << "' in the k-DBN.")
409 GUM_ERROR(DuplicateLabel, "A variable named '" << newStr << "' already exists.")
410
412 for (Size t = 0; t < _k_; ++t)
413 if (_atemporal_.contains(_encode_(newStr, static_cast< int >(t))))
415 "Renaming to '" << newStr << "': slice " << t
416 << " collides with an atemporal variable.")
417 for (Size t = 0; t < _k_; ++t)
418 _bn_.changeVariableName(_encode_(oldStr, static_cast< int >(t)),
419 _encode_(newStr, static_cast< int >(t)));
420 _temporal_.erase(oldStr);
421 _temporal_.insert(newStr);
422 } else {
424 if (decodedSlice != ATEMPORAL && _temporal_.contains(decodedBase))
426 "'" << newStr << "' conflicts with temporal process '" << decodedBase
427 << "': that name is already used by its slice nodes.")
431 }
432 }
void erase(std::string_view base)
Removes a variable and all its incident arcs.
Definition KTBN_tpl.h:383
void changeVariableName(std::string_view oldBase, std::string_view newBase)
Renames a variable (temporal process or atemporal variable).
Definition KTBN_tpl.h:399

References _atemporal_, _bn_, _decodeName_(), _encode_(), _k_, _temporal_, ATEMPORAL, and GUM_ERROR.

Here is the call graph for this function:

◆ children() [1/2]

template<GUM_Numeric GUM_SCALAR>
std::vector< std::pair< std::string, int > > gum::KTBN< GUM_SCALAR >::children ( std::string_view base,
int slice ) const

Children of a node as (base, slice) pairs (ATEMPORAL if atemporal).

Definition at line 370 of file KTBN_tpl.h.

371 {
373 }
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

References _bn_, _determineNodeSet_(), and _validateVariable_().

Referenced by children().

Here is the call graph for this function:
Here is the caller graph for this function:

◆ children() [2/2]

template<GUM_Numeric GUM_SCALAR>
std::vector< std::pair< std::string, int > > gum::KTBN< GUM_SCALAR >::children ( std::string_view node_name) const

Returns the children using an engine name ("X[1]", "C", …).

Definition at line 377 of file KTBN_tpl.h.

377 {
378 const auto [b, s] = _determineNode_(std::string{node_name});
379 return children(b, s);
380 }
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

References _determineNode_(), and children().

Here is the call graph for this function:

◆ clear()

template<GUM_Numeric GUM_SCALAR>
void gum::KTBN< GUM_SCALAR >::clear ( )

Removes all variables and arcs, keeping the order \(k\).

Definition at line 205 of file KTBN_tpl.h.

205 {
206 _bn_.clear();
207 _temporal_.clear();
208 _atemporal_.clear();
209 }

References _atemporal_, _bn_, and _temporal_.

◆ cpt() [1/2]

template<GUM_Numeric GUM_SCALAR>
INLINE const Tensor< GUM_SCALAR > & gum::KTBN< GUM_SCALAR >::cpt ( std::string_view base,
int slice ) const

Returns the CPT of a (process, slice) couple.

The returned reference is const but its content is mutable — use any standard gum::Tensor method to fill it:

m.cpt("C").fillWith({0.4, 0.6});
m.cpt("X", 2).fillWith({0.8,0.2, 0.3,0.7, 0.6,0.4, 0.1,0.9});
m.cpt("Y", 1).fillWith(GUM_SCALAR(0.5)); // uniform

Values for the vector overload are in the CPT's natural iteration order: the node's own variable varies fastest, parents follow in the order they appear in cpt().variable(1..n). Use cpt().variable(i).name() to inspect the ordering before filling.

Definition at line 567 of file KTBN_tpl.h.

568 {
569 return _bn_.cpt(_validateVariable_(base, slice));
570 }

References _bn_, and _validateVariable_().

Referenced by cpt(), fillCPT(), and fillCPT().

Here is the call graph for this function:
Here is the caller graph for this function:

◆ cpt() [2/2]

template<GUM_Numeric GUM_SCALAR>
INLINE const Tensor< GUM_SCALAR > & gum::KTBN< GUM_SCALAR >::cpt ( std::string_view node_name) const

Returns the CPT using an engine name ("X[1]", "C", …).

Definition at line 573 of file KTBN_tpl.h.

573 {
574 const auto [b, s] = _determineNode_(std::string{node_name});
575 return cpt(b, s);
576 }
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

References _determineNode_(), and cpt().

Here is the call graph for this function:

◆ empty()

template<GUM_Numeric GUM_SCALAR>
INLINE bool gum::KTBN< GUM_SCALAR >::empty ( ) const
Returns
true if the template contains no variable.

Definition at line 200 of file KTBN_tpl.h.

200 {
201 return _bn_.empty();
202 }

References _bn_.

◆ erase()

template<GUM_Numeric GUM_SCALAR>
void gum::KTBN< GUM_SCALAR >::erase ( std::string_view base)

Removes a variable and all its incident arcs.

The kind (temporal or atemporal) is determined automatically from the registered name sets. For a temporal process all \(k\) slice nodes are removed.

Exceptions
NotFoundif no variable with that name exists.

Definition at line 383 of file KTBN_tpl.h.

383 {
384 const std::string baseStr{base};
385
386 if (_temporal_.contains(baseStr)) {
387 for (Size t = 0; t < _k_; ++t)
388 _bn_.erase(_encode_(baseStr, static_cast< int >(t)));
389 _temporal_.erase(baseStr);
390 } else if (_atemporal_.contains(baseStr)) {
391 _bn_.erase(baseStr);
392 _atemporal_.erase(baseStr);
393 } else {
394 GUM_ERROR(NotFound, "No variable named '" << baseStr << "' in the k-DBN.")
395 }
396 }

References _atemporal_, _bn_, _encode_(), _k_, _temporal_, and GUM_ERROR.

Here is the call graph for this function:

◆ eraseArc() [1/2]

template<GUM_Numeric GUM_SCALAR>
void gum::KTBN< GUM_SCALAR >::eraseArc ( std::string_view tail,
std::string_view head )

Removes an arc using internal engine names (bracket notation).

Exceptions
NotFoundif an endpoint name is unknown or the arc does not exist.

Definition at line 537 of file KTBN_tpl.h.

537 {
538 const auto [tb, ts] = _determineNode_(std::string{tail});
539 const auto [hb, hs] = _determineNode_(std::string{head});
540 eraseArc(tb, ts, hb, hs);
541 }
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

References _determineNode_(), and eraseArc().

Here is the call graph for this function:

◆ eraseArc() [2/2]

template<GUM_Numeric GUM_SCALAR>
void gum::KTBN< GUM_SCALAR >::eraseArc ( std::string_view tailBase,
int tailSlice,
std::string_view headBase,
int headSlice )

Removes an arc between two (process, slice) endpoints.

The arc must exist: erasing an absent arc throws (via the underlying CPT update), even when both endpoints are valid variables.

Exceptions
NotFound/ OperationNotAllowed / OutOfBounds if an endpoint variable does not exist (same rules as addArc()), or if the arc itself does not exist.

Definition at line 513 of file KTBN_tpl.h.

References _bn_, and _validateVariable_().

Referenced by eraseArc().

Here is the call graph for this function:
Here is the caller graph for this function:

◆ exists()

template<GUM_Numeric GUM_SCALAR>
INLINE bool gum::KTBN< GUM_SCALAR >::exists ( std::string_view base) const
Returns
true if a variable with this base name exists.

Definition at line 319 of file KTBN_tpl.h.

319 {
320 const std::string baseStr{base};
321 return _temporal_.contains(baseStr) || _atemporal_.contains(baseStr);
322 }

References _atemporal_, and _temporal_.

Referenced by _determineNodesFromBN_().

Here is the caller graph for this function:

◆ existsArc() [1/2]

template<GUM_Numeric GUM_SCALAR>
bool gum::KTBN< GUM_SCALAR >::existsArc ( std::string_view tail,
std::string_view head ) const
Returns
true if the arc exists; uses internal engine names (bracket notation).
Exceptions
NotFoundif an endpoint name is unknown.

Definition at line 544 of file KTBN_tpl.h.

544 {
545 const auto [tb, ts] = _determineNode_(std::string{tail});
546 const auto [hb, hs] = _determineNode_(std::string{head});
547 return existsArc(tb, ts, hb, hs);
548 }
bool existsArc(std::string_view tailBase, int tailSlice, std::string_view headBase, int headSlice) const
Definition KTBN_tpl.h:521

References _determineNode_(), and existsArc().

Here is the call graph for this function:

◆ existsArc() [2/2]

template<GUM_Numeric GUM_SCALAR>
bool gum::KTBN< GUM_SCALAR >::existsArc ( std::string_view tailBase,
int tailSlice,
std::string_view headBase,
int headSlice ) const
Returns
true if the arc exists in the template.

Definition at line 521 of file KTBN_tpl.h.

524 {
525 return _bn_.existsArc(_validateVariable_(tailBase, tailSlice),
527 }

References _bn_, and _validateVariable_().

Referenced by existsArc().

Here is the call graph for this function:
Here is the caller graph for this function:

◆ fillCPT() [1/2]

template<GUM_Numeric GUM_SCALAR>
void gum::KTBN< GUM_SCALAR >::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).

The order-safe, bracket-free way to fill a CPT: the node and its parents are addressed by their (base, slice) identity, so the result does not depend on the positional order of cpt().fillWith({...}).

Each parent is a dictionary entry keyed by its (base, slice) identity (use ATEMPORAL as slice for a static parent). ALL parents of the node must be listed, in any order. distribution holds the probabilities over the node's own modalities for that parent configuration.

A parent's value is either a modality index or a modality label, and the two may be mixed — see gum::KTBNModality, whose warning on numeric modalities applies here.

m.fillCPT("C", KTBN::ATEMPORAL, {}, {0.4, 0.6}); // P(C), no parents
m.fillCPT("X", 0, {}, {0.7, 0.3}); // P(X[0]), no parents
m.fillCPT("X", 1, {{{"X", 0}, 1}, {{"C", KTBN::ATEMPORAL}, 0}},
{0.6, 0.4}); // P(X[1] | X[0]=1, C=0)
m.fillCPT("X", 1, {{{"X", 0}, "1"}, {{"C", KTBN::ATEMPORAL}, 0}},
{0.6, 0.4}); // same, X[0] by label
Parameters
baseBase name of the target node.
sliceSlice of the target node (ATEMPORAL for static).
parentsOne (base, slice) -> value entry per parent, any order.
distributionProbabilities over the node's modalities; its size must equal the node's domain size.
Exceptions
NotFound/ OutOfBounds if the node or a parent does not exist, if a parent index is out of range, or if a parent label is not one of that parent's modalities (which of the two is raised for an unknown label depends on the variable type).
SizeErrorif distribution size differs from the node domain size, or if not every parent is specified.
InvalidArgumentif an entry's node is not a parent of the target.

Definition at line 595 of file KTBN_tpl.h.

599 {
600 const NodeId id = _validateVariable_(base, slice);
601 const Tensor< GUM_SCALAR >& cpt = _bn_.cpt(id);
602 const DiscreteVariable& self = _bn_.variable(id);
603
604 if (distribution.size() != self.domainSize())
606 "fillCPT: distribution has " << distribution.size() << " value(s) but '" << base
607 << "' has " << self.domainSize() << " modalities.")
608
609 const Size nbParents = cpt.nbrDim() - 1;
610 if (parents.size() != nbParents)
612 "fillCPT: " << parents.size() << " parent value(s) given but the node has "
613 << nbParents << " parent(s); every parent must be specified.")
614
615 // Address each parent by its (base, slice) identity — order-independent.
616 // No duplicate-parent check needed: a dictionary key is unique by
617 // construction, and here each (base, slice) pair names exactly one node,
618 // so no two distinct keys can alias the same parent.
621 const auto& [parBase, parSlice] = parNode;
624 if (parId == id || !cpt.contains(parVar))
626 "fillCPT: '" << parBase << "' is not a parent of the target node.")
628 }
629
630 // Write the whole conditional distribution over the node's own modalities.
631 for (Idx m = 0; m < self.domainSize(); ++m) {
632 inst.chgVal(self, m);
633 cpt.set(inst, distribution[m]);
634 }
635 }
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

References _bn_, _validateVariable_(), gum::Instantiation::chgVal(), cpt(), gum::DiscreteVariable::domainSize(), GUM_ERROR, and parents().

Here is the call graph for this function:

◆ fillCPT() [2/2]

template<GUM_Numeric GUM_SCALAR>
void gum::KTBN< GUM_SCALAR >::fillCPT ( std::string_view node_name,
const std::map< std::variant< std::string, std::pair< std::string, int > >, KTBNModality > & parents,
const std::vector< GUM_SCALAR > & distribution ) const

Fills one conditional distribution using internal bracket-notation engine name for the target node — the bracket notation visible in toDot() and toString(): "X[t]" for a temporal variable at slice t, and the bare variable name for an atemporal variable (e.g.

"C"). Each parent is keyed either by its engine name ("X[0]") or by its (base, slice) identity — both spellings may be mixed in the same dictionary.

Warning
An engine-name key can be written as a bare string literal, but a (base, slice) key needs an explicit std::pair{...}: std::variant's converting constructor takes one value convertible to an alternative, not a nested brace list, so a bare {"X", 0} cannot implicitly construct the pair alternative the way it would a std::pair or std::tuple element.

As in the (base, slice) overload, a parent's value is either a modality index or a modality label — see gum::KTBNModality.

m.fillCPT("X[1]", {{"X[0]", 1}, {"C", 0}}, {0.6, 0.4});
m.fillCPT("X[1]", {{std::pair{"X", 0}, 1}, {std::pair{"C", KTBN::ATEMPORAL}, 0}},
{0.6, 0.4});
m.fillCPT("X[1]", {{"X[0]", 1}, {std::pair{"C", KTBN::ATEMPORAL}, 0}},
{0.6, 0.4}); // mixed key styles
m.fillCPT("X[1]", {{"X[0]", "1"}, {"C", 0}}, {0.6, 0.4}); // mixed value styles
Parameters
node_nameInternal engine name of the target node.
parentsOne engine_name-or-(base,slice) -> value entry per parent, any order.
distributionProbabilities over the node's modalities; its size must equal the node's domain size.
Exceptions
NotFoundif node_name or a parent does not exist.
SizeError/ InvalidArgument / OutOfBounds — same conditions as the (base, slice) overload.

Definition at line 638 of file KTBN_tpl.h.

642 {
643 const NodeId id = _bn_.idFromName(std::string{node_name});
644 const Tensor< GUM_SCALAR >& cpt = _bn_.cpt(id);
645 const DiscreteVariable& self = _bn_.variable(id);
646
647 if (distribution.size() != self.domainSize())
649 "fillCPT: distribution has " << distribution.size() << " value(s) but '"
650 << node_name << "' has " << self.domainSize()
651 << " modalities.")
652
653 const Size nbParents = cpt.nbrDim() - 1;
654 if (parents.size() != nbParents)
656 "fillCPT: " << parents.size() << " parent value(s) given but the node has "
657 << nbParents << " parent(s); every parent must be specified.")
658
659 // Unlike the (base, slice)-keyed overload above, duplicates ARE possible here
660 // despite unique map keys: "X[0]" and (base="X", slice=0) compare unequal as
661 // std::variant values yet name the same node. Both are resolved to an engine
662 // name first, so the seen-check below can catch the alias.
666 const std::string parName
670 std::get< std::pair< std::string, int > >(parKey).second);
671 const NodeId parId = _bn_.idFromName(parName);
673 if (parId == id || !cpt.contains(parVar))
675 "fillCPT: '" << parName << "' is not a parent of the target node.")
676 if (seen.contains(parId))
677 GUM_ERROR(InvalidArgument, "fillCPT: parent '" << parName << "' is listed more than once.")
678 seen.insert(parId);
679 inst.chgVal(parVar, parVal.toIndex(parVar));
680 }
681
682 for (Idx m = 0; m < self.domainSize(); ++m) {
683 inst.chgVal(self, m);
684 cpt.set(inst, distribution[m]);
685 }
686 }

References _bn_, _encode_(), gum::Instantiation::chgVal(), gum::Set< Key >::contains(), cpt(), gum::DiscreteVariable::domainSize(), GUM_ERROR, gum::Set< Key >::insert(), and parents().

Here is the call graph for this function:

◆ fromBN()

template<GUM_Numeric GUM_SCALAR>
KTBN< GUM_SCALAR > gum::KTBN< GUM_SCALAR >::fromBN ( const BayesNet< GUM_SCALAR > & bn,
const std::unordered_set< std::string > & atemporalNodes = {},
std::vector< std::string > * warnings = nullptr )
static

Builds a k-DBN from an existing gum::BayesNet, reading its node names under one of two mutually exclusive conventions.

If any node name already carries the engine's own bracket notation (base[t]), the whole network is read that way: exactly the legacy behaviour, temporal node names assumed canonical (a plain decimal slice, no leading zeros – the form produced by add() / unroll() / toBN()). Otherwise – no node name carries a bracket at all – every node is read under the bracket-free convention: a name ending in a run of digits denotes a temporal variable at the timeslice given by that integer (base = everything before the digits, e.g. "X0" and "X12" both belong to process "X", at slices 0 and 12); any other name is atemporal.

The order \(k\) is inferred as one plus the largest slice index found. A group of same-base nodes that does not cover every slice \(0..k-1\) is not an error: each of its nodes becomes an atemporal variable, original name kept, and a message is appended to warnings. When no temporal process survives, \(k\) falls back to 1.

Parameters
bnThe source Bayesian network (copied).
atemporalNodesNode names – exactly as they appear in bn – to classify atemporal outright. Only needed to lift an ambiguity: a name the active convention already reads as atemporal changes nothing by being listed, while listing a temporal-shaped name says "I meant this atemporally" where the reclassification above would only guess (and warn).
warningsIf non-null, receives one message per reclassified group.
Exceptions
NotFoundif a name in atemporalNodes is not a node of bn.
OperationNotAllowedif the temporal structure is inconsistent: two variables mapping to the same (process, slice), a base name used both as an atemporal variable and as a temporal process, an arc from a temporal node into an atemporal one, or an arc from the future to the past.
Warning
A lone temporal-shaped node with no sibling sharing its base (e.g. "X0" alone under the bracket-free convention, or "X[0]" alone under the bracket one) yields \(k=1\), where a single slice is a complete process: it is kept temporal, silently. List it in atemporalNodes to say otherwise.

Definition at line 881 of file KTBN_tpl.h.

883 {
884 KTBN< GUM_SCALAR > res(1); // _determineNodesFromBN_ below will modify this k=1
885 res._bn_ = bn;
887 return res;
888 }
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

Referenced by gum::learning::KTBNLearner< GUM_SCALAR >::_assemble_(), and load().

Here is the caller graph for this function:

◆ generateCPT() [1/2]

template<GUM_Numeric GUM_SCALAR>
INLINE void gum::KTBN< GUM_SCALAR >::generateCPT ( std::string_view base,
int slice ) const

Randomly generates the CPT of a single node.

Definition at line 584 of file KTBN_tpl.h.

584 {
585 _bn_.generateCPT(_validateVariable_(base, slice));
586 }

References _bn_, and _validateVariable_().

Referenced by generateCPT().

Here is the call graph for this function:
Here is the caller graph for this function:

◆ generateCPT() [2/2]

template<GUM_Numeric GUM_SCALAR>
INLINE void gum::KTBN< GUM_SCALAR >::generateCPT ( std::string_view node_name) const

Same, using an engine name ("X[1]", "C", …).

Definition at line 589 of file KTBN_tpl.h.

589 {
590 const auto [b, s] = _determineNode_(std::string{node_name});
591 generateCPT(b, s);
592 }
void generateCPT(std::string_view base, int slice) const
Randomly generates the CPT of a single node.
Definition KTBN_tpl.h:584

References _determineNode_(), and generateCPT().

Here is the call graph for this function:

◆ generateCPTs()

template<GUM_Numeric GUM_SCALAR>
INLINE void gum::KTBN< GUM_SCALAR >::generateCPTs ( ) const

Randomly generates every CPT of the template.

Definition at line 579 of file KTBN_tpl.h.

579 {
580 _bn_.generateCPTs();
581 }

References _bn_.

◆ k()

template<GUM_Numeric GUM_SCALAR>
INLINE Size gum::KTBN< GUM_SCALAR >::k ( ) const
Returns
The order \(k\) of the k-DBN.

Definition at line 185 of file KTBN_tpl.h.

185 {
186 return _k_;
187 }

References _k_.

Referenced by KTBN().

Here is the caller graph for this function:

◆ load()

template<GUM_Numeric GUM_SCALAR>
KTBN< GUM_SCALAR > gum::KTBN< GUM_SCALAR >::load ( std::string_view filename)
static

Loads a k-DBN from a GUM file produced by save().

Text iff the name ends with .jgum, otherwise binary (gaining a .bgum extension if missing). If the file carries the KTBN classification properties it is restored exactly; otherwise it is re-derived from node names via fromBN().

Parameters
filenameThe GUM file.
Exceptions
IOErrorif the file cannot be read or is not valid.
OperationNotAllowedif the classification properties are absent and the fallback fromBN() finds an inconsistent temporal structure.

Definition at line 825 of file KTBN_tpl.h.

825 {
827
830 const Size nbErr = reader.proceed();
831 if (nbErr > 0) {
833 reader.showElegantErrorsAndWarnings(stream);
834 reader.showErrorCounts(stream);
835 GUM_ERROR(IOError, "KTBN::load: " << stream.str())
836 }
837
838 // A file written by save() carries the classification as properties: restore it
839 // directly. Otherwise fall back to fromBN(), which re-derives it from node names.
840 if (!(bn.existsProperty("KTBN.k") && bn.existsProperty("KTBN.temporal")
841 && bn.existsProperty("KTBN.atemporal")))
842 return fromBN(bn);
843
846 bool escaped = false;
847 for (const char c: csv) {
848 if (escaped) {
849 current += c;
850 escaped = false;
851 } else if (c == '\\') {
852 escaped = true;
853 } else if (c == ',') {
854 if (!current.empty()) out.insert(current);
855 current.clear();
856 } else {
857 current += c;
858 }
859 }
860 if (!current.empty()) out.insert(current);
861 };
862
863 Size k_val{};
864 try {
865 k_val = static_cast< Size >(std::stoul(bn.property("KTBN.k")));
866 } catch (const std::exception& e) {
868 "KTBN::load: malformed KTBN.k property ('" << bn.property("KTBN.k")
869 << "'): " << e.what())
870 }
872 res._bn_ = bn;
873 split(bn.property("KTBN.temporal"), res._temporal_);
874 split(bn.property("KTBN.atemporal"), res._atemporal_);
875
876 return res;
877 }
void clear()
Removes all variables and arcs, keeping the order .
Definition KTBN_tpl.h:205
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
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

References _resolveGumFormat_(), fromBN(), GUM_ERROR, gum::GumBNReader< GUM_SCALAR >::proceed(), gum::GumBNReader< GUM_SCALAR >::showElegantErrorsAndWarnings(), gum::GumBNReader< GUM_SCALAR >::showErrorCounts(), and gum::split().

Here is the call graph for this function:

◆ nbAtemporalVars()

template<GUM_Numeric GUM_SCALAR>
INLINE Size gum::KTBN< GUM_SCALAR >::nbAtemporalVars ( ) const
Returns
The number of atemporal variables.

Definition at line 340 of file KTBN_tpl.h.

340 {
341 return _atemporal_.size();
342 }

References _atemporal_.

◆ nbTemporalVars()

template<GUM_Numeric GUM_SCALAR>
INLINE Size gum::KTBN< GUM_SCALAR >::nbTemporalVars ( ) const
Returns
The number of temporal processes.

Definition at line 335 of file KTBN_tpl.h.

335 {
336 return _temporal_.size();
337 }

References _temporal_.

◆ nodes()

template<GUM_Numeric GUM_SCALAR>
std::vector< std::pair< std::string, int > > gum::KTBN< GUM_SCALAR >::nodes ( ) const
Returns
All nodes as (base, slice) pairs (atemporal nodes use KTBN::ATEMPORAL).

Definition at line 345 of file KTBN_tpl.h.

345 {
347 result.reserve(size());
348 for (const auto& a: _atemporal_)
349 result.emplace_back(a, ATEMPORAL);
350 for (const auto& p: _temporal_)
351 for (Size t = 0; t < _k_; ++t)
352 result.emplace_back(p, static_cast< int >(t));
353 return result;
354 }

References _atemporal_, _k_, _temporal_, ATEMPORAL, and size().

Referenced by _timeSlicesToDot_().

Here is the call graph for this function:
Here is the caller graph for this function:

◆ operator=() [1/2]

template<GUM_Numeric GUM_SCALAR>
KTBN< GUM_SCALAR > & gum::KTBN< GUM_SCALAR >::operator= ( const KTBN< GUM_SCALAR > & source)

Copy assignment operator.

Definition at line 157 of file KTBN_tpl.h.

157 {
158 if (this != &source) {
160 _k_ = source._k_;
161 _bn_ = source._bn_;
164 }
165 return *this;
166 }

References KTBN(), _atemporal_, _bn_, _k_, and _temporal_.

Here is the call graph for this function:

◆ operator=() [2/2]

template<GUM_Numeric GUM_SCALAR>
KTBN< GUM_SCALAR > & gum::KTBN< GUM_SCALAR >::operator= ( KTBN< GUM_SCALAR > && source)
noexcept

Move assignment operator.

Definition at line 169 of file KTBN_tpl.h.

169 {
170 if (this != &source) {
172 _k_ = source._k_;
176 }
177 return *this;
178 }

References KTBN(), _atemporal_, _bn_, _k_, and _temporal_.

Here is the call graph for this function:

◆ parents() [1/2]

template<GUM_Numeric GUM_SCALAR>
std::vector< std::pair< std::string, int > > gum::KTBN< GUM_SCALAR >::parents ( std::string_view base,
int slice ) const

Parents of a node as (base, slice) pairs (ATEMPORAL if atemporal).

Definition at line 357 of file KTBN_tpl.h.

358 {
360 }

References _bn_, _determineNodeSet_(), and _validateVariable_().

Referenced by fillCPT(), fillCPT(), parents(), and unroll().

Here is the call graph for this function:
Here is the caller graph for this function:

◆ parents() [2/2]

template<GUM_Numeric GUM_SCALAR>
std::vector< std::pair< std::string, int > > gum::KTBN< GUM_SCALAR >::parents ( std::string_view node_name) const

Returns the parents using an engine name ("X[1]", "C", …).

Definition at line 364 of file KTBN_tpl.h.

364 {
365 const auto [b, s] = _determineNode_(std::string{node_name});
366 return parents(b, s);
367 }

References _determineNode_(), and parents().

Here is the call graph for this function:

◆ save()

template<GUM_Numeric GUM_SCALAR>
void gum::KTBN< GUM_SCALAR >::save ( std::string_view filename) const

Saves the template in the GUM format (text .jgum or binary .bgum).

The extension selects the format: .jgum writes the text (JSON) variant, anything else the binary (msgpack) one, gaining a .bgum extension if missing. The temporal/atemporal classification and the order \(k\) are stored as properties, so load() reconstructs the k-DBN exactly — including k=1 processes and bracket-named atemporal variables, which fromBN() cannot disambiguate from node names alone.

Parameters
filenameThe destination file.

Definition at line 797 of file KTBN_tpl.h.

797 {
799
800 // Persist the temporal/atemporal classification (and k) as BN properties so that
801 // load() restores the k-DBN exactly, instead of re-deriving it heuristically from
802 // node names (ambiguous for k=1 processes and bracket-named atemporal variables).
803 // Separator is ','; '\' and ',' inside names are backslash-escaped so any name is safe.
806 for (const auto& n: names) {
807 if (!out.empty()) out += ',';
808 for (const char c: n) {
809 if (c == '\\' || c == ',') out += '\\';
810 out += c;
811 }
812 }
813 return out;
814 };
815
817 annotated.setProperty("KTBN.k", std::to_string(_k_));
818 annotated.setProperty("KTBN.temporal", join(_temporal_));
819 annotated.setProperty("KTBN.atemporal", join(_atemporal_));
821 writer.write(filepath, annotated);
822 }

References _atemporal_, _bn_, _k_, _resolveGumFormat_(), _temporal_, and gum::BNWriter< GUM_SCALAR >::write().

Here is the call graph for this function:

◆ size()

template<GUM_Numeric GUM_SCALAR>
INLINE Size gum::KTBN< GUM_SCALAR >::size ( ) const
Returns
The number of nodes in the template (all slices).

Definition at line 190 of file KTBN_tpl.h.

190 {
191 return _bn_.size();
192 }

References _bn_.

Referenced by nodes().

Here is the caller graph for this function:

◆ sizeArcs()

template<GUM_Numeric GUM_SCALAR>
INLINE Size gum::KTBN< GUM_SCALAR >::sizeArcs ( ) const
Returns
The number of arcs in the template.

Definition at line 195 of file KTBN_tpl.h.

195 {
196 return _bn_.sizeArcs();
197 }

References _bn_.

◆ summaryGraph()

template<GUM_Numeric GUM_SCALAR>
std::string gum::KTBN< GUM_SCALAR >::summaryGraph ( ) const

Returns the Graphviz DOT string of the summary graph: the projection of the transition kernel alone (the pattern that actually repeats through time when unrolling), not the whole template.

Every process (temporal or atemporal) becomes a single node. Only arcs whose head lies in the last time slice ( \(k-1\)) are kept – an arc between two earlier slices belongs to the initial-condition structure (slices \(0, \ldots, k-2\)), not to the repeated pattern, and is dropped. Several arcs may connect the same pair of nodes when the kernel depends on more than one lag (e.g. both X[k-2] and X[k-3] pointing to X[k-1]): each is kept and labelled with its lag (head slice minus tail slice). An arc from an atemporal variable has no lag and is left unlabelled.

Definition at line 1228 of file KTBN_tpl.h.

1228 {
1230 baseNames.insert(_atemporal_.begin(), _atemporal_.end());
1231
1232 const int lastSlice = static_cast< int >(_k_) - 1;
1234 for (const auto& arc: _bn_.arcs()) {
1235 const auto [tailBase, tailSlice] = _decodeName_(_bn_.variable(arc.tail()).name());
1236 const auto [headBase, headSlice] = _decodeName_(_bn_.variable(arc.head()).name());
1237 if (headSlice != lastSlice) continue; // not part of the repeated transition kernel
1238
1239 const int lag = (tailSlice == ATEMPORAL) ? ATEMPORAL : headSlice - tailSlice;
1240 edges.emplace(tailBase, headBase, lag);
1241 }
1242
1244 dot << "digraph KTBN {\n";
1245 dot << " rankdir=LR;\n";
1246 dot << " node [color=\"#000000\", fillcolor=white, style=filled];\n\n";
1247
1248 for (const auto& base: baseNames)
1249 dot << " \"" << _escapeDot_(base) << "\";\n";
1250 dot << "\n";
1251
1252 for (const auto& [tailBase, headBase, lag]: edges) {
1253 dot << " \"" << _escapeDot_(tailBase) << "\" -> \"" << _escapeDot_(headBase) << "\"";
1254 if (lag != ATEMPORAL) dot << " [label=\"" << lag << "\"]";
1255 dot << ";\n";
1256 }
1257
1258 dot << "}\n";
1259 return dot.str();
1260 }
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

References _atemporal_, _bn_, _decodeName_(), _escapeDot_(), _k_, _temporal_, and ATEMPORAL.

Here is the call graph for this function:

◆ temporalVarNames()

template<GUM_Numeric GUM_SCALAR>
INLINE const std::unordered_set< std::string > & gum::KTBN< GUM_SCALAR >::temporalVarNames ( ) const
Returns
The set of temporal process base names.

Definition at line 325 of file KTBN_tpl.h.

325 {
326 return _temporal_;
327 }

References _temporal_.

◆ timeSlice()

template<GUM_Numeric GUM_SCALAR>
INLINE int gum::KTBN< GUM_SCALAR >::timeSlice ( const DiscreteVariable & var) const

The time slice of var, or ATEMPORAL if it is atemporal.

Exceptions
NotFoundif var is not a node of this k-DBN.

Definition at line 475 of file KTBN_tpl.h.

475 {
476 _bn_.idFromName(var.name()); // throws NotFound if var is not in this k-DBN
477 return _determineNode_(var.name()).second;
478 }

References _bn_, _determineNode_(), and gum::Variable::name().

Here is the call graph for this function:

◆ toBN()

template<GUM_Numeric GUM_SCALAR>
BayesNet< GUM_SCALAR > gum::KTBN< GUM_SCALAR >::toBN ( ) const
Returns
A deep copy of the underlying template as a gum::BayesNet.

Definition at line 693 of file KTBN_tpl.h.

693 {
695 }

References _bn_.

◆ toDot()

template<GUM_Numeric GUM_SCALAR>
std::string gum::KTBN< GUM_SCALAR >::toDot ( ) const

Returns a Graphviz DOT string with one cluster per time slice.

Definition at line 1120 of file KTBN_tpl.h.

1120 {
1121 return _timeSlicesToDot_(_bn_, false, dot::DotOptions());
1122 }
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

References _bn_, and _timeSlicesToDot_().

Here is the call graph for this function:

◆ toString()

template<GUM_Numeric GUM_SCALAR>
std::string gum::KTBN< GUM_SCALAR >::toString ( ) const
Returns
A human-readable description of the k-DBN.

Definition at line 1085 of file KTBN_tpl.h.

1085 {
1086 const auto join = [](const std::vector< std::string >& v) {
1087 std::string s;
1088 for (const auto& n: v) {
1089 if (!s.empty()) s += ", ";
1090 s += n;
1091 }
1092 return s;
1093 };
1094
1097
1099 for (const auto& arc: _bn_.arcs())
1100 arcs += std::format(" {} -> {}\n",
1101 _bn_.variable(arc.tail()).name(),
1102 _bn_.variable(arc.head()).name());
1103
1104 return std::format("k-TBN (k={}, {} nodes, {} arcs)\n"
1105 " temporal processes ({}): {}\n"
1106 " atemporal variables ({}): {}\n"
1107 "\n arcs ({}):\n{}",
1108 _k_,
1109 _bn_.size(),
1110 _bn_.sizeArcs(),
1111 _temporal_.size(),
1113 _atemporal_.size(),
1115 _bn_.sizeArcs(),
1116 arcs);
1117 }
Size sizeArcs() const
Definition KTBN_tpl.h:195

References _atemporal_, _bn_, _k_, _temporal_, and arcs().

Here is the call graph for this function:

◆ toUnrolledDot() [1/2]

template<GUM_Numeric GUM_SCALAR>
std::string gum::KTBN< GUM_SCALAR >::toUnrolledDot ( Size T,
bool highlightReplicated,
const dot::DotOptions & options ) const

Returns a Graphviz DOT string of the k-DBN unrolled over T time slices, with the options given by the caller (the look is the one of the section dynamicBN of the configuration : size of the graph, colors of the clusters).

The options of a node and of an arc are indexed by the identifiers of the nodes of the unrolled BayesNet, see unroll().

Exceptions
OperationNotAllowedif T < k.

Definition at line 1130 of file KTBN_tpl.h.

1132 {
1133 if (T < _k_)
1134 GUM_ERROR(OperationNotAllowed, "toUnrolledDot: T=" << T << " must be >= k=" << _k_ << ".")
1136 }
BayesNet< GUM_SCALAR > unroll(Size nbTimeSlices) const
Unrolls the k-DBN into a standard gum::BayesNet.
Definition KTBN_tpl.h:698

References _k_, _timeSlicesToDot_(), GUM_ERROR, and unroll().

Here is the call graph for this function:

◆ toUnrolledDot() [2/2]

template<GUM_Numeric GUM_SCALAR>
std::string gum::KTBN< GUM_SCALAR >::toUnrolledDot ( Size T,
bool highlightReplicated = false ) const

Returns a Graphviz DOT string of the k-DBN unrolled over T time slices.

Parameters
TTotal number of time slices to display. Must be \(\geq k\).
highlightReplicatedIf true, shade slices \(\geq k\) (lightcyan) differently from the template slices \(0, \ldots, k-1\) (gray).
Exceptions
OperationNotAllowedif T < k.

Definition at line 1125 of file KTBN_tpl.h.

1125 {
1127 }
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

References toUnrolledDot().

Referenced by toUnrolledDot().

Here is the call graph for this function:
Here is the caller graph for this function:

◆ unroll()

template<GUM_Numeric GUM_SCALAR>
BayesNet< GUM_SCALAR > gum::KTBN< GUM_SCALAR >::unroll ( Size nbTimeSlices) const

Unrolls the k-DBN into a standard gum::BayesNet.

The result has exactly nbTimeSlices time slices. Slices \(0, \ldots, k-1\) are copied verbatim from the template; every additional slice \(t \geq k\) replicates the incoming pattern of slice \(k-1\) (the transition kernel), shifting each temporal parent's slice accordingly so that lags are preserved. Variables are named with the same base[slice] bracket-notation convention (atemporal variables keep their name).

Parameters
nbTimeSlicesTotal number of time slices of the unrolled network.
Exceptions
OperationNotAllowedif nbTimeSlices is smaller than \(k\).

Definition at line 698 of file KTBN_tpl.h.

698 {
699 if (nbTimeSlices < _k_)
701 "Cannot unroll over " << nbTimeSlices << " slices: fewer than the order k=" << _k_
702 << ".")
703
705 const int kernelSlice = static_cast< int >(_k_ - 1);
706
707 // 1. atemporal variables (kept as-is)
709 unrolled.add(_bn_.variable(_bn_.idFromName(a)));
710 }
711
712 // 2. temporal variables, instantiated for every slice 0..nbTimeSlices-1
713 for (const auto& p: _temporal_) {
715 = _bn_.variable(_bn_.idFromName(_encode_(p, kernelSlice)));
716 for (Size t = 0; t < nbTimeSlices; ++t) {
717 // clone() to rename; BayesNet::add() clones again internally (unavoidable via public API).
719 clone->setName(_encode_(p, static_cast< int >(t)));
721 }
722 }
723
724 // 3. template arcs (slices 0..k-1) are copied verbatim: the engine names of
725 // the template already match the unrolled names for those slices.
726 for (const auto& arc: _bn_.arcs()) {
727 unrolled.addArc(_bn_.variable(arc.tail()).name(), _bn_.variable(arc.head()).name());
728 }
729
730 // 4. CPTs of the template nodes (slices 0..k-1): copied by name.
731 for (const NodeId n: _bn_.nodes()) {
732 unrolled.cpt(_bn_.variable(n).name()).fillWith(_bn_.cpt(n));
733 }
734
735 // 5. transition kernel: for each extra slice t = k..nbTimeSlices-1,
736 // add arcs and fill the CPT in one pass using lags computed once per process.
737 for (const auto& p: _temporal_) {
738 const NodeId lastSliceNodeId = _bn_.idFromName(_encode_(p, kernelSlice));
740
741 // (parBase, lag): lag == ATEMPORAL for static parents, otherwise lag = (k-1) - parSlice.
743 for (const auto& [parBase, parSlice]: parents(p, kernelSlice)) {
744 const int lag = (parSlice == ATEMPORAL) ? ATEMPORAL : kernelSlice - parSlice;
745 lags.emplace_back(parBase, lag);
746 }
747
750
751 for (Size t = _k_; t < nbTimeSlices; ++t) {
752 const std::string child = _encode_(p, static_cast< int >(t));
753
754 // Add arcs and build the unrolled->template name mapping simultaneously.
757 for (const auto& [parBase, lag]: lags) {
758 if (lag == ATEMPORAL) {
761 } else {
762 const std::string parName = _encode_(parBase, static_cast< int >(t) - lag);
765 }
766 }
767
768 // Fill the CPT using the mapping built above.
771 templateVarNames.reserve(unrolledCpt.nbrDim());
772 for (Idx i = 0; i < unrolledCpt.nbrDim(); ++i) {
774 }
776 }
777 }
778
779 return unrolled;
780 }

References _atemporal_, _bn_, _encode_(), _k_, _temporal_, ATEMPORAL, gum::HashTable< Key, Val >::clear(), gum::DiscreteVariable::clone(), GUM_ERROR, gum::HashTable< Key, Val >::insert(), and parents().

Referenced by toUnrolledDot().

Here is the call graph for this function:
Here is the caller graph for this function:

◆ variable() [1/2]

template<GUM_Numeric GUM_SCALAR>
INLINE const DiscreteVariable & gum::KTBN< GUM_SCALAR >::variable ( std::string_view base,
int slice ) const

Returns the gum::DiscreteVariable of a (process, slice) couple.

Use KTBN::ATEMPORAL as slice for atemporal variables.

Exceptions
NotFoundif no such variable exists.
OutOfBoundsif slice is out of \([0,k-1]\) for a temporal variable.
OperationNotAllowedif the temporal/atemporal kind does not match slice.

Definition at line 463 of file KTBN_tpl.h.

464 {
465 return _bn_.variable(_validateVariable_(base, slice));
466 }

References _bn_, and _validateVariable_().

Referenced by variable().

Here is the call graph for this function:
Here is the caller graph for this function:

◆ variable() [2/2]

template<GUM_Numeric GUM_SCALAR>
INLINE const DiscreteVariable & gum::KTBN< GUM_SCALAR >::variable ( std::string_view node_name) const

Same, using an engine name: resolved via _determineNode_, so "X[1]" and bare "C" are both accepted.

Definition at line 469 of file KTBN_tpl.h.

469 {
470 const auto [b, s] = _determineNode_(std::string{node_name});
471 return variable(b, s);
472 }

References _determineNode_(), and variable().

Here is the call graph for this function:

Member Data Documentation

◆ _atemporal_

template<GUM_Numeric GUM_SCALAR>
std::unordered_set< std::string > gum::KTBN< GUM_SCALAR >::_atemporal_
private

◆ _bn_

template<GUM_Numeric GUM_SCALAR>
BayesNet< GUM_SCALAR > gum::KTBN< GUM_SCALAR >::_bn_
private

◆ _k_

template<GUM_Numeric GUM_SCALAR>
Size gum::KTBN< GUM_SCALAR >::_k_
private

◆ _temporal_

template<GUM_Numeric GUM_SCALAR>
std::unordered_set< std::string > gum::KTBN< GUM_SCALAR >::_temporal_
private

◆ ATEMPORAL

template<GUM_Numeric GUM_SCALAR>
int gum::KTBN< GUM_SCALAR >::ATEMPORAL = -1
staticconstexpr

Conventional time-slice value denoting an atemporal (static) variable.

Definition at line 204 of file KTBN.h.

Referenced by gum::learning::KTBNDatabaseGenerator< GUM_SCALAR >::_build_(), gum::learning::KTBNLearner< GUM_SCALAR >::_build_(), gum::learning::IKTBNLearner< GUM_SCALAR >::_checkArcTemporallyFeasible_(), gum::learning::KTBNDatabaseGenerator< GUM_SCALAR >::_decode_(), _decodeName_(), _determineNode_(), gum::learning::IKTBNLearner< GUM_SCALAR >::_determineNode_(), _determineNodesFromBN_(), gum::learning::KTBNDatabaseGenerator< GUM_SCALAR >::_drawSamples_(), _encode_(), gum::learning::IKTBNLearner< GUM_SCALAR >::_encode_(), gum::learning::KTBNLearner< GUM_SCALAR >::_forEachAllSlicesPair_(), gum::learning::KTBNAdaptiveLearner< GUM_SCALAR >::_forEachScoredNode_(), gum::learning::KTBNLearner< GUM_SCALAR >::_forOwningLearner_(), gum::KTBNGenerator< GUM_SCALAR >::_legalArcs_(), gum::learning::KTBNAdaptiveLearner< GUM_SCALAR >::_raiseKMinForSlice_(), _timeSlicesToDot_(), _validateAdd_(), _validateVariable_(), gum::learning::KTBNAdaptiveLearner< GUM_SCALAR >::_verifyBase_(), addArc(), gum::learning::KTBNAdaptiveLearner< GUM_SCALAR >::addForbiddenArcAllSlices(), gum::learning::KTBNLearner< GUM_SCALAR >::addNoChildrenNode(), gum::learning::KTBNLearner< GUM_SCALAR >::addNoParentNode(), gum::learning::KTBNLearner< GUM_SCALAR >::addPossibleEdge(), changeVariableName(), gum::learning::KTBNLearner< GUM_SCALAR >::domainSize(), gum::learning::KTBNAdaptiveLearner< GUM_SCALAR >::eraseForbiddenArcAllSlices(), gum::learning::KTBNLearner< GUM_SCALAR >::eraseNoChildrenNode(), gum::learning::KTBNLearner< GUM_SCALAR >::eraseNoParentNode(), gum::learning::KTBNLearner< GUM_SCALAR >::erasePossibleEdge(), gum::learning::KTBNLearner< GUM_SCALAR >::learnParameters(), nodes(), gum::learning::KTBNDatabaseGenerator< GUM_SCALAR >::setVarOrderTopological(), gum::learning::KTBNLearner< GUM_SCALAR >::state(), summaryGraph(), and unroll().


The documentation for this class was generated from the following files: