aGrUM 3.3.2
a C++ library for (probabilistic) graphical models
BNLearner_tpl.h
Go to the documentation of this file.
1/****************************************************************************
2 * This file is part of the aGrUM/pyAgrum library. *
3 * *
4 * Copyright (c) 2005-2026 by *
5 * - Pierre-Henri WUILLEMIN(_at_LIP6) *
6 * - Christophe GONZALES(_at_AMU) *
7 * *
8 * The aGrUM/pyAgrum library is free software; you can redistribute it *
9 * and/or modify it under the terms of either : *
10 * *
11 * - the GNU Lesser General Public License as published by *
12 * the Free Software Foundation, either version 3 of the License, *
13 * or (at your option) any later version, *
14 * - the MIT license (MIT), *
15 * - or both in dual license, as here. *
16 * *
17 * (see https://agrum.gitlab.io/articles/dual-licenses-lgplv3mit.html) *
18 * *
19 * This aGrUM/pyAgrum library is distributed in the hope that it will be *
20 * useful, but WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, *
21 * INCLUDING BUT NOT LIMITED TO THE WARRANTIES MERCHANTABILITY or FITNESS *
22 * FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE *
23 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER *
24 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, *
25 * ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR *
26 * OTHER DEALINGS IN THE SOFTWARE. *
27 * *
28 * See LICENCES for more details. *
29 * *
30 * SPDX-FileCopyrightText: Copyright 2005-2026 *
31 * - Pierre-Henri WUILLEMIN(_at_LIP6) *
32 * - Christophe GONZALES(_at_AMU) *
33 * SPDX-License-Identifier: LGPL-3.0-or-later OR MIT *
34 * *
35 * Contact : info_at_agrum_dot_org *
36 * homepage : http://agrum.gitlab.io *
37 * gitlab : https://gitlab.com/agrumery/agrum *
38 * *
39 ****************************************************************************/
40
41#pragma once
42
43
52#include <fstream>
53
55#include <agrum/BN/learning/BNLearner.h> // to ease IDE parser
56
57#ifndef DOXYGEN_SHOULD_SKIP_THIS
58
59// to help IDE parser
62
63namespace gum {
64
65 namespace learning {
66 template < GUM_Numeric GUM_SCALAR >
67 BNLearner< GUM_SCALAR >::BNLearner(std::string_view filename,
68 const std::vector< std::string >& missingSymbols,
69 const bool induceTypes) :
70 IBNLearner(filename, missingSymbols, induceTypes) {
71 GUM_CONSTRUCTOR(BNLearner);
72 }
73
74 template < GUM_Numeric GUM_SCALAR >
75 BNLearner< GUM_SCALAR >::BNLearner(const DatabaseTable& db) : IBNLearner(db) {
76 GUM_CONSTRUCTOR(BNLearner);
77 }
78
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);
85 }
86
88 template < GUM_Numeric GUM_SCALAR >
89 BNLearner< GUM_SCALAR >::BNLearner(const BNLearner< GUM_SCALAR >& src) : IBNLearner(src) {
90 GUM_CONSTRUCTOR(BNLearner);
91 }
92
94 template < GUM_Numeric GUM_SCALAR >
95 BNLearner< GUM_SCALAR >::BNLearner(BNLearner< GUM_SCALAR >&& src) : IBNLearner(src) {
96 GUM_CONSTRUCTOR(BNLearner);
97 }
98
100 template < GUM_Numeric GUM_SCALAR >
101 BNLearner< GUM_SCALAR >::~BNLearner() {
102 GUM_DESTRUCTOR(BNLearner);
103 }
104
106
107 // ##########################################################################
109 // ##########################################################################
111
113 template < GUM_Numeric GUM_SCALAR >
117 return *this;
118 }
119
121 template < GUM_Numeric GUM_SCALAR >
124 IBNLearner::operator=(std::move(src));
125 return *this;
126 }
127
129 template < GUM_Numeric GUM_SCALAR >
130 BayesNet< GUM_SCALAR > BNLearner< GUM_SCALAR >::learnBN() {
131 // create the score, the prior and the estimator
132 auto notification = checkScorePriorCompatibility();
133 if (notification != "") { std::cout << "[aGrUM notification] " << notification << std::endl; }
134 createPrior_();
135 createScore_();
136
137 std::unique_ptr< ParamEstimator > param_estimator(
138 createParamEstimator_(scoreDatabase_.parser(), true));
139
140 return dag2BN_.createBN< GUM_SCALAR >(*(param_estimator.get()), learnDag_());
141 }
142
143 // check that the database contains the nodes of the dag, else raise an exception
144 template < GUM_Numeric GUM_SCALAR >
146 // if the dag contains no node, this is compatible with the database
147 if (dag.size() == 0) return;
148
149 // check that the dag corresponds to the database
150 std::vector< NodeId > ids;
151 ids.reserve(dag.sizeNodes());
152 for (const auto node: dag)
153 ids.push_back(node);
154 std::sort(ids.begin(), ids.end());
155
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);
162 }
163 if (bad_ids.size() > 1) str += 's';
164 str += ": ";
165 bool deja = false;
166 for (const auto node: bad_ids) {
167 if (deja) str += ", ";
168 else deja = true;
169 str += std::to_string(node);
170 }
171 GUM_ERROR(MissingVariableInDatabase, str)
172 }
173 }
174
175 // learns a BN (its parameters) using a basic learning when its structure is known
176 template < GUM_Numeric GUM_SCALAR >
177 BayesNet< GUM_SCALAR > BNLearner< GUM_SCALAR >::_learnParameters_(const DAG& dag,
178 bool takeIntoAccountScore) {
179 // if the dag contains no node, return an empty BN
180 if (dag.size() == 0) return BayesNet< GUM_SCALAR >();
181
182 // be sure that the database contains dag's node ids
183 _checkDAGCompatibility_(dag);
184
185 // create the prior
186 createPrior_();
187
188 // check that the database does not contain any missing value
189 if (scoreDatabase_.databaseTable().hasMissingValues()
190 || ((priorDatabase_ != nullptr)
191 && (priorType_ == BNLearnerPriorType::DIRICHLET_FROM_DATABASE)
192 && priorDatabase_->databaseTable().hasMissingValues())) {
193 GUM_ERROR(MissingValueInDatabase,
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()");
197 }
198
199 // create the usual estimator
200 DBRowGeneratorParser parser(scoreDatabase_.databaseTable().handler(), DBRowGeneratorSet());
201 std::unique_ptr< ParamEstimator > param_estimator(
202 createParamEstimator_(parser, takeIntoAccountScore));
203
204 return dag2BN_.createBN< GUM_SCALAR >(*(param_estimator.get()), dag);
205 }
206
207 // initialize the parameter learning by EM
208 // GCC 16 false positive: VRP inlines shared_ptr<ParamEstimator> control block and
209 // incorrectly reports -Warray-bounds on the mutex; #pragma GCC diagnostic cannot
210 // suppress warnings whose primary location is in system headers (stl_construct.h),
211 // so we disable VRP for this function via optimize pragma instead
212# if defined(__GNUC__) && !defined(__clang__)
213# pragma GCC push_options
214# pragma GCC optimize("no-tree-vrp")
215# endif
216
217 template < GUM_Numeric GUM_SCALAR >
218 std::pair< std::shared_ptr< ParamEstimator >, std::shared_ptr< ParamEstimator > >
220 bool takeIntoAccountScore) {
221 // be sure that the database contains dag's node ids
222 _checkDAGCompatibility_(dag);
223
224 // create the prior
225 createPrior_();
226
227 // propagate the messages of dag2BN_ to the BNLearner so that the objects that listen
228 // to the BNLearner can be informed of the progress of the EM's execution by dag2BN_
229 // BNLearnerListener listener(this, dag2BN_);
230
231 // get the column types
232 const auto& database = scoreDatabase_.databaseTable();
233 const std::size_t nb_vars = database.nbVariables();
234 const std::vector< gum::learning::DBTranslatedValueType > col_types(
235 nb_vars,
237
238 // create the bootstrap estimator
239 DBRowGenerator4CompleteRows generator_bootstrap(col_types);
240 DBRowGeneratorSet genset_bootstrap;
241 genset_bootstrap.insertGenerator(generator_bootstrap);
242 DBRowGeneratorParser parser_bootstrap(database.handler(), genset_bootstrap);
243 std::shared_ptr< ParamEstimator > param_estimator_bootstrap(
244 createParamEstimator_(parser_bootstrap, takeIntoAccountScore));
245
246 // create the EM estimator
247 BayesNet< GUM_SCALAR > dummy_bn;
248 DBRowGeneratorEM< GUM_SCALAR > generator_EM(col_types, dummy_bn);
249 DBRowGenerator& gen_EM = generator_EM; // fix for g++-4.8
250 DBRowGeneratorSet genset_EM;
251 genset_EM.insertGenerator(gen_EM);
252 DBRowGeneratorParser parser_EM(database.handler(), genset_EM);
253 std::shared_ptr< ParamEstimator > param_estimator_EM(
254 createParamEstimator_(parser_EM, takeIntoAccountScore));
255
256 return {param_estimator_bootstrap, param_estimator_EM};
257 }
258
259# if defined(__GNUC__) && !defined(__clang__)
260# pragma GCC pop_options
261# endif
262
263 // learns a BN (its parameters) with EM when its structure is known
264 template < GUM_Numeric GUM_SCALAR >
265 BayesNet< GUM_SCALAR >
267 bool takeIntoAccountScore) {
268 // if the dag contains no node, return an empty BN
269 if (dag.size() == 0) return BayesNet< GUM_SCALAR >();
270
271 // get a pair containing the bootstrap and the EM estimators
272 auto estimators = _initializeEMParameterLearning_(dag, takeIntoAccountScore);
273
274 // perform the EM algorithm
275 return dag2BN_.createBNwithEM< GUM_SCALAR >(*(estimators.first.get()),
276 *(estimators.second.get()),
277 dag);
278 }
279
281 template < GUM_Numeric GUM_SCALAR >
282 BayesNet< GUM_SCALAR >
283 BNLearner< GUM_SCALAR >::_learnParametersWithEM_(const BayesNet< GUM_SCALAR >& bn,
284 bool takeIntoAccountScore) {
285 // if the dag contains no node, return an empty BN
286 if (bn.internalDag().size() == 0) return BayesNet< GUM_SCALAR >();
287
288 // get a pair containing the bootstrap and the EM estimators
289 auto estimators = _initializeEMParameterLearning_(bn.internalDag(), takeIntoAccountScore);
290
291 return dag2BN_.createBNwithEM< GUM_SCALAR >(*(estimators.first.get()),
292 *(estimators.second.get()),
293 bn);
294 }
295
297 template < GUM_Numeric GUM_SCALAR >
298 BayesNet< GUM_SCALAR > BNLearner< GUM_SCALAR >::learnParameters(const DAG& dag,
299 bool takeIntoAccountScore) {
300 if (!scoreDatabase_.databaseTable().hasMissingValues() || !useEM_) {
301 // here, we learn without EM
302 return _learnParameters_(dag, takeIntoAccountScore);
303 } else {
304 // here we learn with EM
305 return _learnParametersWithEM_(dag, takeIntoAccountScore);
306 }
307 }
308
310 template < GUM_Numeric GUM_SCALAR >
311 BayesNet< GUM_SCALAR >
312 BNLearner< GUM_SCALAR >::learnParameters(const BayesNet< GUM_SCALAR >& bn,
313 bool takeIntoAccountScore) {
314 if (!scoreDatabase_.databaseTable().hasMissingValues() || !useEM_) {
315 DAG dag;
316 const auto& db = scoreDatabase_.databaseTable();
317 for (const auto n: bn.nodes()) {
318 dag.addNodeWithId(db.columnFromVariableName(bn.variable(n).name()));
319 }
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()));
323 }
324
325 // create le DAG en fonction des
326 return _learnParameters_(dag, takeIntoAccountScore);
327 } else {
328 return _learnParametersWithEM_(bn, takeIntoAccountScore);
329 }
330 }
331
333 template < GUM_Numeric GUM_SCALAR >
334 BayesNet< GUM_SCALAR > BNLearner< GUM_SCALAR >::learnParameters(bool take_into_account_score) {
335 return learnParameters(initialDag_, take_into_account_score);
336 }
337
338 template < GUM_Numeric GUM_SCALAR >
340 BNLearner< GUM_SCALAR >::_labelsFromBN_(std::string_view filename,
341 const BayesNet< GUM_SCALAR >& src) {
342 std::ifstream in(std::string(filename), std::ifstream::in);
343
344 if ((in.rdstate() & std::ifstream::failbit) != 0) {
345 GUM_ERROR(gum::IOError, "File " << filename << " not found")
346 }
347
348 CSVParser parser(in, std::string(filename));
349 parser.next();
350 auto names = parser.current();
351
353
354 for (gum::Idx col = 0; col < names.size(); col++) {
355 if (src.exists(names[col])) {
356 gum::NodeId graphId = src.idFromName(names[col]);
357 modals.insert(col, gum::Sequence< std::string >());
358
359 for (gum::Size i = 0; i < src.variable(graphId).domainSize(); ++i)
360 modals[col].insert(src.variable(graphId).label(i));
361 }
362 // else: no problem, a column not in the BN...
363 }
364
365 return modals;
366 }
367
368 template < GUM_Numeric GUM_SCALAR >
369 std::string BNLearner< GUM_SCALAR >::toString() const {
370 const auto st = state();
371
372 Size maxkey = 0;
373 for (const auto& tuple: st)
374 if (std::get< 0 >(tuple).length() > maxkey) maxkey = std::get< 0 >(tuple).length();
375
376 std::string s;
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));
380 s += '\n';
381 }
382 return s;
383 }
384
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;
389
390 std::string key;
391 std::string comment;
392 const auto& db = database();
393
394 vals.emplace_back("Filename", filename_, "");
395 vals.emplace_back("Size",
396 "(" + std::to_string(nbRows()) + "," + std::to_string(nbCols()) + ")",
397 "");
398
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)) + "]";
403 }
404 vals.emplace_back("Variables", vars, "");
405 vals.emplace_back("Induced types", inducedTypes_ ? "True" : "False", "");
406 vals.emplace_back("Missing values", hasMissingValues() ? "True" : "False", "");
407
408 key = "Algorithm";
409 switch (selectedAlgo_) {
410 case AlgoType::GREEDY_HILL_CLIMBING :
411 vals.emplace_back(key, "Greedy Hill Climbing", "");
412 break;
413 case AlgoType::EXTENDED_GREEDY_HILL_CLIMBING :
414 vals.emplace_back(key, "Extended Greedy Hill Climbing", "");
415 break;
416 case AlgoType::K2 : {
417 vals.emplace_back(key, "K2", "");
418 const auto& k2order = algoK2_.order();
419 vars = "";
420 for (NodeId i = 0; i < k2order.size(); i++) {
421 if (i > 0) vars += ", ";
422 vars += nameFromId(k2order.atPos(i));
423 }
424 vals.emplace_back("K2 order", vars, "");
425 } break;
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_),
431 "");
432 break;
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", "");
438 break;
439 default : vals.emplace_back(key, "(unknown)", "?"); break;
440 }
441
442 key = "Score";
443
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;
455 }
456 }
457
458 if (isConstraintBased()) {
459 key = "Correction";
460 switch (kmodeMiic_) {
462 vals.emplace_back(key, "MDL", "");
463 break;
465 vals.emplace_back(key, "NML", "");
466 break;
468 vals.emplace_back(key, "No correction", "");
469 break;
470 default : vals.emplace_back(key, "(unknown)", "?"); break;
471 }
472 }
473
474 key = "Prior";
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_, "");
481 break;
482 case BNLearnerPriorType::DIRICHLET_FROM_BAYESNET :
483 vals.emplace_back(key, "Dirichlet", comment);
484 vals.emplace_back("Dirichlet from Bayesian network : ", _prior_bn_.toString(), "");
485 break;
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;
489 }
490
491 if (priorType_ != BNLearnerPriorType::NO_prior)
492 vals.emplace_back("Prior weight", std::to_string(priorWeight_), "");
493
494 if (databaseWeight() != double(nbRows())) {
495 vals.emplace_back("Database weight", std::to_string(databaseWeight()), "");
496 }
497
498 if (useEM_) {
499 comment = "";
500 if (!hasMissingValues()) comment = "But no missing values in this database";
501 vals.emplace_back("use EM", "True", "");
502 std::string s = "[";
503 bool first = true;
504 if (dag2BN_.isEnabledMinEpsilonRate()) {
505 s += std::format("MinRate: {}", dag2BN_.minEpsilonRate());
506 first = false;
507 }
508 if (dag2BN_.isEnabledEpsilon()) {
509 if (!first) s += ", ";
510 first = false;
511 s += std::format("MinDiff: {}", dag2BN_.epsilon());
512 }
513 if (dag2BN_.isEnabledMaxIter()) {
514 if (!first) s += ", ";
515 first = false;
516 s += std::format("MaxIter: {}", dag2BN_.maxIter());
517 }
518 if (dag2BN_.isEnabledMaxTime()) {
519 if (!first) s += ", ";
520 first = false;
521 s += std::format("MaxTime: {}", dag2BN_.maxTime());
522 }
523 s += "]";
524 vals.emplace_back("EM stopping criteria", s, comment);
525 }
526
527 std::string res;
528 bool nofirst;
529 if (constraintIndegree_.maxIndegree() < std::numeric_limits< Size >::max()) {
530 vals.emplace_back("Constraint Max InDegree",
531 std::to_string(constraintIndegree_.maxIndegree()),
532 "");
533 }
534 if (!constraintForbiddenArcs_.arcs().empty()) {
535 res = "{";
536 nofirst = false;
537 for (const auto& arc: constraintForbiddenArcs_.arcs()) {
538 if (nofirst) res += ", ";
539 else nofirst = true;
540 res += nameFromId(arc.tail()) + "->" + nameFromId(arc.head());
541 }
542 res += "}";
543 vals.emplace_back("Constraint Forbidden Arcs", res, "");
544 }
545 if (!constraintMandatoryArcs_.arcs().empty()) {
546 res = "{";
547 nofirst = false;
548 for (const auto& arc: constraintMandatoryArcs_.arcs()) {
549 if (nofirst) res += ", ";
550 else nofirst = true;
551 res += nameFromId(arc.tail()) + "->" + nameFromId(arc.head());
552 }
553 res += "}";
554 vals.emplace_back("Constraint Mandatory Arcs", res, "");
555 }
556 if (!constraintPossibleEdges_.edges().empty()) {
557 res = "{";
558 nofirst = false;
559 for (const auto& edge: constraintPossibleEdges_.edges()) {
560 if (nofirst) res += ", ";
561 else nofirst = true;
562 res += nameFromId(edge.first()) + "--" + nameFromId(edge.second());
563 }
564 res += "}";
565 vals.emplace_back("Constraint Possible Edges", res, "");
566 }
567 if (!constraintSliceOrder_.sliceOrder().empty()) {
568 res = "{";
569 nofirst = false;
570 const auto& order = constraintSliceOrder_.sliceOrder();
571 for (const auto& p: order) {
572 if (nofirst) res += ", ";
573 else nofirst = true;
574 res += nameFromId(p.first) + ":" + std::to_string(p.second);
575 }
576 res += "}";
577 vals.emplace_back("Constraint Slice Order", res, "");
578 }
579 if (!constraintNoParentNodes_.nodes().empty()) {
580 res = "{";
581 nofirst = false;
582 for (const auto& node: constraintNoParentNodes_.nodes()) {
583 if (nofirst) res += ", ";
584 else nofirst = true;
585 res += nameFromId(node);
586 }
587 res += "}";
588 vals.emplace_back("Constraint No Parent Nodes", res, "");
589 }
590 if (!constraintNoChildrenNodes_.nodes().empty()) {
591 res = "{";
592 nofirst = false;
593 for (const auto& node: constraintNoChildrenNodes_.nodes()) {
594 if (nofirst) res += ", ";
595 else nofirst = true;
596 res += nameFromId(node);
597 }
598 res += "}";
599 vals.emplace_back("Constraint No Children Nodes", res, "");
600 }
601 if (initialDag_.size() != 0) {
602 vals.emplace_back("Initial DAG", "True", initialDag_.toDot());
603 }
604
605 return vals;
606 }
607
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());
616 break;
617 case AlgoType::K2 : useK2(learner.algoK2_.order()); break;
618 case AlgoType::LOCAL_SEARCH_WITH_TABU_LIST :
619 useLocalSearchWithTabuList(learner.tabuListSize_, learner.nbDecreasingChanges_);
620 break;
621 case AlgoType::MIIC : useMIIC(); break;
622 case AlgoType::PC : usePC(); break;
623 case AlgoType::FCI : useFCI(); break;
624 }
625
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;
635 }
636
637 switch (learner.kmodeMiic_) {
638 case CorrectedMutualInformation::KModeTypes::MDL : useMDLCorrection(); break;
639 case CorrectedMutualInformation::KModeTypes::NML : useNMLCorrection(); break;
640 case CorrectedMutualInformation::KModeTypes::NoCorr : useNoCorrection(); break;
641 }
642
643 switch (learner.priorType_) {
644 case BNLearnerPriorType::NO_prior : useNoPrior(); break;
645 case BNLearnerPriorType::DIRICHLET_FROM_DATABASE :
646 useDirichletPrior(learner.priorDbname_, learner.priorWeight_);
647 break;
648 case BNLearnerPriorType::DIRICHLET_FROM_BAYESNET :
649 useDirichletPrior(learner._prior_bn_, learner.priorWeight_);
650 break;
651 case BNLearnerPriorType::BDEU : useBDeuPrior(learner.priorWeight_); break;
652 case BNLearnerPriorType::SMOOTHING : useSmoothingPrior(learner.priorWeight_); break;
653 }
654
655 useEM_ = learner.useEM_;
656 dag2BN_ = learner.dag2BN_;
657
658 setMaxIndegree(learner.constraintIndegree_.maxIndegree());
659 for (const auto src: learner.constraintNoParentNodes_.nodes()) {
660 try {
661 const auto dst = idFromName(learner.nameFromId(src));
662 addNoParentNode(dst);
663 } catch (const MissingVariableInDatabase&) {
664 // nothing to do
665 }
666 }
667 for (const auto src: learner.constraintNoChildrenNodes_.nodes()) {
668 try {
669 const auto dst = idFromName(learner.nameFromId(src));
670 addNoChildrenNode(dst);
671 } catch (const MissingVariableInDatabase&) {
672 // nothing to do
673 }
674 }
675 for (const auto& arc: learner.constraintForbiddenArcs_.arcs()) {
676 try {
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&) {
681 // nothing to do
682 }
683 }
684 for (const auto& arc: learner.constraintMandatoryArcs_.arcs()) {
685 try {
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&) {
690 // nothing to do
691 }
692 }
693 for (const auto& edge: learner.constraintPossibleEdges_.edges()) {
694 try {
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&) {
699 // nothing to do
700 }
701 }
702 if (!learner.constraintSliceOrder_.sliceOrder().empty()) {
703 NodeProperty< NodeId > slice_order;
704 for (const auto& p: learner.constraintSliceOrder_.sliceOrder()) {
705 try {
706 slice_order.insert(idFromName(learner.nameFromId(p.first)), p.second);
707 } catch (const MissingVariableInDatabase&) {
708 // nothing to do
709 }
710 }
711 setSliceOrder(slice_order);
712 }
713 if (!learner.constraintTotalOrder_.totalOrder().empty()) {
714 setTotalOrder(learner.constraintTotalOrder_.totalOrder());
715 }
716 }
717
718 template < GUM_Numeric GUM_SCALAR >
720 // first, save the old prior, to be delete if everything is ok
721 Prior* old_prior = prior_;
722
723 // create the new prior
724 switch (priorType_) {
725 case BNLearnerPriorType::NO_prior :
726 prior_ = new NoPrior(scoreDatabase_.databaseTable(), scoreDatabase_.nodeId2Columns());
727 break;
728
729 case BNLearnerPriorType::SMOOTHING :
730 prior_
731 = new SmoothingPrior(scoreDatabase_.databaseTable(), scoreDatabase_.nodeId2Columns());
732 break;
733
734 case BNLearnerPriorType::DIRICHLET_FROM_DATABASE :
735 if (priorDatabase_ != nullptr) {
736 delete priorDatabase_;
737 priorDatabase_ = nullptr;
738 }
739
740 priorDatabase_
741 = new Database(priorDbname_, scoreDatabase_, scoreDatabase_.missingSymbols());
742
743 prior_ = new DirichletPriorFromDatabase(scoreDatabase_.databaseTable(),
744 priorDatabase_->parser(),
745 priorDatabase_->nodeId2Columns());
746 break;
747
748 case BNLearnerPriorType::DIRICHLET_FROM_BAYESNET :
749 prior_
750 = new DirichletPriorFromBN< GUM_SCALAR >(scoreDatabase_.databaseTable(), &_prior_bn_);
751 break;
752
753 case BNLearnerPriorType::BDEU :
754 prior_ = new BDeuPrior(scoreDatabase_.databaseTable(), scoreDatabase_.nodeId2Columns());
755 break;
756
757 default : GUM_ERROR(OperationNotAllowed, "The BNLearner does not support yet this prior")
758 }
759
760 // do not forget to assign a weight to the prior
761 prior_->setWeight(priorWeight_);
762
763 // remove the old prior, if any
764 if (old_prior != nullptr) delete old_prior;
765 }
766
767 template < GUM_Numeric GUM_SCALAR >
768 std::ostream& operator<<(std::ostream& output, const BNLearner< GUM_SCALAR >& learner) {
769 output << learner.toString();
770 return output;
771 }
772
773 // =========================================================================
774 // Delegation methods — each calls IBNLearner and returns *this
775 // =========================================================================
776
777 template < GUM_Numeric GUM_SCALAR >
780 return *this;
781 }
782
783 template < GUM_Numeric GUM_SCALAR >
785 IBNLearner::useEM(epsilon);
786 return *this;
787 }
788
789 template < GUM_Numeric GUM_SCALAR >
792 return *this;
793 }
794
795 template < GUM_Numeric GUM_SCALAR >
798 return *this;
799 }
800
801 template < GUM_Numeric GUM_SCALAR >
803 const double noise) {
804 IBNLearner::useEM(epsilon, noise);
805 return *this;
806 }
807
808 template < GUM_Numeric GUM_SCALAR >
810 const double noise) {
812 return *this;
813 }
814
815 template < GUM_Numeric GUM_SCALAR >
817 const double noise) {
819 return *this;
820 }
821
822 template < GUM_Numeric GUM_SCALAR >
825 return *this;
826 }
827
828 template < GUM_Numeric GUM_SCALAR >
831 return *this;
832 }
833
834 template < GUM_Numeric GUM_SCALAR >
837 return *this;
838 }
839
840 template < GUM_Numeric GUM_SCALAR >
843 return *this;
844 }
845
846 template < GUM_Numeric GUM_SCALAR >
849 return *this;
850 }
851
852 template < GUM_Numeric GUM_SCALAR >
855 return *this;
856 }
857
858 template < GUM_Numeric GUM_SCALAR >
861 return *this;
862 }
863
864 template < GUM_Numeric GUM_SCALAR >
867 return *this;
868 }
869
870 template < GUM_Numeric GUM_SCALAR >
873 return *this;
874 }
875
876 template < GUM_Numeric GUM_SCALAR >
879 return *this;
880 }
881
882 template < GUM_Numeric GUM_SCALAR >
885 return *this;
886 }
887
888 template < GUM_Numeric GUM_SCALAR >
891 return *this;
892 }
893
894 template < GUM_Numeric GUM_SCALAR >
897 return *this;
898 }
899
900 template < GUM_Numeric GUM_SCALAR >
903 return *this;
904 }
905
906 template < GUM_Numeric GUM_SCALAR >
909 return *this;
910 }
911
912 template < GUM_Numeric GUM_SCALAR >
915 return *this;
916 }
917
918 template < GUM_Numeric GUM_SCALAR >
921 return *this;
922 }
923
924 template < GUM_Numeric GUM_SCALAR >
927 return *this;
928 }
929
930 template < GUM_Numeric GUM_SCALAR >
933 return *this;
934 }
935
936 template < GUM_Numeric GUM_SCALAR >
939 return *this;
940 }
941
942 template < GUM_Numeric GUM_SCALAR >
945 return *this;
946 }
947
948 template < GUM_Numeric GUM_SCALAR >
951 return *this;
952 }
953
954 template < GUM_Numeric GUM_SCALAR >
957 return *this;
958 }
959
960 template < GUM_Numeric GUM_SCALAR >
963 return *this;
964 }
965
966 template < GUM_Numeric GUM_SCALAR >
969 return *this;
970 }
971
972 template < GUM_Numeric GUM_SCALAR >
974 BNLearner< GUM_SCALAR >::useDirichletPrior(const gum::BayesNet< GUM_SCALAR >& bn) {
975 return useDirichletPrior(bn, gum::config().typed< double >("learning", "priorWeight"));
976 }
977
978 template < GUM_Numeric GUM_SCALAR >
981 return *this;
982 }
983
984 template < GUM_Numeric GUM_SCALAR >
987 return *this;
988 }
989
990 template < GUM_Numeric GUM_SCALAR >
992 double weight) {
993 IBNLearner::useDirichletPrior(filename, weight);
994 return *this;
995 }
996
997 template < GUM_Numeric GUM_SCALAR >
999 BNLearner< GUM_SCALAR >::useDirichletPrior(const gum::BayesNet< GUM_SCALAR >& bn,
1000 double weight) {
1001 _prior_bn_ = bn;
1002 priorType_ = BNLearnerPriorType::DIRICHLET_FROM_BAYESNET;
1003 _setPriorWeight_(weight);
1004 return *this;
1005 }
1006
1007 template < GUM_Numeric GUM_SCALAR >
1010 return *this;
1011 }
1012
1013 template < GUM_Numeric GUM_SCALAR >
1016 return *this;
1017 }
1018
1019 template < GUM_Numeric GUM_SCALAR >
1022 return *this;
1023 }
1024
1025 template < GUM_Numeric GUM_SCALAR >
1028 return *this;
1029 }
1030
1031 template < GUM_Numeric GUM_SCALAR >
1034 }
1035
1036 template < GUM_Numeric GUM_SCALAR >
1039 return *this;
1040 }
1041
1042 template < GUM_Numeric GUM_SCALAR >
1045 return *this;
1046 }
1047
1048 template < GUM_Numeric GUM_SCALAR >
1050 Size nb_decrease) {
1051 IBNLearner::useLocalSearchWithTabuList(tabu_size, nb_decrease);
1052 return *this;
1053 }
1054
1055 template < GUM_Numeric GUM_SCALAR >
1056 BNLearner< GUM_SCALAR >& BNLearner< GUM_SCALAR >::useK2(const Sequence< NodeId >& order) {
1057 IBNLearner::useK2(order);
1058 return *this;
1059 }
1060
1061 template < GUM_Numeric GUM_SCALAR >
1062 BNLearner< GUM_SCALAR >& BNLearner< GUM_SCALAR >::useK2(const std::vector< NodeId >& order) {
1063 IBNLearner::useK2(order);
1064 return *this;
1065 }
1066
1067 template < GUM_Numeric GUM_SCALAR >
1070 return *this;
1071 }
1072
1073 template < GUM_Numeric GUM_SCALAR >
1076 return *this;
1077 }
1078
1079 template < GUM_Numeric GUM_SCALAR >
1082 return *this;
1083 }
1084
1085 template < GUM_Numeric GUM_SCALAR >
1088 return *this;
1089 }
1090
1091 template < GUM_Numeric GUM_SCALAR >
1094 return *this;
1095 }
1096
1097 template < GUM_Numeric GUM_SCALAR >
1100 return *this;
1101 }
1102
1103 template < GUM_Numeric GUM_SCALAR >
1106 return *this;
1107 }
1108
1109 template < GUM_Numeric GUM_SCALAR >
1112 return *this;
1113 }
1114
1115 template < GUM_Numeric GUM_SCALAR >
1118 }
1119
1120 template < GUM_Numeric GUM_SCALAR >
1123 return *this;
1124 }
1125
1126 template < GUM_Numeric GUM_SCALAR >
1129 return *this;
1130 }
1131
1132 template < GUM_Numeric GUM_SCALAR >
1135 return *this;
1136 }
1137
1138 template < GUM_Numeric GUM_SCALAR >
1141 return *this;
1142 }
1143
1144 template < GUM_Numeric GUM_SCALAR >
1147 return *this;
1148 }
1149
1150 template < GUM_Numeric GUM_SCALAR >
1153 return *this;
1154 }
1155
1156 template < GUM_Numeric GUM_SCALAR >
1159 return *this;
1160 }
1161
1162 template < GUM_Numeric GUM_SCALAR >
1165 return *this;
1166 }
1167
1168 template < GUM_Numeric GUM_SCALAR >
1171 return *this;
1172 }
1173
1174 template < GUM_Numeric GUM_SCALAR >
1176 IBNLearner::setMaxIndegree(max_indegree);
1177 return *this;
1178 }
1179
1180 template < GUM_Numeric GUM_SCALAR >
1183 IBNLearner::setSliceOrder(slice_order);
1184 return *this;
1185 }
1186
1187 template < GUM_Numeric GUM_SCALAR >
1189 const std::vector< std::vector< std::string > >& slices) {
1191 return *this;
1192 }
1193
1194 template < GUM_Numeric GUM_SCALAR >
1196 BNLearner< GUM_SCALAR >::setTotalOrder(const std::vector< std::string >& order) {
1198 return *this;
1199 }
1200
1201 template < GUM_Numeric GUM_SCALAR >
1203 BNLearner< GUM_SCALAR >::setTotalOrder(const Sequence< NodeId >& order) {
1205 return *this;
1206 }
1207
1208 template < GUM_Numeric GUM_SCALAR >
1211 return *this;
1212 }
1213
1214 template < GUM_Numeric GUM_SCALAR >
1217 return *this;
1218 }
1219
1220 template < GUM_Numeric GUM_SCALAR >
1222 IBNLearner::addForbiddenArc(tail, head);
1223 return *this;
1224 }
1225
1226 template < GUM_Numeric GUM_SCALAR >
1228 std::string_view head) {
1229 IBNLearner::addForbiddenArc(tail, head);
1230 return *this;
1231 }
1232
1233 template < GUM_Numeric GUM_SCALAR >
1236 return *this;
1237 }
1238
1239 template < GUM_Numeric GUM_SCALAR >
1242 return *this;
1243 }
1244
1245 template < GUM_Numeric GUM_SCALAR >
1247 std::string_view head) {
1249 return *this;
1250 }
1251
1252 template < GUM_Numeric GUM_SCALAR >
1255 return *this;
1256 }
1257
1258 template < GUM_Numeric GUM_SCALAR >
1260 IBNLearner::addMandatoryArc(tail, head);
1261 return *this;
1262 }
1263
1264 template < GUM_Numeric GUM_SCALAR >
1266 std::string_view head) {
1267 IBNLearner::addMandatoryArc(tail, head);
1268 return *this;
1269 }
1270
1271 template < GUM_Numeric GUM_SCALAR >
1274 return *this;
1275 }
1276
1277 template < GUM_Numeric GUM_SCALAR >
1280 return *this;
1281 }
1282
1283 template < GUM_Numeric GUM_SCALAR >
1285 std::string_view head) {
1287 return *this;
1288 }
1289
1290 template < GUM_Numeric GUM_SCALAR >
1293 return *this;
1294 }
1295
1296 template < GUM_Numeric GUM_SCALAR >
1298 IBNLearner::addPossibleEdge(tail, head);
1299 return *this;
1300 }
1301
1302 template < GUM_Numeric GUM_SCALAR >
1304 std::string_view head) {
1305 IBNLearner::addPossibleEdge(tail, head);
1306 return *this;
1307 }
1308
1309 template < GUM_Numeric GUM_SCALAR >
1312 return *this;
1313 }
1314
1315 template < GUM_Numeric GUM_SCALAR >
1318 return *this;
1319 }
1320
1321 template < GUM_Numeric GUM_SCALAR >
1323 std::string_view head) {
1325 return *this;
1326 }
1327
1328 template < GUM_Numeric GUM_SCALAR >
1331 return *this;
1332 }
1333
1334 template < GUM_Numeric GUM_SCALAR >
1337 return *this;
1338 }
1339
1340 template < GUM_Numeric GUM_SCALAR >
1342 BNLearner< GUM_SCALAR >::setPossibleSkeleton(const UndiGraph& skeleton) {
1344 return *this;
1345 }
1346
1347 template < GUM_Numeric GUM_SCALAR >
1350 return *this;
1351 }
1352
1353 template < GUM_Numeric GUM_SCALAR >
1356 return *this;
1357 }
1358
1359 template < GUM_Numeric GUM_SCALAR >
1362 return *this;
1363 }
1364
1365 template < GUM_Numeric GUM_SCALAR >
1368 return *this;
1369 }
1370
1371 template < GUM_Numeric GUM_SCALAR >
1374 return *this;
1375 }
1376
1377 template < GUM_Numeric GUM_SCALAR >
1380 return *this;
1381 }
1382
1383 template < GUM_Numeric GUM_SCALAR >
1386 return *this;
1387 }
1388
1389 template < GUM_Numeric GUM_SCALAR >
1392 return *this;
1393 }
1394
1395 template < GUM_Numeric GUM_SCALAR >
1398 return *this;
1399 }
1400
1401 template < GUM_Numeric GUM_SCALAR >
1404 return *this;
1405 }
1406
1407 template < GUM_Numeric GUM_SCALAR >
1410 return *this;
1411 }
1412
1413 template < GUM_Numeric GUM_SCALAR >
1416 return *this;
1417 }
1418
1419 template < GUM_Numeric GUM_SCALAR >
1422 }
1423
1424 template < GUM_Numeric GUM_SCALAR >
1426 return IBNLearner::isScoreBased();
1427 }
1428
1429 } /* namespace learning */
1430
1431} /* namespace gum */
1432
1433#endif /* DOXYGEN_SHOULD_SKIP_THIS */
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.
Definition BayesNet.h:99
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.
Definition BNLearner.h:73
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()
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).
Definition CSVParser.h:78
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.
Definition IBNLearner.h:107
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
Definition prior.h:84
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)
Definition exceptions.h:76
std::size_t Size
In aGrUM, hashed values are unsigned long int.
Definition types.h:74
Size Idx
Type for indexes.
Definition types.h:79
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
Definition CSVParser.h:55
GUM_SHARED_PUBLIC std::ostream & operator<<(std::ostream &stream, const IdCondSet &idset)
the display operator
gum is the global namespace for all aGrUM entities
Definition agrum.h:46
Configuration & config()
A short name for Configuration::instance() : gum::config().epsilonStandard(). It is not inline so tha...