71 template < std::
integral T >
78 template < GUM_Numeric GUM_SCALAR >
80 if (slice ==
ATEMPORAL)
return std::string{base};
81 return std::string{base} +
'[' + std::to_string(slice) +
']';
84 template < GUM_Numeric GUM_SCALAR >
86 const std::size_t bracketPos = name.rfind(
'[');
87 if (bracketPos == std::string_view::npos)
return {std::string{name},
ATEMPORAL};
89 const std::string_view bracketContent = name.substr(bracketPos + 1);
90 if (bracketContent.empty() || bracketContent.back() !=
']')
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};
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.")
105 return {std::string{name.substr(0, bracketPos)}, slice};
108 template < GUM_Numeric GUM_SCALAR >
109 INLINE std::pair< std::string, int >
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)
131 template < GUM_Numeric GUM_SCALAR >
134 GUM_CONSTRUCTOR(
KTBN)
137 template < GUM_Numeric GUM_SCALAR >
142 template < GUM_Numeric GUM_SCALAR >
149 template < GUM_Numeric GUM_SCALAR >
151 _k_(source._k_),
_bn_(std::move(source._bn_)),
_temporal_(std::move(source._temporal_)),
156 template < GUM_Numeric GUM_SCALAR >
158 if (
this != &source) {
168 template < GUM_Numeric GUM_SCALAR >
170 if (
this != &source) {
173 _bn_ = std::move(source._bn_);
184 template < GUM_Numeric GUM_SCALAR >
189 template < GUM_Numeric GUM_SCALAR >
194 template < GUM_Numeric GUM_SCALAR >
196 return _bn_.sizeArcs();
199 template < GUM_Numeric GUM_SCALAR >
204 template < GUM_Numeric GUM_SCALAR >
215 template < GUM_Numeric GUM_SCALAR >
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.")
231 for (
Size t = 0; t <
_k_; ++t) {
232 const std::string encoded =
_encode_(base,
static_cast< int >(t));
235 "Temporal process '" << base <<
"' at slice " << t <<
" would produce node '"
236 << encoded <<
"' which conflicts with atemporal variable '"
240 const auto [decodedBase, decodedSlice] =
_decodeName_(base);
250 "Atemporal variable name '" << base <<
"' conflicts with temporal process '"
252 <<
"': that name is already used by its slice "
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_ <<
".")
264 template < GUM_Numeric GUM_SCALAR >
266 const std::string base = var.
name();
270 for (
Size t = 0; t <
_k_; ++t) {
272 std::unique_ptr< DiscreteVariable > clone(var.
clone());
273 clone->setName(
_encode_(base,
static_cast< int >(t)));
284 template < GUM_Numeric GUM_SCALAR >
287 unsigned int default_nbrmod) {
292 template < GUM_Numeric GUM_SCALAR >
297 template < GUM_Numeric GUM_SCALAR >
302 template < GUM_Numeric GUM_SCALAR >
304 unsigned int default_nbrmod) {
305 add(fast_description,
true, default_nbrmod);
308 template < GUM_Numeric GUM_SCALAR >
310 unsigned int default_nbrmod) {
311 add(fast_description,
false, default_nbrmod);
318 template < GUM_Numeric GUM_SCALAR >
320 const std::string baseStr{base};
324 template < GUM_Numeric GUM_SCALAR >
329 template < GUM_Numeric GUM_SCALAR >
334 template < GUM_Numeric GUM_SCALAR >
339 template < GUM_Numeric GUM_SCALAR >
344 template < GUM_Numeric GUM_SCALAR >
346 std::vector< std::pair< std::string, int > > result;
347 result.reserve(
size());
352 result.emplace_back(p,
static_cast< int >(t));
356 template < GUM_Numeric GUM_SCALAR >
362 template < GUM_Numeric GUM_SCALAR >
363 std::vector< std::pair< std::string, int > >
369 template < GUM_Numeric GUM_SCALAR >
375 template < GUM_Numeric GUM_SCALAR >
376 std::vector< std::pair< std::string, int > >
382 template < GUM_Numeric GUM_SCALAR >
384 const std::string baseStr{base};
398 template < GUM_Numeric GUM_SCALAR >
400 const std::string oldStr{oldBase};
401 const std::string newStr{newBase};
403 if (oldStr == newStr)
return;
415 "Renaming to '" << newStr <<
"': slice " << t
416 <<
" collides with an atemporal variable.")
418 _bn_.changeVariableName(
_encode_(oldStr,
static_cast< int >(t)),
419 _encode_(newStr,
static_cast< int >(t)));
423 const auto [decodedBase, decodedSlice] =
_decodeName_(newStr);
426 "'" << newStr <<
"' conflicts with temporal process '" << decodedBase
427 <<
"': that name is already used by its slice nodes.")
428 _bn_.changeVariableName(oldStr, newStr);
434 template < GUM_Numeric GUM_SCALAR >
436 const std::string baseStr{base};
442 "'" << baseStr <<
"' is a temporal process but is used as atemporal.")
445 return _bn_.idFromName(baseStr);
451 "'" << baseStr <<
"' is an atemporal variable but is used at slice " << slice
455 if (slice < 0 ||
Size(slice) >=
_k_)
457 "Slice " << slice <<
" is out of [0," << (
_k_ - 1) <<
"] for process '" << baseStr
462 template < GUM_Numeric GUM_SCALAR >
468 template < GUM_Numeric GUM_SCALAR >
474 template < GUM_Numeric GUM_SCALAR >
480 template < GUM_Numeric GUM_SCALAR >
490 template < GUM_Numeric GUM_SCALAR >
493 std::string_view headBase,
501 "A temporal variable cannot be a parent of the atemporal variable '" << headBase
503 }
else if (tailSlice !=
ATEMPORAL && tailSlice > headSlice) {
505 "An arc cannot go from a future slice (" << tailSlice <<
") to a past slice ("
506 << headSlice <<
").")
509 _bn_.addArc(tail, head);
512 template < GUM_Numeric GUM_SCALAR >
515 std::string_view headBase,
520 template < GUM_Numeric GUM_SCALAR >
523 std::string_view headBase,
524 int headSlice)
const {
529 template < GUM_Numeric GUM_SCALAR >
536 template < GUM_Numeric GUM_SCALAR >
543 template < GUM_Numeric GUM_SCALAR >
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()) {
566 template < GUM_Numeric GUM_SCALAR >
572 template < GUM_Numeric GUM_SCALAR >
578 template < GUM_Numeric GUM_SCALAR >
583 template < GUM_Numeric GUM_SCALAR >
588 template < GUM_Numeric GUM_SCALAR >
594 template < GUM_Numeric GUM_SCALAR >
596 std::string_view base,
599 const std::vector< GUM_SCALAR >& distribution)
const {
601 const Tensor< GUM_SCALAR >&
cpt =
_bn_.cpt(
id);
606 "fillCPT: distribution has " << distribution.size() <<
" value(s) but '" << base
607 <<
"' has " << self.
domainSize() <<
" modalities.")
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.")
620 for (
const auto& [parNode, parVal]:
parents) {
621 const auto& [parBase, parSlice] = parNode;
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));
633 cpt.set(inst, distribution[m]);
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 >&
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);
649 "fillCPT: distribution has " << distribution.size() <<
" value(s) but '"
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.")
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);
673 if (parId ==
id || !
cpt.contains(parVar))
675 "fillCPT: '" << parName <<
"' is not a parent of the target node.")
679 inst.
chgVal(parVar, parVal.toIndex(parVar));
684 cpt.set(inst, distribution[m]);
692 template < GUM_Numeric GUM_SCALAR >
694 return BayesNet< GUM_SCALAR >(
_bn_);
697 template < GUM_Numeric GUM_SCALAR >
699 if (nbTimeSlices <
_k_)
701 "Cannot unroll over " << nbTimeSlices <<
" slices: fewer than the order k=" <<
_k_
704 BayesNet< GUM_SCALAR > unrolled;
705 const int kernelSlice =
static_cast< int >(
_k_ - 1);
709 unrolled.add(
_bn_.variable(
_bn_.idFromName(a)));
716 for (
Size t = 0; t < nbTimeSlices; ++t) {
718 std::unique_ptr< DiscreteVariable > clone(templateVar.
clone());
719 clone->setName(
_encode_(p,
static_cast< int >(t)));
720 unrolled.add(*clone);
726 for (
const auto& arc:
_bn_.arcs()) {
727 unrolled.addArc(
_bn_.variable(arc.tail()).name(),
_bn_.variable(arc.head()).name());
732 unrolled.cpt(
_bn_.variable(n).name()).fillWith(
_bn_.cpt(n));
739 const Tensor< GUM_SCALAR >& templateCpt =
_bn_.cpt(lastSliceNodeId);
742 std::vector< std::pair< std::string, int > > lags;
743 for (
const auto& [parBase, parSlice]:
parents(p, kernelSlice)) {
745 lags.emplace_back(parBase, lag);
749 std::vector< std::string > templateVarNames;
751 for (
Size t =
_k_; t < nbTimeSlices; ++t) {
752 const std::string child =
_encode_(p,
static_cast< int >(t));
755 unrolledToTemplate.
clear();
757 for (
const auto& [parBase, lag]: lags) {
759 unrolled.addArc(parBase, child);
760 unrolledToTemplate.
insert(parBase, parBase);
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));
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()]);
775 unrolledCpt.fillWith(templateCpt, templateVarNames);
786 template < GUM_Numeric GUM_SCALAR >
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};
796 template < GUM_Numeric GUM_SCALAR >
804 auto join = [](
const std::unordered_set< std::string >& names) {
806 for (
const auto& n: names) {
807 if (!out.empty()) out +=
',';
808 for (
const char c: n) {
809 if (c ==
'\\' || c ==
',') out +=
'\\';
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_));
821 writer.
write(filepath, annotated);
824 template < GUM_Numeric GUM_SCALAR >
828 BayesNet< GUM_SCALAR > bn;
832 std::stringstream stream;
840 if (!(bn.existsProperty(
"KTBN.k") && bn.existsProperty(
"KTBN.temporal")
841 && bn.existsProperty(
"KTBN.atemporal")))
844 auto split = [](std::string_view csv, std::unordered_set< std::string >& out) {
846 bool escaped =
false;
847 for (
const char c: csv) {
851 }
else if (c ==
'\\') {
853 }
else if (c ==
',') {
854 if (!current.empty()) out.insert(current);
860 if (!current.empty()) out.insert(current);
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())
871 KTBN< GUM_SCALAR > res(k_val);
873 split(bn.property(
"KTBN.temporal"), res._temporal_);
874 split(bn.property(
"KTBN.atemporal"), res._atemporal_);
879 template < GUM_Numeric GUM_SCALAR >
882 const std::unordered_set< std::string >& atemporalNodes,
883 std::vector< std::string >* warnings) {
884 KTBN< GUM_SCALAR > res(1);
886 res._determineNodesFromBN_(atemporalNodes, warnings);
890 template < GUM_Numeric GUM_SCALAR >
892 const std::unordered_set< std::string >& atemporalNodes,
893 std::vector< std::string >* warnings) {
899 for (
const std::string& name: atemporalNodes)
900 if (!
_bn_.exists(name))
903 const auto warn = [warnings](
const std::string& message) {
904 if (warnings !=
nullptr) warnings->push_back(message);
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])))
917 if (pos == name.size())
return {std::string{name},
ATEMPORAL};
919 const std::string_view digits = name.substr(pos);
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.")
927 return {std::string{name.substr(0, pos)}, slice};
939 bool hasBracket =
false;
941 const std::string& name =
_bn_.variable(n).name();
942 if (atemporalNodes.contains(name))
continue;
950 std::vector< std::string > discovered;
955 const std::string& name =
_bn_.variable(n).name();
960 if (atemporalNodes.contains(name)) {
965 const auto [base, slice] = hasBracket ?
_decodeName_(name) : decodeTrailingSlice(name);
970 if (!slicesPerProcess.
exists(base)) {
972 discovered.push_back(base);
975 if (slicesPerProcess[base].
exists(slice))
977 "Two variables map to process '" << base <<
"' at slice " << slice <<
".")
979 slicesPerProcess[base].
insert(slice, n);
981 if (slice > maxSlice) maxSlice = slice;
985 _k_ = (maxSlice < 0) ?
Size(1) :
Size(maxSlice + 1);
992 const char*
const conventionNoun = hasBracket ?
"bracket" :
"digit-suffixed";
993 for (
const auto& base: discovered) {
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().")
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);
1009 if (missing.empty()) {
1019 std::unique_ptr< DiscreteVariable > probe(ref.
clone());
1020 for (
Size t = 1; t <
_k_; ++t) {
1022 probe->setName(other.
name());
1023 if (!(*probe == other))
1025 "The temporal process '"
1026 << base <<
"' has mismatched slice variables: '" << ref.
name() <<
"' is "
1028 <<
". Every slice of a process must have the same type and domain.")
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)));
1044 std::string reclassified;
1045 for (
auto it = sliceMap.
cbegin(); it != sliceMap.
cend(); ++it) {
1046 const std::string& nodeName =
_bn_.variable(it.val()).name();
1048 if (!reclassified.empty()) reclassified +=
", ";
1049 reclassified +=
"'" + nodeName +
"'";
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.");
1066 for (
const auto& arc:
_bn_.arcs()) {
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() <<
".")
1084 template < GUM_Numeric GUM_SCALAR >
1086 const auto join = [](
const std::vector< std::string >& v) {
1088 for (
const auto& n: v) {
1089 if (!s.empty()) s +=
", ";
1099 for (
const auto& arc:
_bn_.arcs())
1100 arcs += std::format(
" {} -> {}\n",
1101 _bn_.variable(arc.tail()).name(),
1102 _bn_.variable(arc.head()).name());
1104 return std::format(
"k-TBN (k={}, {} nodes, {} arcs)\n"
1105 " temporal processes ({}): {}\n"
1106 " atemporal variables ({}): {}\n"
1107 "\n arcs ({}):\n{}",
1112 join(temporalNames),
1114 join(atemporalNames),
1119 template < GUM_Numeric GUM_SCALAR >
1124 template < GUM_Numeric GUM_SCALAR >
1129 template < GUM_Numeric GUM_SCALAR >
1131 bool highlightReplicated,
1142 template < GUM_Numeric GUM_SCALAR >
1144 bool highlightReplicated,
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();
1155 timeslices[slice].emplace_back(name, base, n);
1160 {
"size", options.
size().empty() ? style.size : options.
size()},
1162 {
"splines",
"ortho"}});
1164 {
"fillcolor",
"white"},
1165 {
"fontcolor",
"black"},
1166 {
"style",
"filled"}});
1168 for (
auto& [slice,
nodes]: timeslices) {
1172 "cluster_atemporal",
1173 {{
"label",
"atemporal"}, {
"style",
"filled"}, {
"bgcolor", style.atemporalBgColor}});
1175 const bool replicated = highlightReplicated &&
Size(slice) >=
_k_;
1177 "cluster_" + std::to_string(slice),
1178 {{
"label",
"Time slice " + std::to_string(slice)},
1179 {
"style",
"filled"},
1180 {
"bgcolor", replicated ? style.replicatedSliceBgColor : style.timeSliceBgColor}});
1182 for (
const auto& [full, label, node]:
nodes)
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(),
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);
1199 for (
const auto& [slice,
nodes]: timeslices) {
1208 return writer.
str();
1211 template < GUM_Numeric GUM_SCALAR >
1214 out.reserve(name.size());
1215 for (
const char c: name) {
1216 if (c ==
'"') out +=
'\\';
1222 template < GUM_Numeric GUM_SCALAR >
1224 return _bn_.toDot();
1227 template < GUM_Numeric GUM_SCALAR >
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;
1240 edges.emplace(tailBase, headBase, lag);
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";
1248 for (
const auto& base: baseNames)
1252 for (
const auto& [tailBase, headBase, lag]: edges) {
1254 if (lag !=
ATEMPORAL)
dot <<
" [label=\"" << lag <<
"\"]";
1262 template < GUM_Numeric GUM_SCALAR >
1263 std::ostream&
operator<<(std::ostream& output,
const KTBN< GUM_SCALAR >& kdbn) {
1264 output << kdbn.toString();
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.
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).
void clear()
Removes all variables and arcs, keeping the order .
void addTemporal(const DiscreteVariable &var)
Convenience shortcut for add(var, true).
const std::unordered_set< std::string > & temporalVarNames() const
void addAtemporal(const DiscreteVariable &var)
Convenience shortcut for add(var, false).
BayesNet< GUM_SCALAR > toBN() const
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...
void addArc(std::string_view tailBase, int tailSlice, std::string_view headBase, int headSlice)
Adds an arc between two (process, slice) endpoints.
std::vector< std::pair< std::pair< std::string, int >, std::pair< std::string, int > > > arcs() const
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...
std::vector< std::pair< std::string, int > > nodes() const
BayesNet< GUM_SCALAR > _bn_
The underlying Bayesian network used as a storage engine for the template.
static KTBN< GUM_SCALAR > load(std::string_view filename)
Loads a k-DBN from a GUM file produced by save().
void erase(std::string_view base)
Removes a variable and all its incident arcs.
const DiscreteVariable & variable(std::string_view base, int slice) const
Returns the gum::DiscreteVariable of a (process, slice) couple.
std::string summaryGraph() const
Returns the Graphviz DOT string of the summary graph: the projection of the transition kernel alone (...
bool existsArc(std::string_view tailBase, int tailSlice, std::string_view headBase, int headSlice) const
void save(std::string_view filename) const
Saves the template in the GUM format (text .jgum or binary .bgum).
static std::string _escapeDot_(std::string_view name)
Escapes double quotes for a DOT identifier or label. Used by summaryGraph().
NodeId _validateVariable_(std::string_view base, int slice) const
Resolves and validates a (base, slice) endpoint into its NodeId.
std::unordered_set< std::string > _temporal_
Base names of the registered temporal processes.
void eraseArc(std::string_view tailBase, int tailSlice, std::string_view headBase, int headSlice)
Removes an arc between two (process, slice) endpoints.
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).
const std::unordered_set< std::string > & atemporalVarNames() const
void generateCPT(std::string_view base, int slice) const
Randomly generates the CPT of a single node.
Size nbAtemporalVars() const
std::string _encode_(std::string_view base, int slice) const
Encodes (base, slice) → engine name: base[t], or base if atemporal.
const Tensor< GUM_SCALAR > & cpt(std::string_view base, int slice) const
Returns the CPT of a (process, slice) couple.
void generateCPTs() const
Randomly generates every CPT of the template.
std::unordered_set< std::string > _atemporal_
Base names of the registered atemporal variables.
std::string baseName(const DiscreteVariable &var) const
Returns the base name (without bracket encoding) of var.
static constexpr int ATEMPORAL
Conventional time-slice value denoting an atemporal (static) variable.
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 bnToDot() const
Returns the Graphviz DOT string of the underlying storage BayesNet.
KTBN< GUM_SCALAR > & operator=(const KTBN< GUM_SCALAR > &source)
Copy assignment operator.
int timeSlice(const DiscreteVariable &var) const
The time slice of var, or ATEMPORAL if it is atemporal.
void changeVariableName(std::string_view oldBase, std::string_view newBase)
Renames a variable (temporal process or atemporal variable).
std::string toDot() const
Returns a Graphviz DOT string with one cluster per time slice.
virtual ~KTBN()
Destructor.
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...
BayesNet< GUM_SCALAR > unroll(Size nbTimeSlices) const
Unrolls the k-DBN into a standard gum::BayesNet.
KTBN(Size k=2)
Default constructor.
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).
Size _k_
The order (number of time slices in the template).
Size nbTemporalVars() const
std::vector< std::pair< std::string, int > > _determineNodeSet_(const NodeSet &ids) const
Maps a set of node ids to (base, slice) pairs (via determineNode).
bool exists(std::string_view base) const
void _validateAdd_(const std::string &base, bool temporal) const
Checks that a variable named base can be added.
std::string toString() const
void add(const DiscreteVariable &var, bool temporal=true)
Adds a variable to the k-DBN.
static std::pair< std::string, bool > _resolveGumFormat_(std::string_view filename)
Resolves a user filename to (filepath, binary): ensures a .jgum/.bgum extension (....
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...
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...
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.
void insert(const Key &k)
Inserts a new element into the set.
Size size() const noexcept
Returns the number of elements in the set.
Exception : problem with size.
const std::string & name() const
returns the name of the variable
The options given to a toDot(const DotOptions&).
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.
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)
std::size_t Size
In aGrUM, hashed values are unsigned long int.
Size Idx
Type for indexes.
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
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.
Idx index
The index, when isLabel is false.
bool isLabel
Whether the value was spelled as a label rather than an index.
KTBNModality(T modality)
From a modality index.
static DynamicBNDotStyle read()