66 template < GUM_Numeric GUM_SCALAR >
74 template < GUM_Numeric GUM_SCALAR >
77 std::string_view head,
79 const int last =
static_cast< int >(
_prior_ktbn_.k()) - 1;
94 template < GUM_Numeric GUM_SCALAR >
97 std::string_view headBase,
101 "unknown base variable '" << tailBase
102 <<
"': it is not one of this learner's variables")
105 "unknown base variable '" << headBase
106 <<
"': it is not one of this learner's variables")
110 const bool tailAtemp =
_prior_ktbn_.atemporalVarNames().contains(std::string{tailBase});
111 const bool headAtemp =
_prior_ktbn_.atemporalVarNames().contains(std::string{headBase});
113 if (tailAtemp && headAtemp) {
115 }
else if (tailAtemp) {
116 for (
int hs = 0; hs <
k; ++hs)
118 }
else if (headAtemp) {
121 for (
int ts = 0; ts <
k; ++ts)
122 for (
int hs = ts; hs <
k; ++hs)
131 template < GUM_Numeric GUM_SCALAR >
133 std::string_view csvBaseName,
136 const std::unordered_set< std::string >& atemporalVars,
137 const std::vector< std::string >& missingSymbols,
139 bool ignoreMissingSymbols) :
151 }
catch (
const gum::UnknownLabelInDatabase&) {
158 "KTBNLearner CSV constructor: an unknown label was encountered while "
159 "reading the trajectory CSVs. The variable domains are inferred from "
160 "the first CSV alone, so any variable whose modalities are not all "
161 "present in trajectory 1 will trigger this error (atemporal variables "
162 "are especially prone: each trajectory holds a single constant value "
163 "for them, so at most one label appears in trajectory 1). "
164 "Use the BN-schema constructor "
165 "KTBNLearner(dir, base, n, k, bn, atemporals) to supply the full "
166 "variable domains explicitly.")
173 template < GUM_Numeric GUM_SCALAR >
175 std::string_view csvBaseName,
178 const std::vector< std::string >& missingSymbols,
180 bool ignoreMissingSymbols) :
196 ignoreMissingSymbols) {}
198 template < GUM_Numeric GUM_SCALAR >
200 std::string_view csvBaseName,
203 const BayesNet< GUM_SCALAR >& bn,
204 const std::unordered_set< std::string >& atemporalVars,
205 const std::vector< std::string >& missingSymbols,
206 bool ignoreMissingSymbols) :
220 template < GUM_Numeric GUM_SCALAR >
229 template < GUM_Numeric GUM_SCALAR >
236 const bool suppressAtemporal
242 : BayesNet< GUM_SCALAR >{};
243 return _assemble_(transitionBN, initialBN, atemporalBN);
246 template < GUM_Numeric GUM_SCALAR >
248 bool takeIntoAccountScore) {
251 "learnParameters: structure has k="
252 << structure.k() <<
" but this learner was built with k=" <<
_prior_ktbn_.k())
266 for (std::size_t
id = 0;
id < nbTransNodes; ++id)
270 for (std::size_t
id = 0;
id < nbInitNodes; ++id)
275 for (std::size_t
id = 0;
id < nbAtemNodes; ++id)
279 for (
const auto& [tail, head]: structure.arcs()) {
280 const auto& [tailBase, tailSlice] = tail;
281 const auto& [headBase, headSlice] = head;
282 const std::string tailName =
_encode_(tailBase, tailSlice);
283 const std::string headName =
_encode_(headBase, headSlice);
285 if (headSlice ==
k - 1) {
298 BayesNet< GUM_SCALAR > transitionBN
300 BayesNet< GUM_SCALAR > initialBN
302 BayesNet< GUM_SCALAR > atemporalBN
305 : BayesNet< GUM_SCALAR >{};
307 return _assemble_(transitionBN, initialBN, atemporalBN);
315 template < GUM_Numeric GUM_SCALAR >
321 template < GUM_Numeric GUM_SCALAR >
327 template < GUM_Numeric GUM_SCALAR >
333 template < GUM_Numeric GUM_SCALAR >
339 template < GUM_Numeric GUM_SCALAR >
341 _forEachLearner_([](BNLearner< GUM_SCALAR >& l) { l.useScoreLog2Likelihood(); });
345 template < GUM_Numeric GUM_SCALAR >
351 template < GUM_Numeric GUM_SCALAR >
356 template < GUM_Numeric GUM_SCALAR >
368 template < GUM_Numeric GUM_SCALAR >
370 _forEachLearner_([](BNLearner< GUM_SCALAR >& l) { l.useGreedyHillClimbing(); });
374 template < GUM_Numeric GUM_SCALAR >
376 _forEachLearner_([](BNLearner< GUM_SCALAR >& l) { l.useExtendedGreedyHillClimbing(); });
380 template < GUM_Numeric GUM_SCALAR >
386 template < GUM_Numeric GUM_SCALAR >
392 template < GUM_Numeric GUM_SCALAR >
396 [&](BNLearner< GUM_SCALAR >& l) { l.useLocalSearchWithTabuList(tabu_size, nb_decrease); });
400 template < GUM_Numeric GUM_SCALAR >
406 template < GUM_Numeric GUM_SCALAR >
408 _forEachLearner_([](BNLearner< GUM_SCALAR >& l) { l.useGreedyThickThinning(); });
412 template < GUM_Numeric GUM_SCALAR >
418 template < GUM_Numeric GUM_SCALAR >
428 template < GUM_Numeric GUM_SCALAR >
434 template < GUM_Numeric GUM_SCALAR >
440 template < GUM_Numeric GUM_SCALAR >
446 template < GUM_Numeric GUM_SCALAR >
447 std::vector< std::pair< std::string, std::string > >
454 std::vector< std::pair< std::string, std::string > > result;
455 std::unordered_set< std::string > seen;
457 auto collect = [&](
const std::unique_ptr< BNLearner< GUM_SCALAR > >& learner) {
458 if (!learner)
return;
459 for (
const auto& arc: learner->latentVariables()) {
460 std::string tail = learner->nameFromId(arc.tail());
461 std::string head = learner->nameFromId(arc.head());
462 if (seen.insert(tail +
'\t' + head).second)
463 result.emplace_back(std::move(tail), std::move(head));
476 template < GUM_Numeric GUM_SCALAR >
481 template < GUM_Numeric GUM_SCALAR >
483 _forEachLearner_([&](BNLearner< GUM_SCALAR >& l) { l.useSmoothingPrior(weight); });
491 template < GUM_Numeric GUM_SCALAR >
493 std::string_view headNode) {
495 l.addForbiddenArc(tailNode, headNode);
500 template < GUM_Numeric GUM_SCALAR >
503 std::string_view headBase,
509 template < GUM_Numeric GUM_SCALAR >
512 std::string_view headNode) {
517 l.eraseForbiddenArc(tailNode, headNode);
522 template < GUM_Numeric GUM_SCALAR >
525 std::string_view headBase,
530 template < GUM_Numeric GUM_SCALAR >
532 std::string_view headNode) {
541 l.addMandatoryArc(tailNode, headNode);
546 template < GUM_Numeric GUM_SCALAR >
549 std::string_view headBase,
555 template < GUM_Numeric GUM_SCALAR >
558 std::string_view headNode) {
562 l.eraseMandatoryArc(tailNode, headNode);
567 template < GUM_Numeric GUM_SCALAR >
570 std::string_view headBase,
575 template < GUM_Numeric GUM_SCALAR >
578 std::string_view headBase) {
584 for (
int t = 0; t <
k; ++t)
589 template < GUM_Numeric GUM_SCALAR >
592 std::string_view headBase) {
596 for (
int t = 0; t <
k; ++t)
601 template < GUM_Numeric GUM_SCALAR >
604 std::string_view headBase) {
611 template < GUM_Numeric GUM_SCALAR >
614 std::string_view headBase) {
621 template < GUM_Numeric GUM_SCALAR >
627 template < GUM_Numeric GUM_SCALAR >
635 }
else if (!isAtemp) {
642 template < GUM_Numeric GUM_SCALAR >
648 template < GUM_Numeric GUM_SCALAR >
662 template < GUM_Numeric GUM_SCALAR >
668 template < GUM_Numeric GUM_SCALAR >
678 template < GUM_Numeric GUM_SCALAR >
684 template < GUM_Numeric GUM_SCALAR >
694 template < GUM_Numeric GUM_SCALAR >
697 std::string_view headBase,
704 template < GUM_Numeric GUM_SCALAR >
707 std::string_view headBase,
712 template < GUM_Numeric GUM_SCALAR >
714 std::string_view head) {
727 if (tailSlice < last && headSlice < last)
_initialLearner_->addPossibleEdge(tail, head);
738 template < GUM_Numeric GUM_SCALAR >
740 std::string_view head) {
746 if (tailSlice < last && headSlice < last)
_initialLearner_->erasePossibleEdge(tail, head);
757 template < GUM_Numeric GUM_SCALAR >
759 _forEachLearner_([&](BNLearner< GUM_SCALAR >& l) { l.allowArcAdditions(allow); });
763 template < GUM_Numeric GUM_SCALAR >
765 _forEachLearner_([&](BNLearner< GUM_SCALAR >& l) { l.allowArcDeletions(allow); });
769 template < GUM_Numeric GUM_SCALAR >
771 _forEachLearner_([&](BNLearner< GUM_SCALAR >& l) { l.allowArcReversals(allow); });
775 template < GUM_Numeric GUM_SCALAR >
777 _forEachLearner_([&](BNLearner< GUM_SCALAR >& l) { l.setMaxIndegree(max_indegree); });
785 template < GUM_Numeric GUM_SCALAR >
790 template < GUM_Numeric GUM_SCALAR >
795 template < GUM_Numeric GUM_SCALAR >
803 template < GUM_Numeric GUM_SCALAR >
808 template < GUM_Numeric GUM_SCALAR >
813 template < GUM_Numeric GUM_SCALAR >
818 s <<
"k : " <<
k() <<
'\n';
820 <<
" temporal, " <<
_prior_ktbn_.nbAtemporalVars() <<
" atemporal)" <<
'\n';
824 s <<
"=== Transition learner (arcs into slice " << (
k() - 1) <<
") ===" <<
'\n';
827 s <<
"=== Initial learner (slices 0.." << (
k() - 2) <<
") ===" <<
'\n';
831 s <<
"=== Atemporal learner (atemporal->atemporal arcs) ===" <<
'\n';
837 template < GUM_Numeric GUM_SCALAR >
838 std::vector< std::tuple< std::string, std::string, std::string > >
848 for (
auto& [key, val, comment]: result) {
849 if (key !=
"Variables")
continue;
851 std::string collapsed;
853 auto emit = [&](
const std::string& base,
int slice) {
855 if (!first) collapsed +=
", ";
856 collapsed += base +
"[" + std::to_string(var.domainSize()) +
"]";
861 for (
const auto& base:
_prior_ktbn_.atemporalVarNames())
869 template < GUM_Numeric GUM_SCALAR >
891 template < GUM_Numeric GUM_SCALAR >
898 template < GUM_Numeric GUM_SCALAR >
903 template < GUM_Numeric GUM_SCALAR >
908 template < GUM_Numeric GUM_SCALAR >
914 template < GUM_Numeric GUM_SCALAR >
922 std::vector< std::string > result;
924 for (
Size i = 0; i < n; ++i)
929 template < GUM_Numeric GUM_SCALAR >
934 return std::vector< Size >(all.begin(), all.begin() +
nbCols());
937 template < GUM_Numeric GUM_SCALAR >
943 const std::string b{base};
954 template < GUM_Numeric GUM_SCALAR >
956 std::string_view dirPath,
957 std::string_view csvBaseName,
960 const std::vector< std::string >& missingSymbols) {
968 template < GUM_Numeric GUM_SCALAR >
970 std::string_view dirPath,
971 std::string_view csvBaseName,
973 const std::unordered_set< std::string >& atemporalVars,
974 const std::vector< std::string >& missingSymbols,
978 namespace fs = std::filesystem;
979 const std::string firstCSV
980 = (fs::path{dirPath} / (std::string{csvBaseName} +
"1.csv")).
string();
988 const BNLearner< GUM_SCALAR > tmpLearner(firstCSV, missingSymbols, induceTypes);
992 const DBTranslatorSet& translators = tmpLearner.database().translatorSet();
993 const std::vector< std::string >&
names = tmpLearner.names();
995 KTBN< GUM_SCALAR > prior(
k);
996 for (std::size_t i = 0; i <
names.size(); ++i) {
998 !atemporalVars.contains(
names[i]));
1002 for (
const std::string& aname: atemporalVars)
1003 if (!prior.exists(aname))
1005 "atemporal variable '" << aname <<
"' not found in the CSV header")
1009 template < GUM_Numeric GUM_SCALAR >
1012 const BayesNet< GUM_SCALAR >& bn,
1013 const std::unordered_set< std::string >& atemporalVars) {
1016 KTBN< GUM_SCALAR > prior(
k);
1019 for (
const NodeId node: bn.nodes()) {
1021 prior.add(var, !atemporalVars.contains(var.
name()));
1023 for (
const std::string& aname: atemporalVars)
1024 if (!prior.exists(aname))
1029 template < GUM_Numeric GUM_SCALAR >
1031 std::string_view csvBaseName,
1033 const std::vector< std::string >& missingSymbols) {
1059 const std::unordered_set< std::string > missingSet(missingSymbols.begin(),
1060 missingSymbols.end());
1061 const auto insertIfComplete = [&](
DatabaseTable& table,
const std::vector< std::string >& r) {
1063 for (
const auto& cell: r)
1064 if (missingSet.contains(cell)) {
1072 const std::filesystem::path dir{dirPath};
1073 const std::string stem{csvBaseName};
1075 const std::size_t transRowSize = nbAtempVars + nbTempVars *
k;
1076 const std::size_t initRowSize = nbAtempVars + nbTempVars * (
k - 1);
1077 const std::size_t atempRowSize = nbAtempVars;
1079 std::vector< std::string > header;
1080 std::unordered_set< Size > atemVarsCols;
1083 std::vector< std::vector< std::string > > buffer;
1084 std::vector< std::string > row;
1085 row.reserve(transRowSize);
1090 const std::filesystem::path file = dir / (stem + std::to_string(i + 1) +
".csv");
1091 std::ifstream is(file, std::ifstream::in);
1092 if (!is.is_open())
GUM_ERROR(gum::IOError,
"Cannot open " << file.string());
1101 const auto& rawHeader = parser.
current();
1102 header.assign(rawHeader.begin(), rawHeader.end());
1103 for (std::size_t c = 0; c < header.size(); ++c)
1104 if (
_prior_ktbn_.atemporalVarNames().contains(header[c])) atemVarsCols.insert(c);
1110 const std::unordered_set< std::string > headerSet(header.begin(), header.end());
1111 auto requirePresent = [&](
const std::string& base) {
1112 if (!headerSet.contains(base))
1114 "schema variable '" << base <<
"' is absent from '" << file.string() <<
"'")
1116 for (
const auto& base:
_prior_ktbn_.temporalVarNames())
1117 requirePresent(base);
1118 for (
const auto& base:
_prior_ktbn_.atemporalVarNames())
1119 requirePresent(base);
1124 for (
const std::string& col: header)
1127 "CSV column '" << col <<
"' in '" << file.string()
1128 <<
"' is not declared as a variable of this KTBNLearner")
1134 std::vector< std::string > varNamesTran;
1135 std::vector< std::string > varNamesInit;
1136 std::vector< std::string > varNamesAtemp;
1139 = [&](
DatabaseTable& table,
const std::string& base,
int slice, std::size_t col) {
1146 varNamesTran.reserve(transRowSize);
1147 varNamesInit.reserve(initRowSize);
1148 varNamesAtemp.reserve(atempRowSize);
1150 std::size_t tcol = 0, icol = 0, acol = 0;
1151 for (std::size_t c = 0; c < header.size(); ++c) {
1153 insertTrans(transitionTable, header[c], slice, tcol++);
1154 varNamesTran.push_back(
_encode_(header[c], slice));
1155 insertTrans(initTable, header[c], slice, icol++);
1156 varNamesInit.push_back(
_encode_(header[c], slice));
1157 if (atemVarsCols.contains(c)) {
1159 varNamesAtemp.push_back(header[c]);
1162 for (
Size slice = 1; slice <
k - 1; ++slice)
1163 for (std::size_t c = 0; c < header.size(); ++c)
1164 if (!atemVarsCols.contains(c)) {
1165 insertTrans(initTable, header[c], (
int)slice, icol++);
1166 varNamesInit.push_back(
_encode_(header[c], (
int)slice));
1168 for (
Size slice = 1; slice <
k; ++slice)
1169 for (std::size_t c = 0; c < header.size(); ++c)
1170 if (!atemVarsCols.contains(c)) {
1171 insertTrans(transitionTable, header[c], (
int)slice, tcol++);
1172 varNamesTran.push_back(
_encode_(header[c], (
int)slice));
1181 const auto& raw = parser.
current();
1182 bool same = (raw.size() == header.size());
1183 for (std::size_t c = 0; same && c < header.size(); ++c)
1184 same = (raw[c] == header[c]);
1190 while (parser.
next()) {
1191 const auto& tokens = parser.
current();
1192 if (tokens.size() != header.size())
1194 "Trajectory " << (i + 1) <<
", row " << parser.
nbLine() <<
": expected "
1195 << header.size() <<
" columns, got " << tokens.size());
1196 buffer.push_back({tokens.begin(), tokens.end()});
1199 if (buffer.size() <
k)
1201 "Trajectory " << (i + 1) <<
" has " << buffer.size()
1202 <<
" time steps but at least k=" <<
k <<
" are required");
1211 std::unordered_map< Size, std::string > atempValue;
1212 for (
const Size col: atemVarsCols)
1213 for (
const auto& r: buffer)
1214 if (!missingSet.contains(r[col])) {
1215 atempValue[col] = r[col];
1223 const auto cellAt = [&](std::size_t tt,
Size col) ->
const std::string& {
1224 if (!atemVarsCols.contains(col))
return buffer[tt][col];
1225 const auto it = atempValue.find(col);
1226 return (it == atempValue.end()) ? buffer[0][col] : it->second;
1230 for (std::size_t t = 0; t +
k <= buffer.size(); ++t) {
1234 for (
Size col = 0; col < buffer[0].size(); ++col) {
1235 row.push_back(cellAt(t, col));
1237 for (
Size slice = 1; slice <
k; ++slice) {
1238 for (
Size col = 0; col < buffer[0].size(); ++col) {
1239 if (!atemVarsCols.contains(col)) { row.push_back(buffer[t + slice][col]); }
1242 insertIfComplete(transitionTable, row);
1247 for (
Size col = 0; col < buffer[0].size(); ++col) {
1248 row.push_back(cellAt(0, col));
1250 for (
Size slice = 1; slice <
k - 1; ++slice) {
1251 for (
Size col = 0; col < buffer[0].size(); ++col) {
1252 if (!atemVarsCols.contains(col)) { row.push_back(buffer[slice][col]); }
1255 insertIfComplete(initTable, row);
1261 if (nbAtempVars > 1) {
1263 for (
Size col = 0; col < buffer[0].size(); ++col)
1264 if (atemVarsCols.contains(col)) row.push_back(cellAt(0, col));
1265 insertIfComplete(atemporalTable, row);
1275 "every row was dropped as incomplete ("
1277 <<
" in total): no fully observed transition window (or initial block) is left "
1278 "to learn from. The trajectories are too sparsely observed for k="
1289 if (nbAtempVars > 1) {
1306 const int ki = (int)
k;
1307 const auto& temporalVars =
_prior_ktbn_.temporalVarNames();
1308 const auto& atemporalVars =
_prior_ktbn_.atemporalVarNames();
1310 for (
const auto& base: temporalVars)
1311 for (
int slice = 0; slice < ki - 1; ++slice)
1314 for (
const auto& atemBase: atemporalVars) {
1324 for (
const auto& tailBase: temporalVars)
1325 for (
const auto& headBase: temporalVars)
1326 for (
int tailSlice = 1; tailSlice < ki - 1; ++tailSlice)
1327 for (
int headSlice = 0; headSlice < tailSlice; ++headSlice)
1333 template < GUM_Numeric GUM_SCALAR >
1338 template < GUM_Numeric GUM_SCALAR >
1340 const std::string b{base};
1345 template < GUM_Numeric GUM_SCALAR >
1348 const BayesNet< GUM_SCALAR >& initialBN,
1349 const BayesNet< GUM_SCALAR >& atemporalBN)
const {
1356 BayesNet< GUM_SCALAR > bn(initialBN);
1359 for (
const auto& base:
_prior_ktbn_.temporalVarNames()) {
1360 const std::string name =
_encode_(base,
k - 1);
1361 const NodeId transId = transitionBN.idFromName(name);
1362 bn.add(transitionBN.variable(transId));
1366 for (
const auto& base:
_prior_ktbn_.temporalVarNames()) {
1367 const std::string headName =
_encode_(base,
k - 1);
1368 const NodeId transHead = transitionBN.idFromName(headName);
1369 for (
const NodeId transParent: transitionBN.parents(transHead)) {
1370 const std::string& parentName = transitionBN.variable(transParent).name();
1371 bn.addArc(parentName, headName);
1380 if (atemporalBN.size() != 0) {
1381 for (
const auto& atemBase:
_prior_ktbn_.atemporalVarNames()) {
1382 const NodeId atemTail = atemporalBN.idFromName(atemBase);
1383 for (
const NodeId atemChild: atemporalBN.children(atemTail)) {
1384 const std::string& childName = atemporalBN.variable(atemChild).name();
1385 bn.addArc(atemBase, childName);
1391 for (
const auto& base:
_prior_ktbn_.temporalVarNames()) {
1392 const std::string name =
_encode_(base,
k - 1);
1393 const NodeId bnId = bn.idFromName(name);
1394 const NodeId transId = transitionBN.idFromName(name);
1395 bn.cpt(bnId).fillWith(transitionBN.cpt(transId));
1400 if (atemporalBN.size() != 0) {
1401 for (
const auto& atemBase:
_prior_ktbn_.atemporalVarNames()) {
1402 const NodeId bnId = bn.idFromName(atemBase);
1403 const NodeId atemId = atemporalBN.idFromName(atemBase);
1404 bn.cpt(bnId).fillWith(atemporalBN.cpt(atemId));
Class for fast parsing of CSV file (never more than one line in application memory).
A structure/parameter learner for k-order dynamic Bayesian networks.
void addArc(NodeId tail, NodeId head) final
insert a new arc into the directed graph
Base class for discrete random variable.
Exception: at least one argument passed to a function is not what was expected.
static constexpr int ATEMPORAL
Conventional time-slice value denoting an atemporal (static) variable.
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...
Error: A name of variable is not found in the database.
virtual void addNodeWithId(const NodeId id)
try to insert a node with the given id
Exception : operation not allowed.
Error: An unknown label is found in the database.
const std::string & name() const
returns the name of the variable
Class for fast parsing of CSV file (never more than one line in application memory).
bool next()
gets the next line of the csv stream and parses it
std::size_t nbLine() const
returns the current line number within the stream
const std::vector< std::string > & current() const
returns the current parsed line
the class for packing together the translators used to preprocess the datasets
DBTranslator & translatorSafe(const std::size_t k)
returns the kth translator
virtual const Variable * variable() const =0
returns the variable stored into the translator
The class representing a tabular database as used by learning tasks.
void setVariableNames(const std::vector< std::string > &names, const bool from_external_object=true) override
sets the names of the variables
std::size_t insertTranslator(const DBTranslator &translator, const std::size_t input_column, const bool unique_column=true)
insert a new translator into the database table
void reorder(const std::size_t k, const bool k_is_input_col=false)
performs a reordering of the kth translator or of the first translator parsing the kth column of the ...
void insertRow(const std::vector< std::string > &new_row) override
insert a new row at the end of the database
std::size_t nbRows() const noexcept
returns the number of records (rows) in the database
void _checkBaseIsTemporal_(std::string_view base, std::string_view context) const
Throw InvalidArgument unless base is a known temporal base. context completes "cannot appear in <cont...
void _checkArcTemporallyFeasible_(std::string_view tail, std::string_view head, std::string_view action) const
Reject an arc the k-TBN definition can never contain, so eraseForbiddenArc and addMandatoryArc both f...
static std::unordered_set< std::string > _scanConstantColumns_(std::string_view dirPath, std::string_view csvBaseName, Size nbSamples, const std::vector< std::string > &missingSymbols)
Scans every trajectory and returns the base names classified atemporal: those whose value never chang...
static void _checkMinimalOrder_(Size order, std::string_view label)
Throw InvalidArgument unless order is at least 2, label naming the offending parameter ("k" for the f...
static double defaultPriorWeight_()
static Size defaultTabuListSize_()
std::string _encode_(std::string_view base, int slice) const
(base, slice) -> engine name ("A[1]" / atemporal engine name). Pure function, shared by every learner...
std::pair< std::string, int > _determineNode_(const std::string &name) const
engine name -> (base, slice); atemporal names map to KTBN::ATEMPORAL. Shared by every learner; only t...
static Size defaultTabuNbDecrease_()
Learns a k-TBN (structure and/or parameters) from trajectory CSVs.
static KTBN< GUM_SCALAR > _buildPriorFromCSV_(std::string_view dirPath, std::string_view csvBaseName, Size k, const std::unordered_set< std::string > &atemporalVars, const std::vector< std::string > &missingSymbols, bool induceTypes)
called in the member-initialiser list of the k-CSV constructor: opens the first trajectory CSV,...
std::vector< std::string > names() const
Base names (no slice suffix), one entry per base variable (temporal or atemporal),...
void copyState(const KTBNLearner< GUM_SCALAR > &learner)
Copy all score/algorithm/prior/constraint settings from another KTBNLearner (does not copy the databa...
KTBNLearner< GUM_SCALAR > & useNMLCorrection() override
Engine-name pairs (tail, head) of arcs flagged as hiding a latent variable by MIIC (merged from all i...
KTBNLearner< GUM_SCALAR > & useGreedyThickThinning() override
the default parameters (keys tabuListSize, tabuNbDecrease of the section learning)
const std::unordered_set< std::string > & _atemporalVarNames_() const override
atemporal base names for IKTBNLearner's shared encode/_determineNode_; read straight from the prior k...
std::unique_ptr< BNLearner< GUM_SCALAR > > _initialLearner_
learns the initial slices 0..k-2
KTBNLearner< GUM_SCALAR > & eraseForbiddenArcAllSlices(std::string_view tailBase, std::string_view headBase) override
Undo a previous addForbiddenArcAllSlices.
void _build_(std::string_view dirPath, std::string_view csvBaseName, Size nbSamples, const std::vector< std::string > &missingSymbols)
reads every trajectory, builds the three DatabaseTables (sliding window, initial-slice flattening,...
KTBNLearner< GUM_SCALAR > & erasePossibleEdge(std::string_view tailBase, int tailSlice, std::string_view headBase, int headSlice) override
Undo a previous addPossibleEdge.
KTBN< GUM_SCALAR > learnKTBN() override
Full learning (structure + CPTs). Mirrors BNLearner::learnBN().
bool _ignoreMissingSymbols_
prior k-TBN: the single source of truth for k, variable domains, temporal/atemporal classification an...
std::vector< std::pair< std::string, std::string > > latentVariables() const
Engine-name pairs (tail, head) of arcs flagged as hiding a latent variable by MIIC (merged from all i...
KTBNLearner< GUM_SCALAR > & addForbiddenArc(std::string_view tailNode, std::string_view headNode) override
Forbid tailNode from ever parenting headNode (engine names, e.g. "X[1]", "C").
Size nbDroppedRows() const
Number of rows dropped from the internal databases because they carried a missing symbol.
KTBNLearner< GUM_SCALAR > & usePC() override
the default parameters (keys tabuListSize, tabuNbDecrease of the section learning)
KTBNLearner< GUM_SCALAR > & useScoreAIC() override
Returns a warning string if the current score and prior are incompatible, empty string otherwise.
KTBNLearner< GUM_SCALAR > & useGreedyHillClimbing() override
the default parameters (keys tabuListSize, tabuNbDecrease of the section learning)
static KTBN< GUM_SCALAR > _buildPriorFromBN_(Size k, const BayesNet< GUM_SCALAR > &bn, const std::unordered_set< std::string > &atemporalVars)
called in the member-initialiser list of the BN constructor: builds and returns a KTBN whose variable...
Size nbSamples() const
Number of trajectory CSV files loaded (the constructor's nbSamples).
KTBNLearner< GUM_SCALAR > & useScoreLog2Likelihood() override
Returns a warning string if the current score and prior are incompatible, empty string otherwise.
std::vector< Size > nbRows() const
Number of time steps in each trajectory CSV (one entry per sample, in load order)....
bool isConstraintBased() const
True if the current structure-learning algorithm is constraint-based (e.g. MIIC).
void _forOwningLearner_(std::string_view tail, std::string_view head, F &&f)
Apply f to the ONE internal learner that can learn the arc tail -> head, chosen by its head: a slice-...
KTBN< GUM_SCALAR > _assemble_(const BayesNet< GUM_SCALAR > &transitionBN, const BayesNet< GUM_SCALAR > &initialBN, const BayesNet< GUM_SCALAR > &atemporalBN) const
glues the three parameter-learned BNs into a single k-TBN
Size nbCols() const
Number of columns in each CSV, i.e. of base variables (temporal + atemporal).
void _forEachLearner_(F &&f)
Apply f to each present internal learner (the atemporal one only when it exists). Factors out the fan...
Size _nbTemporalPossibleEdges_
counts of currently-active possible edges, split by kind: edges with at least one temporal endpoint,...
KTBNLearner< GUM_SCALAR > & addForbiddenArcAllSlices(std::string_view tailBase, std::string_view headBase) override
Forbid tailBase -> headBase at every causally-possible slice pair (every lag, not just matching slice...
std::unique_ptr< BNLearner< GUM_SCALAR > > _transitionLearner_
learns the transition kernel (arcs arriving at slice k-1)
KTBNLearner< GUM_SCALAR > & useScoreBD() override
Returns a warning string if the current score and prior are incompatible, empty string otherwise.
KTBNLearner< GUM_SCALAR > & allowArcReversals(bool allow=true) override
Allow or forbid arc reversals during structure search.
KTBNLearner< GUM_SCALAR > & addNoChildrenNode(std::string_view base, int slice) override
Declare a single (base, slice) node as a leaf (no children).
std::vector< std::size_t > domainSizes() const
Domain sizes of the base variables, in the same column order as names().
KTBN< GUM_SCALAR > learnParameters(const KTBN< GUM_SCALAR > &structure, bool takeIntoAccountScore=true)
CPTs only, using the arc structure of structure. structure must have the same base variables (names a...
Size _nbDroppedRows_
number of time steps (rows) in each trajectory CSV, in load order. rows build() dropped because they ...
KTBN< GUM_SCALAR > _prior_ktbn_
KTBNLearner< GUM_SCALAR > & allowArcDeletions(bool allow=true) override
Allow or forbid arc deletions during structure search.
KTBNLearner< GUM_SCALAR > & useExtendedGreedyHillClimbing() override
the default parameters (keys tabuListSize, tabuNbDecrease of the section learning)
std::string checkScorePriorCompatibility() const
Returns a warning string if the current score and prior are incompatible, empty string otherwise.
KTBNLearner< GUM_SCALAR > & useNoCorrection() override
Engine-name pairs (tail, head) of arcs flagged as hiding a latent variable by MIIC (merged from all i...
bool isScoreBased() const
True if the current structure-learning algorithm is score-based (e.g. BIC, AIC).
KTBNLearner< GUM_SCALAR > & allowArcAdditions(bool allow=true) override
Allow or forbid arc additions during structure search.
Size domainSize(std::string_view base) const
Domain size of the base variable base (e.g. "X", "C"). Engine names (e.g. "X[1]") are also accepted.
KTBNLearner< GUM_SCALAR > & eraseForbiddenArc(std::string_view tailNode, std::string_view headNode) override
Undo a previous addForbiddenArc (engine names, e.g. "X[1]", "C").
KTBNLearner< GUM_SCALAR > & useSmoothingPrior(double weight) override
the default weight (key priorWeight of the section learning)
KTBNLearner< GUM_SCALAR > & useScoreBIC() override
Returns a warning string if the current score and prior are incompatible, empty string otherwise.
bool isIgnoringMissingSymbols() const
Whether build() drops the rows carrying a missing symbol.
KTBNLearner< GUM_SCALAR > & useMIIC() override
the default parameters (keys tabuListSize, tabuNbDecrease of the section learning)
void useScorefNML() override
Returns a warning string if the current score and prior are incompatible, empty string otherwise.
KTBNLearner< GUM_SCALAR > & useScoreMDL() override
Returns a warning string if the current score and prior are incompatible, empty string otherwise.
KTBNLearner< GUM_SCALAR > & useSmoothingPrior()
the default weight (key priorWeight of the section learning)
KTBNLearner< GUM_SCALAR > & eraseNoChildrenNode(std::string_view base, int slice) override
Undo a previous addNoChildrenNode for a single (base, slice) node.
static std::unordered_set< std::string > _inferAtemporalVars_(std::string_view dirPath, std::string_view csvBaseName, Size nbSamples, Size k, const std::vector< std::string > &missingSymbols)
checks k >= 2, then delegates the actual scan to the shared IKTBNLearner::scanConstantColumns() (also...
KTBNLearner< GUM_SCALAR > & eraseForbiddenIntraSliceArc(std::string_view tailBase, std::string_view headBase) override
Undo a previous addForbiddenIntraSliceArc.
std::string toString() const
Human-readable summary of the learner's current configuration.
std::vector< Size > _nbTimeSlices_
Captured once by build() and exposed by nbRows(). This is the raw trajectory length,...
std::vector< std::tuple< std::string, std::string, std::string > > state() const
Settings as a vector of (key, value, comment) tuples (mirrors BNLearner::state()).
KTBNLearner< GUM_SCALAR > & addMandatoryArc(std::string_view tailNode, std::string_view headNode) override
Force tailNode to be a parent of headNode (engine names, e.g. "X[1]", "C").
bool hasMissingValues() const
True if any internal database contains missing values.
KTBNLearner< GUM_SCALAR > & setMaxIndegree(Size max_indegree) override
Cap the number of parents of any single node.
KTBNLearner< GUM_SCALAR > & addForbiddenIntraSliceArc(std::string_view tailBase, std::string_view headBase) override
Forbid tailBase -> headBase at every intra-slice position (i.e. tailBase[t] -> headBase[t] for all t ...
KTBNLearner< GUM_SCALAR > & addPossibleEdge(std::string_view tailBase, int tailSlice, std::string_view headBase, int headSlice) override
Add a candidate edge for MIIC (only edges explicitly listed are explored).
bool _isKnownBase_(std::string_view base) const override
whether base is one of this learner's variables; read straight from the prior k-TBN,...
KTBNLearner< GUM_SCALAR > & useMDLCorrection() override
Engine-name pairs (tail, head) of arcs flagged as hiding a latent variable by MIIC (merged from all i...
KTBNLearner< GUM_SCALAR > & useLocalSearchWithTabuList()
the default parameters (keys tabuListSize, tabuNbDecrease of the section learning)
KTBNLearner< GUM_SCALAR > & useLocalSearchWithTabuList(Size tabu_size, Size nb_decrease) override
the default parameters (keys tabuListSize, tabuNbDecrease of the section learning)
KTBNLearner< GUM_SCALAR > & useScoreBDeu() override
Returns a warning string if the current score and prior are incompatible, empty string otherwise.
Size _nbAtemporalPossibleEdges_
KTBNLearner< GUM_SCALAR > & eraseMandatoryArc(std::string_view tailNode, std::string_view headNode) override
Undo a previous addMandatoryArc (engine names, e.g. "X[1]", "C").
KTBNLearner< GUM_SCALAR > & addNoParentNode(std::string_view base, int slice) override
Declare a single (base, slice) node as a root (no parents).
std::unique_ptr< BNLearner< GUM_SCALAR > > _atemporalLearner_
learns the atemporal variables (arcs atemporal -> atemporal)
KTBNLearner< GUM_SCALAR > & useFCI() override
the default parameters (keys tabuListSize, tabuNbDecrease of the section learning)
KTBNLearner(std::string_view dirPath, std::string_view csvBaseName, Size nbSamples, Size k, const std::unordered_set< std::string > &atemporalVars, const std::vector< std::string > &missingSymbols={"?"}, bool induceTypes=true, bool ignoreMissingSymbols=false)
Structure-learning constructor — variable roles supplied explicitly.
Size k() const
Order of the k-TBN being learned.
KTBNLearner< GUM_SCALAR > & eraseNoParentNode(std::string_view base, int slice) override
Undo a previous addNoParentNode for a single (base, slice) node.
void _forEachAllSlicesPair_(std::string_view tailBase, std::string_view headBase, F &&f) const
Apply f(tailSlice, headSlice) to every causally-possible slice pair of an all-slices constraint betwe...
Typed, documented, sectioned configuration singleton read from an .ini content.
The class representing a tabular database stored in RAM.
#define GUM_ERROR(type, msg)
std::size_t Size
In aGrUM, hashed values are unsigned long int.
Size NodeId
Type for node ids.
include the inlined functions if necessary