aGrUM 3.3.2
a C++ library for (probabilistic) graphical models
KTBN_tpl.h
Go to the documentation of this file.
1/****************************************************************************
2 * This file is part of the aGrUM/pyAgrum library. *
3 * *
4 * Copyright (c) 2005-2026 by *
5 * - Pierre-Henri WUILLEMIN(_at_LIP6) *
6 * - Christophe GONZALES(_at_AMU) *
7 * *
8 * The aGrUM/pyAgrum library is free software; you can redistribute it *
9 * and/or modify it under the terms of either : *
10 * *
11 * - the GNU Lesser General Public License as published by *
12 * the Free Software Foundation, either version 3 of the License, *
13 * or (at your option) any later version, *
14 * - the MIT license (MIT), *
15 * - or both in dual license, as here. *
16 * *
17 * (see https://agrum.gitlab.io/articles/dual-licenses-lgplv3mit.html) *
18 * *
19 * This aGrUM/pyAgrum library is distributed in the hope that it will be *
20 * useful, but WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, *
21 * INCLUDING BUT NOT LIMITED TO THE WARRANTIES MERCHANTABILITY or FITNESS *
22 * FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE *
23 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER *
24 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, *
25 * ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR *
26 * OTHER DEALINGS IN THE SOFTWARE. *
27 * *
28 * See LICENCES for more details. *
29 * *
30 * SPDX-FileCopyrightText: Copyright 2005-2026 *
31 * - Pierre-Henri WUILLEMIN(_at_LIP6) *
32 * - Christophe GONZALES(_at_AMU) *
33 * SPDX-License-Identifier: LGPL-3.0-or-later OR MIT *
34 * *
35 * Contact : info_at_agrum_dot_org *
36 * homepage : http://agrum.gitlab.io *
37 * gitlab : https://gitlab.com/agrumery/agrum *
38 * *
39 ****************************************************************************/
40
41
48
49#pragma once
50
51#include <algorithm>
52#include <cctype>
53#include <format>
54#include <map>
55#include <set>
56#include <sstream>
57#include <tuple>
58
63#include <agrum/KTBN/KTBN.h>
64
65namespace gum {
66
67 // ===========================================================================
68 // KTBNModality
69 // ===========================================================================
70
71 template < std::integral T >
72 KTBNModality::KTBNModality(T modality) : isLabel(false), index(static_cast< Idx >(modality)) {}
73
74 // ===========================================================================
75 // Private naming helpers (the only place names are produced / parsed)
76 // ===========================================================================
77
78 template < GUM_Numeric GUM_SCALAR >
79 INLINE std::string KTBN< GUM_SCALAR >::_encode_(std::string_view base, int slice) const {
80 if (slice == ATEMPORAL) return std::string{base};
81 return std::string{base} + '[' + std::to_string(slice) + ']';
82 }
83
84 template < GUM_Numeric GUM_SCALAR >
85 std::pair< std::string, int > KTBN< GUM_SCALAR >::_decodeName_(std::string_view name) const {
86 const std::size_t bracketPos = name.rfind('[');
87 if (bracketPos == std::string_view::npos) return {std::string{name}, ATEMPORAL};
88
89 const std::string_view bracketContent = name.substr(bracketPos + 1);
90 if (bracketContent.empty() || bracketContent.back() != ']')
91 return {std::string{name}, ATEMPORAL};
92
93 const std::string_view digits = bracketContent.substr(0, bracketContent.size() - 1);
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 {
100 slice = std::stoi(std::string{digits});
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 }
107
108 template < GUM_Numeric GUM_SCALAR >
109 INLINE std::pair< std::string, int >
110 KTBN< GUM_SCALAR >::_determineNode_(const std::string& name) const {
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 }
116
117 template < GUM_Numeric GUM_SCALAR >
118 std::vector< std::pair< std::string, int > >
120 std::vector< std::pair< std::string, int > > result;
121 result.reserve(ids.size());
122 for (const NodeId id: ids)
123 result.push_back(_determineNode_(_bn_.variable(id).name()));
124 return result;
125 }
126
127 // ===========================================================================
128 // Constructors and destructor
129 // ===========================================================================
130
131 template < GUM_Numeric GUM_SCALAR >
133 if (k == 0) GUM_ERROR(InvalidArgument, "A k-DBN must have an order k >= 1.")
134 GUM_CONSTRUCTOR(KTBN)
135 }
136
137 template < GUM_Numeric GUM_SCALAR >
139 GUM_DESTRUCTOR(KTBN)
140 }
141
142 template < GUM_Numeric GUM_SCALAR >
143 KTBN< GUM_SCALAR >::KTBN(const KTBN< GUM_SCALAR >& source) :
144 _k_(source._k_), _bn_(source._bn_), _temporal_(source._temporal_),
145 _atemporal_(source._atemporal_) {
146 GUM_CONS_CPY(KTBN)
147 }
148
149 template < GUM_Numeric GUM_SCALAR >
150 KTBN< GUM_SCALAR >::KTBN(KTBN< GUM_SCALAR >&& source) noexcept :
151 _k_(source._k_), _bn_(std::move(source._bn_)), _temporal_(std::move(source._temporal_)),
152 _atemporal_(std::move(source._atemporal_)) {
153 GUM_CONS_MOV(KTBN)
154 }
155
156 template < GUM_Numeric GUM_SCALAR >
157 KTBN< GUM_SCALAR >& KTBN< GUM_SCALAR >::operator=(const KTBN< GUM_SCALAR >& source) {
158 if (this != &source) {
159 GUM_OP_CPY(KTBN);
160 _k_ = source._k_;
161 _bn_ = source._bn_;
162 _temporal_ = source._temporal_;
163 _atemporal_ = source._atemporal_;
164 }
165 return *this;
166 }
167
168 template < GUM_Numeric GUM_SCALAR >
169 KTBN< GUM_SCALAR >& KTBN< GUM_SCALAR >::operator=(KTBN< GUM_SCALAR >&& source) noexcept {
170 if (this != &source) {
171 GUM_OP_MOV(KTBN);
172 _k_ = source._k_;
173 _bn_ = std::move(source._bn_);
174 _temporal_ = std::move(source._temporal_);
175 _atemporal_ = std::move(source._atemporal_);
176 }
177 return *this;
178 }
179
180 // ===========================================================================
181 // Accessors
182 // ===========================================================================
183
184 template < GUM_Numeric GUM_SCALAR >
186 return _k_;
187 }
188
189 template < GUM_Numeric GUM_SCALAR >
191 return _bn_.size();
192 }
193
194 template < GUM_Numeric GUM_SCALAR >
196 return _bn_.sizeArcs();
197 }
198
199 template < GUM_Numeric GUM_SCALAR >
200 INLINE bool KTBN< GUM_SCALAR >::empty() const {
201 return _bn_.empty();
202 }
203
204 template < GUM_Numeric GUM_SCALAR >
206 _bn_.clear();
207 _temporal_.clear();
208 _atemporal_.clear();
209 }
210
211 // ===========================================================================
212 // Variable management
213 // ===========================================================================
214
215 template < GUM_Numeric GUM_SCALAR >
216 void KTBN< GUM_SCALAR >::_validateAdd_(const std::string& base, bool temporal) const {
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.")
224 if (otherSet.contains(base))
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 }
263
264 template < GUM_Numeric GUM_SCALAR >
265 void KTBN< GUM_SCALAR >::add(const DiscreteVariable& var, bool temporal) {
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).
272 std::unique_ptr< DiscreteVariable > clone(var.clone());
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 }
283
284 template < GUM_Numeric GUM_SCALAR >
285 void KTBN< GUM_SCALAR >::add(std::string_view fast_description,
286 bool temporal,
287 unsigned int default_nbrmod) {
288 auto v = fastVariable< GUM_SCALAR >(std::string{fast_description}, Size(default_nbrmod));
289 add(*v, temporal);
290 }
291
292 template < GUM_Numeric GUM_SCALAR >
294 add(var, true);
295 }
296
297 template < GUM_Numeric GUM_SCALAR >
299 add(var, false);
300 }
301
302 template < GUM_Numeric GUM_SCALAR >
303 INLINE void KTBN< GUM_SCALAR >::addTemporal(std::string_view fast_description,
304 unsigned int default_nbrmod) {
305 add(fast_description, true, default_nbrmod);
306 }
307
308 template < GUM_Numeric GUM_SCALAR >
309 INLINE void KTBN< GUM_SCALAR >::addAtemporal(std::string_view fast_description,
310 unsigned int default_nbrmod) {
311 add(fast_description, false, default_nbrmod);
312 }
313
314 // ===========================================================================
315 // Variable queries
316 // ===========================================================================
317
318 template < GUM_Numeric GUM_SCALAR >
319 INLINE bool KTBN< GUM_SCALAR >::exists(std::string_view base) const {
320 const std::string baseStr{base};
321 return _temporal_.contains(baseStr) || _atemporal_.contains(baseStr);
322 }
323
324 template < GUM_Numeric GUM_SCALAR >
325 INLINE const std::unordered_set< std::string >& KTBN< GUM_SCALAR >::temporalVarNames() const {
326 return _temporal_;
327 }
328
329 template < GUM_Numeric GUM_SCALAR >
330 INLINE const std::unordered_set< std::string >& KTBN< GUM_SCALAR >::atemporalVarNames() const {
331 return _atemporal_;
332 }
333
334 template < GUM_Numeric GUM_SCALAR >
336 return _temporal_.size();
337 }
338
339 template < GUM_Numeric GUM_SCALAR >
341 return _atemporal_.size();
342 }
343
344 template < GUM_Numeric GUM_SCALAR >
345 std::vector< std::pair< std::string, int > > KTBN< GUM_SCALAR >::nodes() const {
346 std::vector< std::pair< std::string, int > > result;
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 }
355
356 template < GUM_Numeric GUM_SCALAR >
357 std::vector< std::pair< std::string, int > > KTBN< GUM_SCALAR >::parents(std::string_view base,
358 int slice) const {
359 return _determineNodeSet_(_bn_.parents(_validateVariable_(base, slice)));
360 }
361
362 template < GUM_Numeric GUM_SCALAR >
363 std::vector< std::pair< std::string, int > >
364 KTBN< GUM_SCALAR >::parents(std::string_view node_name) const {
365 const auto [b, s] = _determineNode_(std::string{node_name});
366 return parents(b, s);
367 }
368
369 template < GUM_Numeric GUM_SCALAR >
370 std::vector< std::pair< std::string, int > > KTBN< GUM_SCALAR >::children(std::string_view base,
371 int slice) const {
372 return _determineNodeSet_(_bn_.children(_validateVariable_(base, slice)));
373 }
374
375 template < GUM_Numeric GUM_SCALAR >
376 std::vector< std::pair< std::string, int > >
377 KTBN< GUM_SCALAR >::children(std::string_view node_name) const {
378 const auto [b, s] = _determineNode_(std::string{node_name});
379 return children(b, s);
380 }
381
382 template < GUM_Numeric GUM_SCALAR >
383 void KTBN< GUM_SCALAR >::erase(std::string_view base) {
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 }
397
398 template < GUM_Numeric GUM_SCALAR >
399 void KTBN< GUM_SCALAR >::changeVariableName(std::string_view oldBase, std::string_view newBase) {
400 const std::string oldStr{oldBase};
401 const std::string newStr{newBase};
402
403 if (oldStr == newStr) return;
404 if (newStr.empty()) GUM_ERROR(InvalidArgument, "New base name must not be empty.")
405
406 if (!_temporal_.contains(oldStr) && !_atemporal_.contains(oldStr))
407 GUM_ERROR(NotFound, "No variable named '" << oldStr << "' in the k-DBN.")
408 if (_temporal_.contains(newStr) || _atemporal_.contains(newStr))
409 GUM_ERROR(DuplicateLabel, "A variable named '" << newStr << "' already exists.")
410
411 if (_temporal_.contains(oldStr)) {
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 {
423 const auto [decodedBase, decodedSlice] = _decodeName_(newStr);
424 if (decodedSlice != ATEMPORAL && _temporal_.contains(decodedBase))
426 "'" << newStr << "' conflicts with temporal process '" << decodedBase
427 << "': that name is already used by its slice nodes.")
428 _bn_.changeVariableName(oldStr, newStr);
429 _atemporal_.erase(oldStr);
430 _atemporal_.insert(newStr);
431 }
432 }
433
434 template < GUM_Numeric GUM_SCALAR >
435 NodeId KTBN< GUM_SCALAR >::_validateVariable_(std::string_view base, int slice) const {
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 }
445 return _bn_.idFromName(baseStr);
446 }
447
448 if (!_temporal_.contains(baseStr)) {
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 << "'.")
459 return _bn_.idFromName(_encode_(baseStr, slice));
460 }
461
462 template < GUM_Numeric GUM_SCALAR >
463 INLINE const DiscreteVariable& KTBN< GUM_SCALAR >::variable(std::string_view base,
464 int slice) const {
465 return _bn_.variable(_validateVariable_(base, slice));
466 }
467
468 template < GUM_Numeric GUM_SCALAR >
469 INLINE const DiscreteVariable& KTBN< GUM_SCALAR >::variable(std::string_view node_name) const {
470 const auto [b, s] = _determineNode_(std::string{node_name});
471 return variable(b, s);
472 }
473
474 template < GUM_Numeric GUM_SCALAR >
475 INLINE int KTBN< GUM_SCALAR >::timeSlice(const DiscreteVariable& var) const {
476 _bn_.idFromName(var.name()); // throws NotFound if var is not in this k-DBN
477 return _determineNode_(var.name()).second;
478 }
479
480 template < GUM_Numeric GUM_SCALAR >
481 INLINE std::string KTBN< GUM_SCALAR >::baseName(const DiscreteVariable& var) const {
482 _bn_.idFromName(var.name()); // throws NotFound if var is not in this k-DBN
483 return _determineNode_(var.name()).first;
484 }
485
486 // ===========================================================================
487 // Arc management
488 // ===========================================================================
489
490 template < GUM_Numeric GUM_SCALAR >
491 void KTBN< GUM_SCALAR >::addArc(std::string_view tailBase,
492 int tailSlice,
493 std::string_view headBase,
494 int headSlice) {
495 const NodeId tail = _validateVariable_(tailBase, tailSlice);
496 const NodeId head = _validateVariable_(headBase, headSlice);
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 }
511
512 template < GUM_Numeric GUM_SCALAR >
513 void KTBN< GUM_SCALAR >::eraseArc(std::string_view tailBase,
514 int tailSlice,
515 std::string_view headBase,
516 int headSlice) {
517 _bn_.eraseArc(_validateVariable_(tailBase, tailSlice), _validateVariable_(headBase, headSlice));
518 }
519
520 template < GUM_Numeric GUM_SCALAR >
521 bool KTBN< GUM_SCALAR >::existsArc(std::string_view tailBase,
522 int tailSlice,
523 std::string_view headBase,
524 int headSlice) const {
525 return _bn_.existsArc(_validateVariable_(tailBase, tailSlice),
526 _validateVariable_(headBase, headSlice));
527 }
528
529 template < GUM_Numeric GUM_SCALAR >
530 void KTBN< GUM_SCALAR >::addArc(std::string_view tail, std::string_view head) {
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 }
535
536 template < GUM_Numeric GUM_SCALAR >
537 void KTBN< GUM_SCALAR >::eraseArc(std::string_view tail, std::string_view head) {
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 }
542
543 template < GUM_Numeric GUM_SCALAR >
544 bool KTBN< GUM_SCALAR >::existsArc(std::string_view tail, std::string_view head) const {
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 }
549
550 template < GUM_Numeric GUM_SCALAR >
551 std::vector< std::pair< std::pair< std::string, int >, std::pair< std::string, int > > >
553 std::vector< std::pair< std::pair< std::string, int >, std::pair< std::string, int > > > result;
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 }
561
562 // ===========================================================================
563 // Conditional probability tables
564 // ===========================================================================
565
566 template < GUM_Numeric GUM_SCALAR >
567 INLINE const Tensor< GUM_SCALAR >& KTBN< GUM_SCALAR >::cpt(std::string_view base,
568 int slice) const {
569 return _bn_.cpt(_validateVariable_(base, slice));
570 }
571
572 template < GUM_Numeric GUM_SCALAR >
573 INLINE const Tensor< GUM_SCALAR >& KTBN< GUM_SCALAR >::cpt(std::string_view node_name) const {
574 const auto [b, s] = _determineNode_(std::string{node_name});
575 return cpt(b, s);
576 }
577
578 template < GUM_Numeric GUM_SCALAR >
580 _bn_.generateCPTs();
581 }
582
583 template < GUM_Numeric GUM_SCALAR >
584 INLINE void KTBN< GUM_SCALAR >::generateCPT(std::string_view base, int slice) const {
585 _bn_.generateCPT(_validateVariable_(base, slice));
586 }
587
588 template < GUM_Numeric GUM_SCALAR >
589 INLINE void KTBN< GUM_SCALAR >::generateCPT(std::string_view node_name) const {
590 const auto [b, s] = _determineNode_(std::string{node_name});
591 generateCPT(b, s);
592 }
593
594 template < GUM_Numeric GUM_SCALAR >
596 std::string_view base,
597 int slice,
598 const std::map< std::pair< std::string, int >, KTBNModality >& parents,
599 const std::vector< GUM_SCALAR >& distribution) const {
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.
619 Instantiation inst(cpt);
620 for (const auto& [parNode, parVal]: parents) {
621 const auto& [parBase, parSlice] = parNode;
622 const NodeId parId = _validateVariable_(parBase, parSlice);
623 const DiscreteVariable& parVar = _bn_.variable(parId);
624 if (parId == id || !cpt.contains(parVar))
626 "fillCPT: '" << parBase << "' is not a parent of the target node.")
627 inst.chgVal(parVar, parVal.toIndex(parVar));
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 }
636
637 template < GUM_Numeric GUM_SCALAR >
639 std::string_view node_name,
640 const std::map< std::variant< std::string, std::pair< std::string, int > >, KTBNModality >&
641 parents,
642 const std::vector< GUM_SCALAR >& distribution) const {
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.
663 Instantiation inst(cpt);
664 NodeSet seen;
665 for (const auto& [parKey, parVal]: parents) {
666 const std::string parName
667 = std::holds_alternative< std::string >(parKey)
668 ? std::get< std::string >(parKey)
669 : _encode_(std::get< std::pair< std::string, int > >(parKey).first,
670 std::get< std::pair< std::string, int > >(parKey).second);
671 const NodeId parId = _bn_.idFromName(parName);
672 const DiscreteVariable& parVar = _bn_.variable(parId);
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 }
687
688 // ===========================================================================
689 // Transformations
690 // ===========================================================================
691
692 template < GUM_Numeric GUM_SCALAR >
693 BayesNet< GUM_SCALAR > KTBN< GUM_SCALAR >::toBN() const {
694 return BayesNet< GUM_SCALAR >(_bn_);
695 }
696
697 template < GUM_Numeric GUM_SCALAR >
698 BayesNet< GUM_SCALAR > KTBN< GUM_SCALAR >::unroll(Size nbTimeSlices) const {
699 if (nbTimeSlices < _k_)
701 "Cannot unroll over " << nbTimeSlices << " slices: fewer than the order k=" << _k_
702 << ".")
703
704 BayesNet< GUM_SCALAR > unrolled;
705 const int kernelSlice = static_cast< int >(_k_ - 1);
706
707 // 1. atemporal variables (kept as-is)
708 for (const auto& a: _atemporal_) {
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_) {
714 const DiscreteVariable& templateVar
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).
718 std::unique_ptr< DiscreteVariable > clone(templateVar.clone());
719 clone->setName(_encode_(p, static_cast< int >(t)));
720 unrolled.add(*clone);
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));
739 const Tensor< GUM_SCALAR >& templateCpt = _bn_.cpt(lastSliceNodeId);
740
741 // (parBase, lag): lag == ATEMPORAL for static parents, otherwise lag = (k-1) - parSlice.
742 std::vector< std::pair< std::string, int > > lags;
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
748 HashTable< std::string, std::string > unrolledToTemplate;
749 std::vector< std::string > templateVarNames;
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.
755 unrolledToTemplate.clear();
756 unrolledToTemplate.insert(child, _encode_(p, kernelSlice));
757 for (const auto& [parBase, lag]: lags) {
758 if (lag == ATEMPORAL) {
759 unrolled.addArc(parBase, child);
760 unrolledToTemplate.insert(parBase, parBase);
761 } else {
762 const std::string parName = _encode_(parBase, static_cast< int >(t) - lag);
763 unrolled.addArc(parName, child);
764 unrolledToTemplate.insert(parName, _encode_(parBase, kernelSlice - lag));
765 }
766 }
767
768 // Fill the CPT using the mapping built above.
769 const Tensor< GUM_SCALAR >& unrolledCpt = unrolled.cpt(child);
770 templateVarNames.clear();
771 templateVarNames.reserve(unrolledCpt.nbrDim());
772 for (Idx i = 0; i < unrolledCpt.nbrDim(); ++i) {
773 templateVarNames.push_back(unrolledToTemplate[unrolledCpt.variable(i).name()]);
774 }
775 unrolledCpt.fillWith(templateCpt, templateVarNames);
776 }
777 }
778
779 return unrolled;
780 }
781
782 // ===========================================================================
783 // Persistence and conversion
784 // ===========================================================================
785
786 template < GUM_Numeric GUM_SCALAR >
787 std::pair< std::string, bool > KTBN< GUM_SCALAR >::_resolveGumFormat_(std::string_view filename) {
788 // The extension selects the format: ".jgum" is text, anything else is binary
789 // and gets a ".bgum" extension appended if missing.
790 std::string filepath{filename};
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 }
795
796 template < GUM_Numeric GUM_SCALAR >
797 void KTBN< GUM_SCALAR >::save(std::string_view filename) const {
798 const auto [filepath, binary] = _resolveGumFormat_(filename);
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.
804 auto join = [](const std::unordered_set< std::string >& names) {
805 std::string out;
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
816 BayesNet< GUM_SCALAR > annotated = _bn_;
817 annotated.setProperty("KTBN.k", std::to_string(_k_));
818 annotated.setProperty("KTBN.temporal", join(_temporal_));
819 annotated.setProperty("KTBN.atemporal", join(_atemporal_));
820 GumBNWriter< GUM_SCALAR > writer(binary);
821 writer.write(filepath, annotated);
822 }
823
824 template < GUM_Numeric GUM_SCALAR >
825 KTBN< GUM_SCALAR > KTBN< GUM_SCALAR >::load(std::string_view filename) {
826 const auto [filepath, binary] = _resolveGumFormat_(filename);
827
828 BayesNet< GUM_SCALAR > bn;
829 GumBNReader< GUM_SCALAR > reader(&bn, filepath, binary);
830 const Size nbErr = reader.proceed();
831 if (nbErr > 0) {
832 std::stringstream stream;
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
844 auto split = [](std::string_view csv, std::unordered_set< std::string >& out) {
845 std::string current;
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 }
871 KTBN< GUM_SCALAR > res(k_val);
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 }
878
879 template < GUM_Numeric GUM_SCALAR >
880 KTBN< GUM_SCALAR >
881 KTBN< GUM_SCALAR >::fromBN(const BayesNet< GUM_SCALAR >& bn,
882 const std::unordered_set< std::string >& atemporalNodes,
883 std::vector< std::string >* warnings) {
884 KTBN< GUM_SCALAR > res(1); // _determineNodesFromBN_ below will modify this k=1
885 res._bn_ = bn;
886 res._determineNodesFromBN_(atemporalNodes, warnings);
887 return res;
888 }
889
890 template < GUM_Numeric GUM_SCALAR >
892 const std::unordered_set< std::string >& atemporalNodes,
893 std::vector< std::string >* warnings) {
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).
913 const auto decodeTrailingSlice = [](std::string_view name) -> std::pair< std::string, int > {
914 std::size_t pos = name.size();
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 {
922 slice = std::stoi(std::string{digits});
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;
943 if (_decodeName_(name).second != ATEMPORAL) {
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
965 const auto [base, slice] = hasBracket ? _decodeName_(name) : decodeTrailingSlice(name);
966
967 if (slice == ATEMPORAL) {
968 _atemporal_.insert(base);
969 } else {
970 if (!slicesPerProcess.exists(base)) {
971 slicesPerProcess.insert(base, HashTable< int, NodeId >());
972 discovered.push_back(base);
973 }
974
975 if (slicesPerProcess[base].exists(slice))
977 "Two variables map to process '" << base << "' at slice " << slice << ".")
978
979 slicesPerProcess[base].insert(slice, n);
980
981 if (slice > maxSlice) maxSlice = slice;
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";
993 for (const auto& base: discovered) {
994 const HashTable< int, NodeId >& sliceMap = slicesPerProcess[base];
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
1002 std::string missing;
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))
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
1044 std::string reclassified;
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;
1069 if (headSlice == ATEMPORAL && tailSlice != ATEMPORAL)
1071 "The network has a temporal->atemporal arc into '"
1072 << _bn_.variable(arc.head()).name() << "'.")
1073 if (headSlice != ATEMPORAL && tailSlice != ATEMPORAL && tailSlice > headSlice)
1075 "The network has a future->past arc " << _bn_.variable(arc.tail()).name() << "->"
1076 << _bn_.variable(arc.head()).name() << ".")
1077 }
1078 }
1079
1080 // ===========================================================================
1081 // Various
1082 // ===========================================================================
1083
1084 template < GUM_Numeric GUM_SCALAR >
1085 std::string KTBN< GUM_SCALAR >::toString() const {
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
1095 const std::vector< std::string > temporalNames(_temporal_.begin(), _temporal_.end());
1096 const std::vector< std::string > atemporalNames(_atemporal_.begin(), _atemporal_.end());
1097
1098 std::string arcs;
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(),
1112 join(temporalNames),
1113 _atemporal_.size(),
1114 join(atemporalNames),
1115 _bn_.sizeArcs(),
1116 arcs);
1117 }
1118
1119 template < GUM_Numeric GUM_SCALAR >
1120 std::string KTBN< GUM_SCALAR >::toDot() const {
1121 return _timeSlicesToDot_(_bn_, false, dot::DotOptions());
1122 }
1123
1124 template < GUM_Numeric GUM_SCALAR >
1125 std::string KTBN< GUM_SCALAR >::toUnrolledDot(Size T, bool highlightReplicated) const {
1126 return toUnrolledDot(T, highlightReplicated, dot::DotOptions());
1127 }
1128
1129 template < GUM_Numeric GUM_SCALAR >
1131 bool highlightReplicated,
1132 const dot::DotOptions& options) const {
1133 if (T < _k_)
1134 GUM_ERROR(OperationNotAllowed, "toUnrolledDot: T=" << T << " must be >= k=" << _k_ << ".")
1135 return _timeSlicesToDot_(unroll(T), highlightReplicated, options);
1136 }
1137
1138 // Direct port of pyAgrum's pyagrum.lib.dynamicBN._TimeSlicesToDot: groups nodes by
1139 // timeslice (one cluster per slice, atemporal nodes ungrouped), draws the real arcs
1140 // unconstrained, then chains each temporal variable across consecutive slices with
1141 // invisible edges so every cluster keeps the same vertical variable order.
1142 template < GUM_Numeric GUM_SCALAR >
1143 std::string KTBN< GUM_SCALAR >::_timeSlicesToDot_(const BayesNet< GUM_SCALAR >& bn,
1144 bool highlightReplicated,
1145 const dot::DotOptions& options) const {
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.
1151 std::map< int, std::vector< std::tuple< std::string, std::string, NodeId > > > timeslices;
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)
1183 writer.node(full, dot::nodeAttributes(style, options.node(node), label));
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) {
1196 const std::string& label = std::get< 1 >(node0);
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 }
1210
1211 template < GUM_Numeric GUM_SCALAR >
1212 std::string KTBN< GUM_SCALAR >::_escapeDot_(std::string_view name) {
1213 std::string out;
1214 out.reserve(name.size());
1215 for (const char c: name) {
1216 if (c == '"') out += '\\';
1217 out += c;
1218 }
1219 return out;
1220 }
1221
1222 template < GUM_Numeric GUM_SCALAR >
1223 INLINE std::string KTBN< GUM_SCALAR >::bnToDot() const {
1224 return _bn_.toDot();
1225 }
1226
1227 template < GUM_Numeric GUM_SCALAR >
1229 std::set< std::string > baseNames(_temporal_.begin(), _temporal_.end());
1230 baseNames.insert(_atemporal_.begin(), _atemporal_.end());
1231
1232 const int lastSlice = static_cast< int >(_k_) - 1;
1233 std::set< std::tuple< std::string, std::string, int > > edges;
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
1243 std::stringstream dot;
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 }
1261
1262 template < GUM_Numeric GUM_SCALAR >
1263 std::ostream& operator<<(std::ostream& output, const KTBN< GUM_SCALAR >& kdbn) {
1264 output << kdbn.toString();
1265 return output;
1266 }
1267
1268} // namespace gum
Definition of classe for GUM (json) file output manipulation.
Class representing k-order dynamic Bayesian networks (k-DBN).
void write(std::ostream &output, IBayesNet< GUM_SCALAR > &bn)
Writes a Bayesian network in the output stream.
Base class for discrete random variable.
DiscreteVariable * clone() const override=0
Copy Factory.
virtual Size domainSize() const =0
std::string domain() const override=0
string represent the domain of the variable
Exception : a similar label already exists.
void showErrorCounts(std::ostream &stream=std::cerr) const
Size proceed() final
Parse the file given at construction.
void showElegantErrorsAndWarnings(std::ostream &stream=std::cerr) const
Writes a IBayesNet in the GUM json format.
Definition GumBNWriter.h:80
const const_iterator & cend() const noexcept
Returns the unsafe const_iterator pointing to the end of the hashtable.
value_type & insert(const Key &key, const Val &val)
Adds a new element (actually a copy of this element) into the hash table.
void clear()
Removes all the elements in the hash table.
bool exists(const Key &key) const
Checks whether there exists an element with a given key in the hashtable.
const_iterator cbegin() const
Returns an unsafe const_iterator pointing to the beginning of the hashtable.
Exception : input/output problem.
Class for assigning/browsing values to tuples of discrete variables.
Instantiation & chgVal(const DiscreteVariable &v, Idx newval)
Assign newval to variable v in the Instantiation.
Exception: at least one argument passed to a function is not what was expected.
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
virtual ~KTBN()
Destructor.
Definition KTBN_tpl.h:138
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
Exception : the element we looked for cannot be found.
Exception : operation not allowed.
Exception : out of bound.
bool contains(const Key &k) const
Indicates whether a given elements belong to the set.
Definition set_tpl.h:468
void insert(const Key &k)
Inserts a new element into the set.
Definition set_tpl.h:510
Size size() const noexcept
Returns the number of elements in the set.
Definition set_tpl.h:607
Exception : problem with size.
const std::string & name() const
returns the name of the variable
The options given to a toDot(const DotOptions&).
Definition dotOptions.h:110
const std::string & size() const
direction of the layout, TB or LR
const DotArcOptions * arc(Size tail, Size head) const
the options of the arc from tail to head, or nullptr if none was given for it
const DotNodeOptions * node(Size node) const
the options of a node, or nullptr if none was given for it
Writes a graph in the dot language, statement after statement, in the order of the calls.
Definition dotWriter.h:100
void nodeDefaults(const DotAttributes &attributes)
node [attributes];, the default attributes of the nodes that follow (none : does nothing).
void graphAttributes(const DotAttributes &attributes)
graph [attributes];, the attributes of the graph (does nothing if there is none).
void edgeDefaults(const DotAttributes &attributes)
edge [attributes];, the default attributes of the edges that follow (none : does nothing).
void edge(std::string_view from, std::string_view to, const DotAttributes &attributes={})
an edge from from to to (-> in a directed graph, -- in an undirected one).
void endSubgraph()
Closes the last subgraph that is open.
std::string str() const
The graph written so far, closed. It can be called at any moment, and the writer can be used after.
void node(std::string_view id, const DotAttributes &attributes={})
a node, whose identifier is id (quoted).
void beginSubgraph(std::string_view name, const DotAttributes &attributes={})
Opens a subgraph : subgraph "name" { key="value"; ... .
The statements common to the graphs drawn with graphviz : preamble, attributes of nodes and arcs.
#define GUM_ERROR(type, msg)
Definition exceptions.h:76
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 ...
std::vector< std::string > split(std::string_view str, std::string_view delim)
Split str using the delimiter.
DotAttributes nodeAttributes(const DotStyle &style, const DotNodeOptions *options, std::string_view defaultLabel, std::string_view defaultTooltip)
The attributes of a node : its label and tooltip, and its colors if the options give some.
DotAttributes arcAttributes(const DotArcOptions *options)
The attributes of an arc or an edge given by the options : color, penwidth, label,...
gum is the global namespace for all aGrUM entities
Definition agrum.h:46
std::ostream & operator<<(std::ostream &stream, const AVLTree< Val, Cmp > &tree)
display the content of a tree
std::unique_ptr< DiscreteVariable > fastVariable(std::string var_description, Size default_domain_size)
Create a pointer on a Discrete Variable from a "fast" syntax.
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
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
static DynamicBNDotStyle read()
Definition dotStyle.cpp:168