57#ifndef DOXYGEN_SHOULD_SKIP_THIS
66 template < GUM_Numeric GUM_SCALAR >
68 const std::vector< std::string >& missingSymbols,
69 const bool induceTypes) :
70 IBNLearner(filename, missingSymbols, induceTypes) {
71 GUM_CONSTRUCTOR(BNLearner);
74 template < GUM_Numeric GUM_SCALAR >
75 BNLearner< GUM_SCALAR >::BNLearner(
const DatabaseTable& db) : IBNLearner(db) {
76 GUM_CONSTRUCTOR(BNLearner);
79 template < GUM_Numeric GUM_SCALAR >
80 BNLearner< GUM_SCALAR >::BNLearner(std::string_view filename,
82 const std::vector< std::string >& missing_symbols) :
83 IBNLearner(filename, bn, missing_symbols) {
84 GUM_CONSTRUCTOR(BNLearner);
88 template < GUM_Numeric GUM_SCALAR >
89 BNLearner< GUM_SCALAR >::BNLearner(
const BNLearner< GUM_SCALAR >& src) : IBNLearner(src) {
90 GUM_CONSTRUCTOR(BNLearner);
94 template < GUM_Numeric GUM_SCALAR >
95 BNLearner< GUM_SCALAR >::BNLearner(BNLearner< GUM_SCALAR >&& src) : IBNLearner(src) {
96 GUM_CONSTRUCTOR(BNLearner);
100 template < GUM_Numeric GUM_SCALAR >
101 BNLearner< GUM_SCALAR >::~BNLearner() {
113 template < GUM_Numeric GUM_SCALAR >
121 template < GUM_Numeric GUM_SCALAR >
129 template < GUM_Numeric GUM_SCALAR >
132 auto notification = checkScorePriorCompatibility();
133 if (notification !=
"") { std::cout <<
"[aGrUM notification] " << notification << std::endl; }
137 std::unique_ptr< ParamEstimator > param_estimator(
138 createParamEstimator_(scoreDatabase_.parser(),
true));
140 return dag2BN_.createBN< GUM_SCALAR >(*(param_estimator.get()), learnDag_());
144 template < GUM_Numeric GUM_SCALAR >
147 if (dag.size() == 0)
return;
150 std::vector< NodeId > ids;
151 ids.reserve(dag.sizeNodes());
152 for (
const auto node: dag)
154 std::sort(ids.begin(), ids.end());
156 if (ids.back() >= scoreDatabase_.names().size()) {
157 std::string str =
"Learning parameters corresponding to the dag is impossible "
158 "because the database does not contain the following nodeID";
159 std::vector< NodeId > bad_ids;
160 for (
const auto node: ids) {
161 if (node >= scoreDatabase_.names().size()) bad_ids.push_back(node);
163 if (bad_ids.size() > 1) str +=
's';
166 for (
const auto node: bad_ids) {
167 if (deja) str +=
", ";
169 str += std::to_string(node);
171 GUM_ERROR(MissingVariableInDatabase, str)
176 template < GUM_Numeric GUM_SCALAR >
178 bool takeIntoAccountScore) {
180 if (dag.size() == 0)
return BayesNet< GUM_SCALAR >();
183 _checkDAGCompatibility_(dag);
189 if (scoreDatabase_.databaseTable().hasMissingValues()
190 || ((priorDatabase_ !=
nullptr)
191 && (priorType_ == BNLearnerPriorType::DIRICHLET_FROM_DATABASE)
192 && priorDatabase_->databaseTable().hasMissingValues())) {
194 "In general, the BNLearner is unable to cope with "
195 <<
"missing values in databases. To learn parameters in "
196 <<
"such situations, you should first use method " <<
"useEM()");
201 std::unique_ptr< ParamEstimator > param_estimator(
202 createParamEstimator_(parser, takeIntoAccountScore));
204 return dag2BN_.createBN< GUM_SCALAR >(*(param_estimator.get()), dag);
212# if defined(__GNUC__) && !defined(__clang__)
213# pragma GCC push_options
214# pragma GCC optimize("no-tree-vrp")
217 template < GUM_Numeric GUM_SCALAR >
218 std::pair< std::shared_ptr< ParamEstimator >, std::shared_ptr< ParamEstimator > >
220 bool takeIntoAccountScore) {
222 _checkDAGCompatibility_(dag);
232 const auto& database = scoreDatabase_.databaseTable();
233 const std::size_t nb_vars = database.nbVariables();
234 const std::vector< gum::learning::DBTranslatedValueType > col_types(
243 std::shared_ptr< ParamEstimator > param_estimator_bootstrap(
244 createParamEstimator_(parser_bootstrap, takeIntoAccountScore));
247 BayesNet< GUM_SCALAR > dummy_bn;
253 std::shared_ptr< ParamEstimator > param_estimator_EM(
254 createParamEstimator_(parser_EM, takeIntoAccountScore));
256 return {param_estimator_bootstrap, param_estimator_EM};
259# if defined(__GNUC__) && !defined(__clang__)
260# pragma GCC pop_options
264 template < GUM_Numeric GUM_SCALAR >
265 BayesNet< GUM_SCALAR >
267 bool takeIntoAccountScore) {
269 if (dag.size() == 0)
return BayesNet< GUM_SCALAR >();
272 auto estimators = _initializeEMParameterLearning_(dag, takeIntoAccountScore);
275 return dag2BN_.createBNwithEM< GUM_SCALAR >(*(estimators.first.get()),
276 *(estimators.second.get()),
281 template < GUM_Numeric GUM_SCALAR >
282 BayesNet< GUM_SCALAR >
284 bool takeIntoAccountScore) {
286 if (bn.internalDag().size() == 0)
return BayesNet< GUM_SCALAR >();
289 auto estimators = _initializeEMParameterLearning_(bn.internalDag(), takeIntoAccountScore);
291 return dag2BN_.createBNwithEM< GUM_SCALAR >(*(estimators.first.get()),
292 *(estimators.second.get()),
297 template < GUM_Numeric GUM_SCALAR >
299 bool takeIntoAccountScore) {
300 if (!scoreDatabase_.databaseTable().hasMissingValues() || !useEM_) {
302 return _learnParameters_(dag, takeIntoAccountScore);
305 return _learnParametersWithEM_(dag, takeIntoAccountScore);
310 template < GUM_Numeric GUM_SCALAR >
311 BayesNet< GUM_SCALAR >
313 bool takeIntoAccountScore) {
314 if (!scoreDatabase_.databaseTable().hasMissingValues() || !useEM_) {
316 const auto& db = scoreDatabase_.databaseTable();
317 for (
const auto n: bn.nodes()) {
318 dag.addNodeWithId(db.columnFromVariableName(bn.variable(n).name()));
320 for (
const auto& arc: bn.arcs()) {
321 dag.addArc(db.columnFromVariableName(bn.variable(arc.tail()).name()),
322 db.columnFromVariableName(bn.variable(arc.head()).name()));
326 return _learnParameters_(dag, takeIntoAccountScore);
328 return _learnParametersWithEM_(bn, takeIntoAccountScore);
333 template < GUM_Numeric GUM_SCALAR >
335 return learnParameters(initialDag_, take_into_account_score);
338 template < GUM_Numeric GUM_SCALAR >
341 const BayesNet< GUM_SCALAR >& src) {
342 std::ifstream in(std::string(filename), std::ifstream::in);
344 if ((in.rdstate() & std::ifstream::failbit) != 0) {
345 GUM_ERROR(gum::IOError,
"File " << filename <<
" not found")
348 CSVParser parser(in, std::string(filename));
350 auto names = parser.current();
354 for (
gum::Idx col = 0; col < names.size(); col++) {
355 if (src.exists(names[col])) {
357 modals.insert(col, gum::Sequence< std::string >());
359 for (
gum::Size i = 0; i < src.variable(graphId).domainSize(); ++i)
360 modals[col].insert(src.variable(graphId).label(i));
368 template < GUM_Numeric GUM_SCALAR >
370 const auto st = state();
373 for (
const auto& tuple: st)
374 if (std::get< 0 >(tuple).length() > maxkey) maxkey = std::get< 0 >(tuple).length();
377 for (
const auto& tuple: st) {
378 s += std::format(
"{:<{}} : {}", std::get< 0 >(tuple), maxkey, std::get< 1 >(tuple));
379 if (std::get< 2 >(tuple) !=
"") s += std::format(
" ({})", std::get< 2 >(tuple));
385 template < GUM_Numeric GUM_SCALAR >
386 std::vector< std::tuple< std::string, std::string, std::string > >
388 std::vector< std::tuple< std::string, std::string, std::string > > vals;
392 const auto& db = database();
394 vals.emplace_back(
"Filename", filename_,
"");
395 vals.emplace_back(
"Size",
396 "(" + std::to_string(nbRows()) +
"," + std::to_string(nbCols()) +
")",
399 std::string vars =
"";
400 for (
NodeId i = 0; i < db.nbVariables(); i++) {
401 if (i > 0) vars +=
", ";
402 vars += nameFromId(i) +
"[" + std::to_string(db.domainSize(i)) +
"]";
404 vals.emplace_back(
"Variables", vars,
"");
405 vals.emplace_back(
"Induced types", inducedTypes_ ?
"True" :
"False",
"");
406 vals.emplace_back(
"Missing values", hasMissingValues() ?
"True" :
"False",
"");
409 switch (selectedAlgo_) {
410 case AlgoType::GREEDY_HILL_CLIMBING :
411 vals.emplace_back(key,
"Greedy Hill Climbing",
"");
413 case AlgoType::EXTENDED_GREEDY_HILL_CLIMBING :
414 vals.emplace_back(key,
"Extended Greedy Hill Climbing",
"");
416 case AlgoType::K2 : {
417 vals.emplace_back(key,
"K2",
"");
418 const auto& k2order = algoK2_.order();
420 for (
NodeId i = 0; i < k2order.size(); i++) {
421 if (i > 0) vars +=
", ";
422 vars += nameFromId(k2order.atPos(i));
424 vals.emplace_back(
"K2 order", vars,
"");
426 case AlgoType::LOCAL_SEARCH_WITH_TABU_LIST :
427 vals.emplace_back(key,
"Local Search with Tabu List",
"");
428 vals.emplace_back(
"Tabu list size", std::to_string(tabuListSize_),
"");
429 vals.emplace_back(
"Max consecutive decreasing changes",
430 std::to_string(nbDecreasingChanges_),
433 case AlgoType::MIIC : vals.emplace_back(key,
"MIIC",
"");
break;
434 case AlgoType::PC : vals.emplace_back(key,
"PC",
"");
break;
435 case AlgoType::FCI : vals.emplace_back(key,
"FCI",
"");
break;
436 case AlgoType::GREEDY_THICK_THINNING :
437 vals.emplace_back(key,
"Greedy Thick Thinning",
"");
439 default : vals.emplace_back(key,
"(unknown)",
"?");
break;
444 if (isScoreBased()) {
445 switch (scoreType_) {
446 case ScoreType::AIC : vals.emplace_back(key,
"AIC",
"");
break;
447 case ScoreType::BIC : vals.emplace_back(key,
"BIC",
"");
break;
448 case ScoreType::BD : vals.emplace_back(key,
"BD",
"");
break;
449 case ScoreType::BDeu : vals.emplace_back(key,
"BDeu",
"");
break;
450 case ScoreType::fNML : vals.emplace_back(key,
"fNML",
"");
break;
451 case ScoreType::K2 : vals.emplace_back(key,
"K2",
"");
break;
452 case ScoreType::LOG2LIKELIHOOD : vals.emplace_back(key,
"Log2Likelihood",
"");
break;
453 case ScoreType::MDL : vals.emplace_back(key,
"MDL",
"");
break;
454 default : vals.emplace_back(key,
"(unknown)",
"?");
break;
458 if (isConstraintBased()) {
460 switch (kmodeMiic_) {
462 vals.emplace_back(key,
"MDL",
"");
465 vals.emplace_back(key,
"NML",
"");
468 vals.emplace_back(key,
"No correction",
"");
470 default : vals.emplace_back(key,
"(unknown)",
"?");
break;
475 comment = checkScorePriorCompatibility();
476 switch (priorType_) {
477 case BNLearnerPriorType::NO_prior : vals.emplace_back(key,
"-", comment);
break;
478 case BNLearnerPriorType::DIRICHLET_FROM_DATABASE :
479 vals.emplace_back(key,
"Dirichlet", comment);
480 vals.emplace_back(
"Dirichlet from database", priorDbname_,
"");
482 case BNLearnerPriorType::DIRICHLET_FROM_BAYESNET :
483 vals.emplace_back(key,
"Dirichlet", comment);
484 vals.emplace_back(
"Dirichlet from Bayesian network : ", _prior_bn_.toString(),
"");
486 case BNLearnerPriorType::BDEU : vals.emplace_back(key,
"BDEU", comment);
break;
487 case BNLearnerPriorType::SMOOTHING : vals.emplace_back(key,
"Smoothing", comment);
break;
488 default : vals.emplace_back(key,
"(unknown)",
"?");
break;
491 if (priorType_ != BNLearnerPriorType::NO_prior)
492 vals.emplace_back(
"Prior weight", std::to_string(priorWeight_),
"");
494 if (databaseWeight() !=
double(nbRows())) {
495 vals.emplace_back(
"Database weight", std::to_string(databaseWeight()),
"");
500 if (!hasMissingValues()) comment =
"But no missing values in this database";
501 vals.emplace_back(
"use EM",
"True",
"");
504 if (dag2BN_.isEnabledMinEpsilonRate()) {
505 s += std::format(
"MinRate: {}", dag2BN_.minEpsilonRate());
508 if (dag2BN_.isEnabledEpsilon()) {
509 if (!first) s +=
", ";
511 s += std::format(
"MinDiff: {}", dag2BN_.epsilon());
513 if (dag2BN_.isEnabledMaxIter()) {
514 if (!first) s +=
", ";
516 s += std::format(
"MaxIter: {}", dag2BN_.maxIter());
518 if (dag2BN_.isEnabledMaxTime()) {
519 if (!first) s +=
", ";
521 s += std::format(
"MaxTime: {}", dag2BN_.maxTime());
524 vals.emplace_back(
"EM stopping criteria", s, comment);
529 if (constraintIndegree_.maxIndegree() < std::numeric_limits< Size >::max()) {
530 vals.emplace_back(
"Constraint Max InDegree",
531 std::to_string(constraintIndegree_.maxIndegree()),
534 if (!constraintForbiddenArcs_.arcs().empty()) {
537 for (
const auto& arc: constraintForbiddenArcs_.arcs()) {
538 if (nofirst) res +=
", ";
540 res += nameFromId(arc.tail()) +
"->" + nameFromId(arc.head());
543 vals.emplace_back(
"Constraint Forbidden Arcs", res,
"");
545 if (!constraintMandatoryArcs_.arcs().empty()) {
548 for (
const auto& arc: constraintMandatoryArcs_.arcs()) {
549 if (nofirst) res +=
", ";
551 res += nameFromId(arc.tail()) +
"->" + nameFromId(arc.head());
554 vals.emplace_back(
"Constraint Mandatory Arcs", res,
"");
556 if (!constraintPossibleEdges_.edges().empty()) {
559 for (
const auto& edge: constraintPossibleEdges_.edges()) {
560 if (nofirst) res +=
", ";
562 res += nameFromId(edge.first()) +
"--" + nameFromId(edge.second());
565 vals.emplace_back(
"Constraint Possible Edges", res,
"");
567 if (!constraintSliceOrder_.sliceOrder().empty()) {
570 const auto& order = constraintSliceOrder_.sliceOrder();
571 for (
const auto& p: order) {
572 if (nofirst) res +=
", ";
574 res += nameFromId(p.first) +
":" + std::to_string(p.second);
577 vals.emplace_back(
"Constraint Slice Order", res,
"");
579 if (!constraintNoParentNodes_.nodes().empty()) {
582 for (
const auto& node: constraintNoParentNodes_.nodes()) {
583 if (nofirst) res +=
", ";
585 res += nameFromId(node);
588 vals.emplace_back(
"Constraint No Parent Nodes", res,
"");
590 if (!constraintNoChildrenNodes_.nodes().empty()) {
593 for (
const auto& node: constraintNoChildrenNodes_.nodes()) {
594 if (nofirst) res +=
", ";
596 res += nameFromId(node);
599 vals.emplace_back(
"Constraint No Children Nodes", res,
"");
601 if (initialDag_.size() != 0) {
602 vals.emplace_back(
"Initial DAG",
"True", initialDag_.toDot());
608 template < GUM_Numeric GUM_SCALAR >
610 switch (learner.selectedAlgo_) {
611 case AlgoType::EXTENDED_GREEDY_HILL_CLIMBING : useExtendedGreedyHillClimbing();
break;
612 case AlgoType::GREEDY_HILL_CLIMBING : useGreedyHillClimbing();
break;
613 case AlgoType::GREEDY_THICK_THINNING :
614 useGreedyThickThinning();
615 setGreedyThickThinningReversals(learner.greedyThickThinningReversals());
617 case AlgoType::K2 : useK2(learner.algoK2_.order());
break;
618 case AlgoType::LOCAL_SEARCH_WITH_TABU_LIST :
619 useLocalSearchWithTabuList(learner.tabuListSize_, learner.nbDecreasingChanges_);
621 case AlgoType::MIIC : useMIIC();
break;
622 case AlgoType::PC : usePC();
break;
623 case AlgoType::FCI : useFCI();
break;
626 switch (learner.scoreType_) {
627 case ScoreType::K2 : useScoreK2();
break;
628 case ScoreType::AIC : useScoreAIC();
break;
629 case ScoreType::BIC : useScoreBIC();
break;
630 case ScoreType::BD : useScoreBD();
break;
631 case ScoreType::BDeu : useScoreBDeu();
break;
632 case ScoreType::fNML : useScorefNML();
break;
633 case ScoreType::MDL : useScoreMDL();
break;
634 case ScoreType::LOG2LIKELIHOOD : useScoreLog2Likelihood();
break;
637 switch (learner.kmodeMiic_) {
643 switch (learner.priorType_) {
644 case BNLearnerPriorType::NO_prior : useNoPrior();
break;
645 case BNLearnerPriorType::DIRICHLET_FROM_DATABASE :
646 useDirichletPrior(learner.priorDbname_, learner.priorWeight_);
648 case BNLearnerPriorType::DIRICHLET_FROM_BAYESNET :
649 useDirichletPrior(learner._prior_bn_, learner.priorWeight_);
651 case BNLearnerPriorType::BDEU : useBDeuPrior(learner.priorWeight_);
break;
652 case BNLearnerPriorType::SMOOTHING : useSmoothingPrior(learner.priorWeight_);
break;
655 useEM_ = learner.useEM_;
656 dag2BN_ = learner.dag2BN_;
658 setMaxIndegree(learner.constraintIndegree_.maxIndegree());
659 for (
const auto src: learner.constraintNoParentNodes_.nodes()) {
661 const auto dst = idFromName(learner.nameFromId(src));
662 addNoParentNode(dst);
663 }
catch (
const MissingVariableInDatabase&) {
667 for (
const auto src: learner.constraintNoChildrenNodes_.nodes()) {
669 const auto dst = idFromName(learner.nameFromId(src));
670 addNoChildrenNode(dst);
671 }
catch (
const MissingVariableInDatabase&) {
675 for (
const auto& arc: learner.constraintForbiddenArcs_.arcs()) {
677 const auto src = idFromName(learner.nameFromId(arc.tail()));
678 const auto dst = idFromName(learner.nameFromId(arc.head()));
679 addForbiddenArc(src, dst);
680 }
catch (
const MissingVariableInDatabase&) {
684 for (
const auto& arc: learner.constraintMandatoryArcs_.arcs()) {
686 const auto src = idFromName(learner.nameFromId(arc.tail()));
687 const auto dst = idFromName(learner.nameFromId(arc.head()));
688 addMandatoryArc(src, dst);
689 }
catch (
const MissingVariableInDatabase&) {
693 for (
const auto& edge: learner.constraintPossibleEdges_.edges()) {
695 const auto src = idFromName(learner.nameFromId(edge.first()));
696 const auto dst = idFromName(learner.nameFromId(edge.second()));
697 addPossibleEdge(src, dst);
698 }
catch (
const MissingVariableInDatabase&) {
702 if (!learner.constraintSliceOrder_.sliceOrder().empty()) {
704 for (
const auto& p: learner.constraintSliceOrder_.sliceOrder()) {
706 slice_order.insert(idFromName(learner.nameFromId(p.first)), p.second);
707 }
catch (
const MissingVariableInDatabase&) {
711 setSliceOrder(slice_order);
713 if (!learner.constraintTotalOrder_.totalOrder().empty()) {
714 setTotalOrder(learner.constraintTotalOrder_.totalOrder());
718 template < GUM_Numeric GUM_SCALAR >
721 Prior* old_prior = prior_;
724 switch (priorType_) {
725 case BNLearnerPriorType::NO_prior :
726 prior_ =
new NoPrior(scoreDatabase_.databaseTable(), scoreDatabase_.nodeId2Columns());
729 case BNLearnerPriorType::SMOOTHING :
731 =
new SmoothingPrior(scoreDatabase_.databaseTable(), scoreDatabase_.nodeId2Columns());
734 case BNLearnerPriorType::DIRICHLET_FROM_DATABASE :
735 if (priorDatabase_ !=
nullptr) {
736 delete priorDatabase_;
737 priorDatabase_ =
nullptr;
741 =
new Database(priorDbname_, scoreDatabase_, scoreDatabase_.missingSymbols());
744 priorDatabase_->parser(),
745 priorDatabase_->nodeId2Columns());
748 case BNLearnerPriorType::DIRICHLET_FROM_BAYESNET :
753 case BNLearnerPriorType::BDEU :
754 prior_ =
new BDeuPrior(scoreDatabase_.databaseTable(), scoreDatabase_.nodeId2Columns());
757 default :
GUM_ERROR(OperationNotAllowed,
"The BNLearner does not support yet this prior")
764 if (old_prior !=
nullptr)
delete old_prior;
767 template < GUM_Numeric GUM_SCALAR >
769 output << learner.toString();
777 template < GUM_Numeric GUM_SCALAR >
783 template < GUM_Numeric GUM_SCALAR >
789 template < GUM_Numeric GUM_SCALAR >
795 template < GUM_Numeric GUM_SCALAR >
801 template < GUM_Numeric GUM_SCALAR >
803 const double noise) {
808 template < GUM_Numeric GUM_SCALAR >
810 const double noise) {
815 template < GUM_Numeric GUM_SCALAR >
817 const double noise) {
822 template < GUM_Numeric GUM_SCALAR >
828 template < GUM_Numeric GUM_SCALAR >
834 template < GUM_Numeric GUM_SCALAR >
840 template < GUM_Numeric GUM_SCALAR >
846 template < GUM_Numeric GUM_SCALAR >
852 template < GUM_Numeric GUM_SCALAR >
858 template < GUM_Numeric GUM_SCALAR >
864 template < GUM_Numeric GUM_SCALAR >
870 template < GUM_Numeric GUM_SCALAR >
876 template < GUM_Numeric GUM_SCALAR >
882 template < GUM_Numeric GUM_SCALAR >
888 template < GUM_Numeric GUM_SCALAR >
894 template < GUM_Numeric GUM_SCALAR >
900 template < GUM_Numeric GUM_SCALAR >
906 template < GUM_Numeric GUM_SCALAR >
912 template < GUM_Numeric GUM_SCALAR >
918 template < GUM_Numeric GUM_SCALAR >
924 template < GUM_Numeric GUM_SCALAR >
930 template < GUM_Numeric GUM_SCALAR >
936 template < GUM_Numeric GUM_SCALAR >
942 template < GUM_Numeric GUM_SCALAR >
948 template < GUM_Numeric GUM_SCALAR >
954 template < GUM_Numeric GUM_SCALAR >
960 template < GUM_Numeric GUM_SCALAR >
966 template < GUM_Numeric GUM_SCALAR >
972 template < GUM_Numeric GUM_SCALAR >
975 return useDirichletPrior(bn,
gum::config().typed< double >(
"learning",
"priorWeight"));
978 template < GUM_Numeric GUM_SCALAR >
984 template < GUM_Numeric GUM_SCALAR >
990 template < GUM_Numeric GUM_SCALAR >
997 template < GUM_Numeric GUM_SCALAR >
1002 priorType_ = BNLearnerPriorType::DIRICHLET_FROM_BAYESNET;
1003 _setPriorWeight_(weight);
1007 template < GUM_Numeric GUM_SCALAR >
1013 template < GUM_Numeric GUM_SCALAR >
1019 template < GUM_Numeric GUM_SCALAR >
1025 template < GUM_Numeric GUM_SCALAR >
1031 template < GUM_Numeric GUM_SCALAR >
1036 template < GUM_Numeric GUM_SCALAR >
1042 template < GUM_Numeric GUM_SCALAR >
1048 template < GUM_Numeric GUM_SCALAR >
1055 template < GUM_Numeric GUM_SCALAR >
1061 template < GUM_Numeric GUM_SCALAR >
1067 template < GUM_Numeric GUM_SCALAR >
1073 template < GUM_Numeric GUM_SCALAR >
1079 template < GUM_Numeric GUM_SCALAR >
1085 template < GUM_Numeric GUM_SCALAR >
1091 template < GUM_Numeric GUM_SCALAR >
1097 template < GUM_Numeric GUM_SCALAR >
1103 template < GUM_Numeric GUM_SCALAR >
1109 template < GUM_Numeric GUM_SCALAR >
1115 template < GUM_Numeric GUM_SCALAR >
1120 template < GUM_Numeric GUM_SCALAR >
1126 template < GUM_Numeric GUM_SCALAR >
1132 template < GUM_Numeric GUM_SCALAR >
1138 template < GUM_Numeric GUM_SCALAR >
1144 template < GUM_Numeric GUM_SCALAR >
1150 template < GUM_Numeric GUM_SCALAR >
1156 template < GUM_Numeric GUM_SCALAR >
1162 template < GUM_Numeric GUM_SCALAR >
1168 template < GUM_Numeric GUM_SCALAR >
1174 template < GUM_Numeric GUM_SCALAR >
1180 template < GUM_Numeric GUM_SCALAR >
1187 template < GUM_Numeric GUM_SCALAR >
1189 const std::vector< std::vector< std::string > >& slices) {
1194 template < GUM_Numeric GUM_SCALAR >
1201 template < GUM_Numeric GUM_SCALAR >
1208 template < GUM_Numeric GUM_SCALAR >
1214 template < GUM_Numeric GUM_SCALAR >
1220 template < GUM_Numeric GUM_SCALAR >
1226 template < GUM_Numeric GUM_SCALAR >
1228 std::string_view head) {
1233 template < GUM_Numeric GUM_SCALAR >
1239 template < GUM_Numeric GUM_SCALAR >
1245 template < GUM_Numeric GUM_SCALAR >
1247 std::string_view head) {
1252 template < GUM_Numeric GUM_SCALAR >
1258 template < GUM_Numeric GUM_SCALAR >
1264 template < GUM_Numeric GUM_SCALAR >
1266 std::string_view head) {
1271 template < GUM_Numeric GUM_SCALAR >
1277 template < GUM_Numeric GUM_SCALAR >
1283 template < GUM_Numeric GUM_SCALAR >
1285 std::string_view head) {
1290 template < GUM_Numeric GUM_SCALAR >
1296 template < GUM_Numeric GUM_SCALAR >
1302 template < GUM_Numeric GUM_SCALAR >
1304 std::string_view head) {
1309 template < GUM_Numeric GUM_SCALAR >
1315 template < GUM_Numeric GUM_SCALAR >
1321 template < GUM_Numeric GUM_SCALAR >
1323 std::string_view head) {
1328 template < GUM_Numeric GUM_SCALAR >
1334 template < GUM_Numeric GUM_SCALAR >
1340 template < GUM_Numeric GUM_SCALAR >
1347 template < GUM_Numeric GUM_SCALAR >
1353 template < GUM_Numeric GUM_SCALAR >
1359 template < GUM_Numeric GUM_SCALAR >
1365 template < GUM_Numeric GUM_SCALAR >
1371 template < GUM_Numeric GUM_SCALAR >
1377 template < GUM_Numeric GUM_SCALAR >
1383 template < GUM_Numeric GUM_SCALAR >
1389 template < GUM_Numeric GUM_SCALAR >
1395 template < GUM_Numeric GUM_SCALAR >
1401 template < GUM_Numeric GUM_SCALAR >
1407 template < GUM_Numeric GUM_SCALAR >
1413 template < GUM_Numeric GUM_SCALAR >
1419 template < GUM_Numeric GUM_SCALAR >
1424 template < GUM_Numeric GUM_SCALAR >
A listener that allows BNLearner to be used as a proxy for its inner algorithms.
A basic pack of learning algorithms that can easily be used.
Class representing a Bayesian network.
BDeuPrior(const DatabaseTable &database, const Bijection< NodeId, std::size_t > &nodeId2columns=Bijection< NodeId, std::size_t >())
default constructor
A pack of learning algorithms that can easily be used.
BNLearner< GUM_SCALAR > & useNoPrior()
BNLearner< GUM_SCALAR > & EMdisableMaxIter()
Disable stopping criterion on max iterations.
BNLearner< GUM_SCALAR > & useFCIChi2Test()
BNLearner< GUM_SCALAR > & EMenableMinEpsilonRate()
Enable the log-likelihood evolution rate stopping criterion.
BNLearner< GUM_SCALAR > & useGreedyThickThinning()
BNLearner< GUM_SCALAR > & addForbiddenArc(const Arc &arc)
BNLearner< GUM_SCALAR > & useScoreAIC()
BNLearner< GUM_SCALAR > & eraseMandatoryArc(const Arc &arc)
BNLearner< GUM_SCALAR > & setTotalOrder(const std::vector< std::string > &order)
BNLearner< GUM_SCALAR > & EMdisableEpsilon()
Disable the min log-likelihood diff stopping criterion.
BNLearner< GUM_SCALAR > & addPossibleEdge(const Edge &edge)
BNLearner< GUM_SCALAR > & useScoreBD()
BNLearner< GUM_SCALAR > & allowArcReversals(bool allow)
std::vector< std::tuple< std::string, std::string, std::string > > state() const
BNLearner< GUM_SCALAR > & setPCStable(bool stable)
BNLearner< GUM_SCALAR > & addMandatoryArc(const Arc &arc)
BNLearner< GUM_SCALAR > & useDirichletPrior(std::string_view filename, double weight)
BNLearner< GUM_SCALAR > & useScoreBIC()
BNLearner< GUM_SCALAR > & usePC()
BNLearner< GUM_SCALAR > & useNoCorrection()
std::pair< std::shared_ptr< ParamEstimator >, std::shared_ptr< ParamEstimator > > _initializeEMParameterLearning_(const DAG &dag, bool takeIntoAccountScore)
initializes EM and returns a pair containing, first, a bootstrap estimator and, second,...
BNLearner< GUM_SCALAR > & useG2Test()
BNLearner< GUM_SCALAR > & setFCIMaxPathLength(Size max_len)
BNLearner< GUM_SCALAR > & EMdisableMinEpsilonRate()
Disable the log-likelihood evolution rate stopping criterion.
BNLearner(std::string_view filename, const std::vector< std::string > &missingSymbols={"?"}, const bool induceTypes=true)
default constructor
BNLearner< GUM_SCALAR > & erasePossibleEdge(const Edge &edge)
BNLearner< GUM_SCALAR > & setGreedyThickThinningReversals(bool allow)
BNLearner< GUM_SCALAR > & setPossibleSkeleton(const UndiGraph &skeleton)
BayesNet< GUM_SCALAR > _learnParameters_(const DAG &dag, bool takeIntoAccountScore)
learns a BN (its parameters) with the structure passed in argument using a single pass estimation (no...
BNLearner< GUM_SCALAR > & EMenableEpsilon()
Enable the log-likelihood min diff stopping criterion in EM.
BNLearner< GUM_SCALAR > & setPCMaxCondSetSize(Size max_k)
BNLearner< GUM_SCALAR > & setPossibleEdges(const EdgeSet &set)
BNLearner< GUM_SCALAR > & allowArcDeletions(bool allow)
BNLearner< GUM_SCALAR > & useEM(const double epsilon, const double noise)
use The EM algorithm to learn parameters
BNLearner< GUM_SCALAR > & setFCIExhaustiveSepSet(bool exhaustive)
BNLearner< GUM_SCALAR > & EMenableMaxTime()
enable EM's timeout stopping criterion
BayesNet< GUM_SCALAR > _learnParametersWithEM_(const DAG &dag, bool takeIntoAccountScore)
learns a BN (its parameters) with the structure passed in argument using the EM algorithm initialized...
BNLearner< GUM_SCALAR > & addNoChildrenNode(NodeId node)
BNLearner< GUM_SCALAR > & EMsetEpsilon(const double eps)
sets the stopping criterion of EM as being the minimal difference between two consecutive log-likelih...
BNLearner< GUM_SCALAR > & EMdisableMaxTime()
Disable EM's timeout stopping criterion.
BNLearner & operator=(const BNLearner &)
copy operator
bool greedyThickThinningReversals() const
BNLearner< GUM_SCALAR > & useGreedyHillClimbing()
BNLearner< GUM_SCALAR > & forbidEM()
prevent using the EM algorithm for parameter learning
BNLearner< GUM_SCALAR > & useK2(const Sequence< NodeId > &order)
BNLearner< GUM_SCALAR > & useExtendedGreedyHillClimbing()
BNLearner< GUM_SCALAR > & useScoreK2()
BNLearner< GUM_SCALAR > & setMandatoryArcs(const ArcSet &set)
BNLearner< GUM_SCALAR > & eraseNoChildrenNode(NodeId node)
BNLearner< GUM_SCALAR > & useMIIC()
bool fciExhaustiveSepSet() const
BNLearner< GUM_SCALAR > & EMsetPeriodSize(const Size p)
how many samples between 2 stoppings isEnabled
BayesNet< GUM_SCALAR > learnBN()
learn a Bayes Net from a file (must have read the db before)
BNLearner< GUM_SCALAR > & useEMWithDiffCriterion(const double epsilon, const double noise)
use The EM algorithm to learn parameters with the diff stopping criterion
BNLearner< GUM_SCALAR > & setForbiddenArcs(const ArcSet &set)
bool isConstraintBased() const
BNLearner< GUM_SCALAR > & setInitialDAG(const DAG &dag)
BNLearner< GUM_SCALAR > & addNoParentNode(NodeId node)
BNLearner< GUM_SCALAR > & setPCAlpha(double alpha)
BNLearner< GUM_SCALAR > & useScoreLog2Likelihood()
BNLearner< GUM_SCALAR > & useBDeuPrior()
use the BDeu prior with the default weight (key priorWeight of the section learning)
BNLearner< GUM_SCALAR > & EMsetMaxIter(const Size max)
add a max iteration stopping criterion
BNLearner< GUM_SCALAR > & useFCI()
bool isScoreBased() const
BNLearner< GUM_SCALAR > & EMsetMinEpsilonRate(const double rate)
sets the stopping criterion of EM as being the minimal log-likelihood's evolution rate
BNLearner< GUM_SCALAR > & allowArcTriangleDeletions(bool allow)
NodeProperty< Sequence< std::string > > _labelsFromBN_(std::string_view filename, const BayesNet< GUM_SCALAR > &src)
read the first line of a file to find column names
BNLearner< GUM_SCALAR > & useMDLCorrection()
BNLearner< GUM_SCALAR > & eraseNoParentNode(NodeId node)
BNLearner< GUM_SCALAR > & allowArcAdditions(bool allow)
BNLearner< GUM_SCALAR > & EMsetVerbosity(const bool v)
sets or unsets EM's verbosity
BNLearner< GUM_SCALAR > & eraseForbiddenArc(const Arc &arc)
BayesNet< GUM_SCALAR > learnParameters(const DAG &dag, bool takeIntoAccountScore=true)
learns a BN (its parameters) with the structure passed in argument
BNLearner< GUM_SCALAR > & setFCIAlpha(double alpha)
BNLearner< GUM_SCALAR > & useFCIG2Test()
void _checkDAGCompatibility_(const DAG &dag)
check that the database contains the nodes of the dag, else raise an exception
BNLearner< GUM_SCALAR > & useNMLCorrection()
BNLearner< GUM_SCALAR > & useEMWithRateCriterion(const double epsilon, const double noise)
use The EM algorithm to learn parameters with the rate stopping criterion
BNLearner< GUM_SCALAR > & setSliceOrder(const NodeProperty< NodeId > &slice_order)
std::string toString() const
void createPrior_() override
create the prior used for learning
BNLearner< GUM_SCALAR > & EMsetMaxTime(const double timeout)
add a stopping criterion on timeout
void copyState(const BNLearner< GUM_SCALAR > &learner)
copy the states of the BNLearner
BNLearner< GUM_SCALAR > & setPCUnshieldedColliderSorted(bool sorted)
BNLearner< GUM_SCALAR > & EMenableMaxIter()
Enable stopping criterion on max iterations.
BNLearner< GUM_SCALAR > & useChi2Test()
BNLearner< GUM_SCALAR > & useLocalSearchWithTabuList()
use a local search with tabu list and the default parameters (keys tabuListSize and tabuNbDecrease)
BNLearner< GUM_SCALAR > & useScoreBDeu()
BNLearner< GUM_SCALAR > & useSmoothingPrior()
use the smoothing prior with the default weight (key priorWeight)
BNLearner< GUM_SCALAR > & setMaxIndegree(Size max_indegree)
Class for fast parsing of CSV file (never more than one line in application memory).
A DBRowGenerator class that returns the rows that are complete (fully observed) w....
A DBRowGenerator class that returns incomplete rows as EM would do.
the class used to read a row in the database and to transform it into a set of DBRow instances that c...
The class used to pack sets of generators.
void insertGenerator(const Generator &generator)
inserts a new generator at the end of the set
The base class for all DBRow generators.
DirichletPriorFromBN(const DatabaseTable &learning_db, const BayesNet< GUM_SCALAR > *priorbn)
default constructor
DirichletPriorFromDatabase(const DatabaseTable &learning_db, const DBRowGeneratorParser &prior_parser, const Bijection< NodeId, std::size_t > &nodeId2columns=Bijection< NodeId, std::size_t >())
default constructor
A pack of learning algorithms that can easily be used.
void usePC()
indicate that we wish to use PC (Chi2 test by default)
void useBDeuPrior()
use the BDeu prior with the default weight (key priorWeight of the section learning)
void eraseNoChildrenNode(NodeId node)
void EMenableEpsilon()
Enable the log-likelihood min diff stopping criterion in EM.
void EMsetPeriodSize(Size p)
how many samples between 2 stoppings isEnabled
void useGreedyHillClimbing()
indicate that we wish to use a greedy hill climbing algorithm
void useScoreBDeu()
indicate that we wish to use a BDeu score
void addNoParentNode(NodeId node)
void setSliceOrder(const NodeProperty< NodeId > &slice_order)
sets a partial order on the nodes
bool isScoreBased() const
indicate if the selected algorithm is score-based
void setForbiddenArcs(const ArcSet &set)
removes a total
void useFCIChi2Test()
indicate that we wish to use Chi2 independence test for FCI
void setMandatoryArcs(const ArcSet &set)
assign a set of mandatory arcs
bool greedyThickThinningReversals() const
returns whether arc reversals are allowed in the thin phase of greedy thick-thinning
void EMdisableMinEpsilonRate()
Disable the log-likelihood evolution rate stopping criterion.
void useExtendedGreedyHillClimbing()
indicate that we wish to use the extended greedy hill climbing algorithm
void setFCIMaxPathLength(Size max_len)
set maximum discriminating-path length for FCI R4 (default Size(-1) = unlimited)
void useEMWithRateCriterion(const double epsilon, const double noise)
use The EM algorithm to learn parameters with the rate stopping criterion
void addMandatoryArc(const Arc &arc)
void EMenableMaxIter()
Enable stopping criterion on max iterations.
void useFCI()
indicate that we wish to use FCI (Chi2 test by default)
void useSmoothingPrior()
use the prior smoothing with the default weight (key priorWeight of the section learning)
void useEM(const double epsilon, const double noise)
use The EM algorithm to learn parameters
void useFCIG2Test()
indicate that we wish to use G2 independence test for FCI
void setMaxIndegree(Size max_indegree)
sets the max indegree
void EMdisableEpsilon()
Disable the min log-likelihood diff stopping criterion for EM.
void addPossibleEdge(const Edge &edge)
void EMsetMaxIter(Size max)
add a max iteration stopping criterion
void useChi2Test()
indicate that we wish to use Chi2 independence test for PC
void setInitialDAG(const DAG &)
sets an initial DAG structure
void useK2(const Sequence< NodeId > &order)
indicate that we wish to use K2
void allowArcDeletions(bool allow=true)
allow (true)/forbid (false) to delete arcs during learning.
void EMsetMinEpsilonRate(double rate)
sets the stopping criterion of EM as being the minimal log-likelihood's evolution rate
void setGreedyThickThinningReversals(bool allow)
enable or disable arc reversals in the thin phase of greedy thick-thinning
void EMdisableMaxIter()
Disable stopping criterion on max iterations.
void erasePossibleEdge(const Edge &edge)
void useScoreBIC()
indicate that we wish to use a BIC score
void allowArcTriangleDeletions(bool allow=true)
allow (true)/forbid (false) to delete arc triangles during learning.
void useEMWithDiffCriterion(const double epsilon, const double noise)
use The EM algorithm to learn parameters with the diff stopping criterion
void EMsetVerbosity(bool v)
sets or unsets EM's verbosity
void setPossibleEdges(const EdgeSet &set)
assign a set of possible edges
void useNoPrior()
use no prior
void eraseForbiddenArc(const Arc &arc)
void allowArcAdditions(bool allow=true)
allow (true)/forbid (false) to add arcs during learning.
void useScoreK2()
indicate that we wish to use a K2 score
void useGreedyThickThinning()
indicate that we wish to use greedy thick-thinning
void useG2Test()
indicate that we wish to use G2 independence test for PC
void setPossibleSkeleton(const UndiGraph &skeleton)
assign a set of possible edges
void useNMLCorrection()
indicate that we wish to use the NML correction for and MIIC
void forbidEM()
prevent using the EM algorithm for parameter learning
void useLocalSearchWithTabuList()
indicate that we wish to use a local search with tabu list and the default parameters
void setPCMaxCondSetSize(Size max_k)
set maximum conditioning set size for PC (default Size(-1) = unlimited)
void EMenableMaxTime()
sets the stopping criterion of EM as being the minimal difference between two consecutive log-likelih...
void useNoCorrection()
indicate that we wish to use the NoCorr correction for MIIC
void useScoreLog2Likelihood()
indicate that we wish to use a Log2Likelihood score
void useMDLCorrection()
indicate that we wish to use the MDL correction for MIIC
void setFCIAlpha(double alpha)
set the significance threshold alpha for FCI. If it is never set, FCI uses the key learning....
bool fciExhaustiveSepSet() const
return true when FCI uses exhaustive sepset mode
void setPCAlpha(double alpha)
set the significance threshold alpha for PC. If it is never set, PC uses the key learning....
void useDirichletPrior(std::string_view filename, double weight)
use the Dirichlet prior from a database
void addForbiddenArc(const Arc &arc)
void addNoChildrenNode(NodeId node)
void EMsetMaxTime(double timeout)
add a stopping criterion on timeout
IBNLearner & operator=(const IBNLearner &)
copy operator
void EMenableMinEpsilonRate()
Enable the log-likelihood evolution rate stopping criterion.
void setFCIExhaustiveSepSet(bool exhaustive)
enable exhaustive sepset mode for FCI skeleton learning (default false)
void setTotalOrder(const Sequence< NodeId > &order)
sets a total order over some nodes
void useScoreAIC()
indicate that we wish to use an AIC score
void eraseMandatoryArc(const Arc &arc)
void allowArcReversals(bool allow=true)
allow (true)/forbid (false) to reverse arcs during learning.
void useMIIC()
indicate that we wish to use MIIC
void EMdisableMaxTime()
Disable EM's timeout stopping criterion.
void eraseNoParentNode(NodeId node)
void setPCUnshieldedColliderSorted(bool sorted)
set unshielded-collider ordering for PC: sorted=true uses descending p-value order (strongest evidenc...
void EMsetEpsilon(double eps)
sets the stopping criterion of EM as being the minimal difference between two consecutive log-likelih...
void setPCStable(bool stable)
set stable mode for PC — defer removals to end of each depth level (default true)
void useScoreBD()
indicate that we wish to use a BD score
bool isConstraintBased() const
indicate if the selected algorithm is constraint-based
NoPrior(const DatabaseTable &database, const Bijection< NodeId, std::size_t > &nodeId2columns=Bijection< NodeId, std::size_t >())
default constructor
the base class for all a priori
virtual void setWeight(double weight)
sets the weight of the a prior(kind of effective sample size)
SmoothingPrior(const DatabaseTable &database, const Bijection< NodeId, std::size_t > &nodeId2columns=Bijection< NodeId, std::size_t >())
default constructor
Typed, documented, sectioned configuration singleton read from an .ini content.
#define GUM_ERROR(type, msg)
std::size_t Size
In aGrUM, hashed values are unsigned long int.
Size Idx
Type for indexes.
Set< Edge > EdgeSet
Some typdefs and define for shortcuts ...
Size NodeId
Type for node ids.
Set< Arc > ArcSet
Some typdefs and define for shortcuts ...
HashTable< NodeId, VAL > NodeProperty
Property on graph elements.
include the inlined functions if necessary
GUM_SHARED_PUBLIC std::ostream & operator<<(std::ostream &stream, const IdCondSet &idset)
the display operator
gum is the global namespace for all aGrUM entities
Configuration & config()
A short name for Configuration::instance() : gum::config().epsilonStandard(). It is not inline so tha...