aGrUM 3.1.1
a C++ library for (probabilistic) graphical models
IBNLearner.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
52#ifndef GUM_LEARNING_GENERIC_BN_LEARNER_H
53#define GUM_LEARNING_GENERIC_BN_LEARNER_H
54
55#include <memory>
56#include <sstream>
57
58#include <agrum/agrum.h>
59
93
94namespace gum::learning {
96
105 public:
107 enum class ScoreType { AIC, BD, BDeu, BIC, fNML, K2, LOG2LIKELIHOOD, MDL };
108
111 enum class ParamEstimatorType { ML };
112
121
133
135 static constexpr double default_EM_noise{0.1};
136
138 class Database {
139 public:
140 // ########################################################################
142 // ########################################################################
144
146
156 explicit Database(std::string_view file,
157 const std::vector< std::string >& missing_symbols,
158 const bool induceTypes = false);
159
161
164 explicit Database(const DatabaseTable& db);
165
167
177 Database(std::string_view filename,
178 const Database& score_database,
179 const std::vector< std::string >& missing_symbols);
180
182
188 template < GUM_Numeric GUM_SCALAR >
189 Database(std::string_view filename,
191 const std::vector< std::string >& missing_symbols);
192
194 Database(const Database& from);
195
197 Database(Database&& from);
198
200 ~Database();
201
203
204 // ########################################################################
206 // ########################################################################
208
210 Database& operator=(const Database& from);
211
213 Database& operator=(Database&& from);
214
216
217 // ########################################################################
219 // ########################################################################
221
224
226 const std::vector< std::size_t >& domainSizes() const;
227
229 const std::vector< std::string >& names() const;
230
232 NodeId idFromName(std::string_view var_name) const;
233
235 const std::string& nameFromId(NodeId id) const;
236
238 const DatabaseTable& databaseTable() const;
239
242 void setDatabaseWeight(const double new_weight);
243
246
248 const std::vector< std::string >& missingSymbols() const;
249
251 std::size_t nbRows() const;
252
254 std::size_t size() const;
255
257
260 void setWeight(const std::size_t i, const double weight);
261
263
265 double weight(const std::size_t i) const;
266
268 double weight() const;
269
271
272 protected:
275
278
280 std::vector< std::size_t > _domain_sizes_;
281
284
287
290
291 private:
292 // returns the set of variables as a BN. This is convenient for
293 // the constructors of prior Databases
294 template < GUM_Numeric GUM_SCALAR >
295 BayesNet< GUM_SCALAR > _BNVars_() const;
296 };
297
298 // ##########################################################################
300 // ##########################################################################
302
315 IBNLearner(std::string_view filename,
316 const std::vector< std::string >& missingSymbols,
317 bool induceTypes = true);
318
319 explicit IBNLearner(const DatabaseTable& db);
320
338 template < GUM_Numeric GUM_SCALAR >
339 IBNLearner(std::string_view filename,
341 const std::vector< std::string >& missing_symbols);
342
344 IBNLearner(const IBNLearner&);
345
348
350 ~IBNLearner() override;
351
353
354 // ##########################################################################
356 // ##########################################################################
358
361
364
366
367 // ##########################################################################
369 // ##########################################################################
371
373 DAG learnDAG();
374
377 PDAG learnPDAG();
378
381 PAG learnPAG();
382
384 void setInitialDAG(const DAG&);
385
387 DAG initialDAG();
388
390 const std::vector< std::string >& names() const;
391
393 const std::vector< std::size_t >& domainSizes() const;
394 Size domainSize(NodeId var) const;
395 Size domainSize(std::string_view var) const;
396
398
402 NodeId idFromName(std::string_view var_name) const;
403
405 const DatabaseTable& database() const;
406
409 void setDatabaseWeight(const double new_weight);
410
412
415 void setRecordWeight(const std::size_t i, const double weight);
416
418
420 double recordWeight(const std::size_t i) const;
421
423 double databaseWeight() const;
424
426 const std::string& nameFromId(NodeId id) const;
427
429
435 void useDatabaseRanges(const std::vector< std::pair< std::size_t, std::size_t > >& new_ranges);
436
438 void clearDatabaseRanges();
439
441
444 const std::vector< std::pair< std::size_t, std::size_t > >& databaseRanges() const;
445
447
467 std::pair< std::size_t, std::size_t > useCrossValidationFold(const std::size_t learning_fold,
468 const std::size_t k_fold);
469
470
478 std::pair< double, double >
479 chi2(NodeId id1, NodeId id2, const std::vector< NodeId >& knowing = {});
487 std::pair< double, double > chi2(std::string_view name1,
488 std::string_view name2,
489 const std::vector< std::string >& knowing = {});
490
498 std::pair< double, double >
499 G2(NodeId id1, NodeId id2, const std::vector< NodeId >& knowing = {});
507 std::pair< double, double > G2(std::string_view name1,
508 std::string_view name2,
509 const std::vector< std::string >& knowing = {});
510
518 double logLikelihood(const std::vector< NodeId >& vars,
519 const std::vector< NodeId >& knowing = {});
520
528 double logLikelihood(const std::vector< std::string >& vars,
529 const std::vector< std::string >& knowing = {});
530
542 double mutualInformation(NodeId id1, NodeId id2, const std::vector< NodeId >& knowing = {});
543
555 double mutualInformation(std::string_view var1,
556 std::string_view var2,
557 const std::vector< std::string >& knowing = {});
558
559
573 NodeId id2,
574 const std::vector< NodeId >& knowing = {});
575
590 double correctedMutualInformation(std::string_view var1,
591 std::string_view var2,
592 const std::vector< std::string >& knowing = {});
593
602 double score(NodeId vars, const std::vector< NodeId >& knowing = {});
603
613 double score(std::string_view vars, const std::vector< std::string >& knowing = {});
614
620 std::vector< double > rawPseudoCount(const std::vector< NodeId >& vars);
621
627 std::vector< double > rawPseudoCount(const std::vector< std::string >& vars);
632 Size nbCols() const;
633
638 Size nbRows() const;
639
657 void useEM(const double epsilon, const double noise = default_EM_noise);
658
673 void useEMWithRateCriterion(const double epsilon, const double noise = default_EM_noise);
674
688 void useEMWithDiffCriterion(const double epsilon, const double noise = default_EM_noise);
689
691 void forbidEM();
692
694 bool isUsingEM() const;
695
705 EMApproximationScheme& EM();
706
709
711 std::string EMStateMessage() const;
712
714 bool hasMissingValues() const;
715
717
718 // ##########################################################################
720 // ##########################################################################
722
724 void useScoreAIC();
725
727 void useScoreBD();
728
730 void useScoreBDeu();
731
733 void useScoreBIC();
734
736 void useScorefNML();
737
739 void useScoreK2();
740
743
745 void useScoreMDL();
746
748
749 // ##########################################################################
751 // ##########################################################################
753
755 void useNoPrior();
756
758
761 void useBDeuPrior(double weight = 1.0);
762
764
767 void useSmoothingPrior(double weight = 1);
768
770 void useDirichletPrior(std::string_view filename, double weight = 1);
771
773
775 std::string checkScorePriorCompatibility() const;
777
778 // ##########################################################################
780 // ##########################################################################
782
785
787
800
802
805 void useLocalSearchWithTabuList(Size tabu_size = 100, Size nb_decrease = 2);
806
808 void useK2(const Sequence< NodeId >& order);
809
811 void useK2(const std::vector< NodeId >& order);
812
814 void useMIIC();
815
817 void usePC();
818
820 void useFCI();
821
824
826 void setGreedyThickThinningReversals(bool allow);
827
829 bool greedyThickThinningReversals() const;
830
832 bool isConstraintBased() const;
833
835 bool isScoreBased() const;
836
837 // ##########################################################################
839 // ##########################################################################
841
846 void allowArcAdditions(bool allow = true);
847
856 void allowArcDeletions(bool allow = true);
857
864 void allowArcReversals(bool allow = true);
865
871 void allowArcTriangleDeletions(bool allow = true);
872
874
875 // ##########################################################################
877 // ##########################################################################
881 void useNMLCorrection();
884 void useMDLCorrection();
887 void useNoCorrection();
888
891 std::vector< Arc > latentVariables() const;
892
894
895 // ##########################################################################
897 // ##########################################################################
899
902 void useChi2Test();
903
906 void useG2Test();
907
910 void setPCAlpha(double alpha);
911
914 void setPCStable(bool stable);
915
918 void setPCMaxCondSetSize(Size max_k);
919
923 void setPCUnshieldedColliderSorted(bool sorted);
924
926
927 // ##########################################################################
929 // ##########################################################################
931
934 void useFCIChi2Test();
935
938 void useFCIG2Test();
939
942 void setFCIAlpha(double alpha);
943
946 void setFCIMaxPathLength(Size max_len);
947
950 void setFCIExhaustiveSepSet(bool exhaustive);
951
954 bool fciExhaustiveSepSet() const;
955
957
958 // ##########################################################################
960 // ##########################################################################
962
964 void setMaxIndegree(Size max_indegree);
965
971 void setSliceOrder(const NodeProperty< NodeId >& slice_order);
972
979 void setSliceOrder(const std::vector< std::vector< std::string > >& slices);
980
986 void unsetSliceOrder();
987
1005 void setTotalOrder(const Sequence< NodeId >& order);
1006 void setTotalOrder(const std::vector< std::string >& order);
1008
1010 void unsetTotalOrder();
1011
1013
1015 void setForbiddenArcs(const ArcSet& set);
1016
1019 void addForbiddenArc(const Arc& arc);
1020 void addForbiddenArc(NodeId tail, NodeId head);
1021 void addForbiddenArc(std::string_view tail, std::string_view head);
1023
1026 void eraseForbiddenArc(const Arc& arc);
1027 void eraseForbiddenArc(NodeId tail, NodeId head);
1028 void eraseForbiddenArc(std::string_view tail, std::string_view head);
1030
1032 void setMandatoryArcs(const ArcSet& set);
1033
1036 void addMandatoryArc(const Arc& arc);
1037 void addMandatoryArc(NodeId tail, NodeId head);
1038 void addMandatoryArc(std::string_view tail, std::string_view head);
1040
1043 void eraseMandatoryArc(const Arc& arc);
1044 void eraseMandatoryArc(NodeId tail, NodeId head);
1045 void eraseMandatoryArc(std::string_view tail, std::string_view head);
1047
1050 void addNoParentNode(NodeId node);
1051 void addNoParentNode(std::string_view node);
1053
1056 void eraseNoParentNode(NodeId node);
1057 void eraseNoParentNode(std::string_view node);
1058
1061 void addNoChildrenNode(NodeId node);
1062 void addNoChildrenNode(std::string_view node);
1064
1067 void eraseNoChildrenNode(NodeId node);
1068 void eraseNoChildrenNode(std::string_view node);
1070
1075 void setPossibleEdges(const EdgeSet& set);
1076 void setPossibleSkeleton(const UndiGraph& skeleton);
1078
1083 void addPossibleEdge(const Edge& edge);
1084 void addPossibleEdge(NodeId tail, NodeId head);
1085 void addPossibleEdge(std::string_view tail, std::string_view head);
1087
1090 void erasePossibleEdge(const Edge& edge);
1091 void erasePossibleEdge(NodeId tail, NodeId head);
1092 void erasePossibleEdge(std::string_view tail, std::string_view head);
1094
1096
1097 // ##########################################################################
1099 // ##########################################################################
1101
1103
1107 void setNumberOfThreads(Size nb) override;
1108
1110
1111 protected:
1112 PAG learnPAG_();
1113 PDAG learnPDAG_();
1114
1116 void _setPriorWeight_(double weight);
1117
1119 bool inducedTypes_{false};
1120
1123
1125 Score* score_{nullptr};
1126
1129
1131 bool useEM_{false};
1132
1134 double noiseEM_{0.1};
1135
1138
1141
1143 Prior* prior_{nullptr};
1144
1146
1148 double priorWeight_{1.0f};
1149
1152
1155
1158
1161
1164
1167
1170
1173
1176
1179
1182
1185
1188
1191
1194
1197
1200
1204
1207
1209 enum class IndepTestType { Chi2, G2 };
1211
1214
1216 double alphaPc_{0.05};
1217 bool stablePc_{true};
1219 bool sortedUCPc_{false};
1220
1223
1226
1229
1231 double alphaFci_{0.05};
1234
1237
1240
1243
1246
1249
1252
1254 std::vector< std::pair< std::size_t, std::size_t > > ranges_;
1255
1258
1260 std::string priorDbname_;
1261
1264
1266 std::string filename_{"-"};
1267
1268 // size of the tabu list
1270
1271 // the current algorithm as an approximationScheme
1273
1275 static DatabaseTable readFile_(std::string_view filename,
1276 const std::vector< std::string >& missing_symbols);
1277
1279 static void isCSVFileName_(std::string_view filename);
1280
1282 virtual void createPrior_() = 0;
1283
1285 void createScore_();
1286
1289 bool take_into_account_score = true);
1290
1292 DAG learnDag_();
1293
1296
1299
1302
1305
1307 PriorType getPriorType_() const;
1308
1311
1312 public:
1313 // ##########################################################################
1316 // ##########################################################################
1317 // in order to not pollute the proper code of IBNLearner, we
1318 // directly
1319 // implement those
1320 // very simples methods here.
1322 void setCurrentApproximationScheme(const ApproximationScheme* approximationScheme);
1323
1324 void distributeProgress(const ApproximationScheme* approximationScheme,
1325 Size pourcent,
1326 double error,
1327 double time);
1328
1330 void distributeStop(const ApproximationScheme* approximationScheme, std::string_view message);
1331
1333
1338 void setEpsilon(double eps) override;
1339
1341 double epsilon() const override;
1342
1344 void disableEpsilon() override;
1345
1347 void enableEpsilon() override;
1348
1351 bool isEnabledEpsilon() const override;
1352
1354
1360 void setMinEpsilonRate(double rate) override;
1361
1363 double minEpsilonRate() const override;
1364
1366 void disableMinEpsilonRate() override;
1367
1369 void enableMinEpsilonRate() override;
1370
1373 bool isEnabledMinEpsilonRate() const override;
1374
1376
1382 void setMaxIter(Size max) override;
1383
1385 Size maxIter() const override;
1386
1388 void disableMaxIter() override;
1389
1391 void enableMaxIter() override;
1392
1395 bool isEnabledMaxIter() const override;
1396
1398
1403
1405 void setMaxTime(double timeout) override;
1406
1408 double maxTime() const override;
1409
1411 double currentTime() const override;
1412
1414 void disableMaxTime() override;
1415
1416 void enableMaxTime() override;
1417
1420 bool isEnabledMaxTime() const override;
1421
1423
1427 void setPeriodSize(Size p) override;
1428
1429 Size periodSize() const override;
1430
1432
1435 void setVerbosity(bool v) override;
1436
1437 bool verbosity() const override;
1438
1440
1443
1445
1447 Size nbrIterations() const override;
1448
1450 const std::vector< double >& history() const override;
1451
1453
1454
1457
1465 void EMsetEpsilon(double eps);
1466
1468
1473 double EMEpsilon() const;
1474
1476 void EMdisableEpsilon();
1477
1482 void EMenableEpsilon();
1483
1485 bool EMisEnabledEpsilon() const;
1486
1493 void EMsetMinEpsilonRate(double rate);
1494
1500 double EMMinEpsilonRate() const;
1501
1504
1510
1512 bool EMisEnabledMinEpsilonRate() const;
1513
1519 void EMsetMaxIter(Size max);
1520
1526 Size EMMaxIter() const;
1527
1529 void EMdisableMaxIter();
1530
1532 void EMenableMaxIter();
1533
1536 bool EMisEnabledMaxIter() const;
1537
1543 void EMsetMaxTime(double timeout);
1544
1550 double EMMaxTime() const;
1551
1553 double EMCurrentTime() const;
1554
1556 void EMdisableMaxTime();
1557
1558 void EMenableMaxTime();
1559
1561 bool EMisEnabledMaxTime() const;
1562
1567 void EMsetPeriodSize(Size p);
1568
1569 Size EMPeriodSize() const;
1570
1572 void EMsetVerbosity(bool v);
1573
1575 bool EMVerbosity() const;
1576
1579
1581 Size EMnbrIterations() const;
1582
1587 const std::vector< double >& EMHistory() const;
1588
1590 };
1591
1592 /* namespace learning */
1593} // namespace gum::learning
1594
1596#ifndef GUM_NO_INLINE
1598#endif /* GUM_NO_INLINE */
1599
1601
1602#endif /* GUM_LEARNING_GENERIC_BN_LEARNER_H */
A class that, given a structure and a parameter estimator returns a full Bayes net.
The class for initializing DatabaseTable and RawDatabaseTable instances from CSV files.
A DBRowGenerator class that returns the rows that are complete (fully observed) w....
A DBRowGenerator class that returns incomplete rows as EM would do.
A dirichlet priori: computes its N'_ijk from a database.
FCI (Fast Causal Inference) causal discovery algorithm.
A pack of learning algorithms that can easily be used.
The K2 algorithm.
PC (Peter-Clark) constraint-based structure learning algorithm.
The SimpleMiic algorithm.
Class representing a Bayesian network.
Definition BayesNet.h:99
Static math utilities for the chi2 distribution.
Definition chi2.h:73
Base class for dag.
Definition DAG.h:121
ApproximationSchemeSTATE
The different state of an approximation scheme.
Base class for mixed graphs.
Definition mixedGraph.h:146
Partial Ancestral Graph: undirected topology with endpoint marks.
Definition PAG.h:90
Base class for partially directed acyclic graphs.
Definition PDAG.h:130
ThreadNumberManager(Size nb_threads=0)
default constructor
A class that redirects gum_signal from algorithms to the listeners of BNLearn.
The class computing n times the corrected mutual information, as used in the MIIC algorithm.
KModeTypes
the description type for the complexity correction
A class that, given a structure and a parameter estimator returns a full Bayes net.
the class used to read a row in the database and to transform it into a set of DBRow instances that c...
The class representing a tabular database as used by learning tasks.
Fast Causal Inference — PAG learning via constraint-based methods.
Definition FCI.h:79
The greedy hill climbing learning algorithm (for directed graphs).
The greedy thick-thinning learning algorithm (for directed graphs).
a helper to easily read databases
Definition IBNLearner.h:138
const std::vector< std::string > & missingSymbols() const
returns the set of missing symbols taken into account
const DatabaseTable & databaseTable() const
returns the internal database table
Size _min_nb_rows_per_thread_
the minimal number of rows to parse (on average) by thread
Definition IBNLearner.h:289
std::size_t size() const
returns the number of records in the database
std::vector< std::size_t > _domain_sizes_
the domain sizes of the variables (useful to speed-up computations)
Definition IBNLearner.h:280
Database(std::string_view filename, const gum::BayesNet< GUM_SCALAR > &bn, const std::vector< std::string > &missing_symbols)
constructor with a BN providing the variables of interest
DatabaseTable _database_
the database itself
Definition IBNLearner.h:274
const std::string & nameFromId(NodeId id) const
returns the variable name corresponding to a given node id
double weight(const std::size_t i) const
returns the weight of the ith record
Bijection< NodeId, std::size_t > _nodeId2cols_
a bijection assigning to each variable name its NodeId
Definition IBNLearner.h:283
Database(std::string_view file, const std::vector< std::string > &missing_symbols, const bool induceTypes=false)
default constructor
const std::vector< std::string > & names() const
returns the names of the variables in the database
void setWeight(const std::size_t i, const double weight)
sets the weight of the ith record
const Bijection< NodeId, std::size_t > & nodeId2Columns() const
returns the mapping between node ids and their columns in the database
Database & operator=(const Database &from)
copy operator
DBRowGeneratorParser & parser()
returns the parser for the database
DBRowGeneratorParser * _parser_
the parser used for reading the database
Definition IBNLearner.h:277
NodeId idFromName(std::string_view var_name) const
returns the node id corresponding to a variable name
void setDatabaseWeight(const double new_weight)
assign a weight to all the rows of the database so that the sum of their weights is equal to new_weig...
BayesNet< GUM_SCALAR > _BNVars_() const
Size _max_threads_number_
the max number of threads authorized
Definition IBNLearner.h:286
std::size_t nbRows() const
returns the number of records in the database
const std::vector< std::size_t > & domainSizes() const
returns the domain sizes of the variables
double weight() const
returns the weight of the whole database
A pack of learning algorithms that can easily be used.
Definition IBNLearner.h:104
void usePC()
indicate that we wish to use PC (Chi2 test by default)
StructuralConstraintPossibleEdges constraintPossibleEdges_
the constraint on possible Edges
MixedGraph preparePC_()
prepares the initial graph and independence test for PC
StructuralConstraintNoParentNodes constraintNoParentNodes_
the constraint on no parent nodes
Size periodSize() const override
how many samples between 2 stopping isEnableds
void eraseNoChildrenNode(NodeId node)
double recordWeight(const std::size_t i) const
returns the weight of the ith record
BNLearnerPriorType priorType_
the a priorselected for the score and parameters
void EMenableEpsilon()
Enable the log-likelihood min diff stopping criterion in EM.
bool EMisEnabledEpsilon() const
return true if EM's stopping criterion is the log-likelihood min diff
void EMsetPeriodSize(Size p)
how many samples between 2 stoppings isEnabled
const std::vector< std::size_t > & domainSizes() const
returns the domain sizes of the variables in the database
Size nbrIterations() const override
void setMinEpsilonRate(double rate) override
Given that we approximate f(t), stopping criterion on d/dt(|f(t+1)-f(t)|) If the criterion was disabl...
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)
PAG learnPAG()
learn a PAG — only valid when useFCI() has been called
Size EMnbrIterations() const
returns the number of iterations performed by the last EM execution
void enableMaxTime() override
stopping criterion on timeout If the criterion was disabled it will be enabled
void setSliceOrder(const NodeProperty< NodeId > &slice_order)
sets a partial order on the nodes
bool isUsingEM() const
indicates whether we use EM for parameter learning
bool isScoreBased() const
indicate if the selected algorithm is score-based
void setForbiddenArcs(const ArcSet &set)
removes a total
std::string priorDbname_
the filename for the Dirichlet a priori, if any
IndepTestType
independence test type for PC
double priorWeight_
the weight of the prior
void enableEpsilon() override
Enable stopping criterion on epsilon.
double maxTime() const override
returns the timeout (in seconds)
double noiseEM_
the noise factor (in (0,1)) used by EM for perturbing the CPT during init
std::vector< std::pair< std::size_t, std::size_t > > ranges_
the set of rows' ranges within the database in which learning is done
void setDatabaseWeight(const double new_weight)
assign a weight to all the rows of the learning database so that the sum of their weights is equal to...
std::vector< Arc > latentVariables() const
get the list of arcs hiding latent variables
void useFCIChi2Test()
indicate that we wish to use Chi2 independence test for FCI
void clearDatabaseRanges()
reset the ranges to the one range corresponding to the whole database
~IBNLearner() override
destructor
std::string checkScorePriorCompatibility() const
checks whether the current score and prior are compatible
void useBDeuPrior(double weight=1.0)
use the BDeu prior
void setMandatoryArcs(const ArcSet &set)
assign a set of mandatory arcs
GreedyHillClimbing extendedGreedyHillClimbing_
the extended greedy hill climbing
ParamEstimatorType
an enumeration to select the type of parameter estimation we shall apply
Definition IBNLearner.h:111
bool greedyThickThinningReversals() const
returns whether arc reversals are allowed in the thin phase of greedy thick-thinning
AlgoType
an enumeration to select easily the learning algorithm to use
Definition IBNLearner.h:123
ApproximationSchemeSTATE EMState() const
returns the state of the last EM algorithm executed
void distributeStop(const ApproximationScheme *approximationScheme, std::string_view message)
distribute signals
bool allowArcTriangleDeletions_
whether we allow or not arc deletions during learning
void EMdisableMinEpsilonRate()
Disable the log-likelihood evolution rate stopping criterion.
void useExtendedGreedyHillClimbing()
indicate that we wish to use the extended greedy hill climbing algorithm
double EMMaxTime() const
@brief returns EM's timeout (in milliseconds)
virtual void createPrior_()=0
create the prior used for learning
void setFCIMaxPathLength(Size max_len)
set maximum discriminating-path length for FCI R4 (default Size(-1) = unlimited)
ApproximationSchemeSTATE EMStateApproximationScheme() const
get the current state of EM
const std::string & nameFromId(NodeId id) const
returns the variable name corresponding to a given node id
double databaseWeight() const
returns the weight of the whole database
const std::vector< double > & history() const override
void setMaxIter(Size max) override
stopping criterion on number of iterationsIf the criterion was disabled it will be enabled
K2 algoK2_
the K2 algorithm
IndepTestType indepTestTypeFCI_
independence test type for FCI (reuses IndepTestType defined above)
void addMandatoryArc(const Arc &arc)
AlgoType selectedAlgo_
the selected learning algorithm
const std::vector< std::pair< std::size_t, std::size_t > > & databaseRanges() const
returns the current database rows' ranges used for learning
void EMenableMaxIter()
Enable stopping criterion on max iterations.
void useFCI()
indicate that we wish to use FCI (Chi2 test by default)
void enableMinEpsilonRate() override
Enable stopping criterion on epsilon rate.
bool allowArcAdditions_
whether we allow or not arc additions during learning
void useFCIG2Test()
indicate that we wish to use G2 independence test for FCI
void setEpsilon(double eps) override
Given that we approximate f(t), stopping criterion on |f(t+1)-f(t)| If the criterion was disabled it ...
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)
bool isEnabledMaxIter() const override
void EMsetMaxIter(Size max)
add a max iteration stopping criterion
void useChi2Test()
indicate that we wish to use Chi2 independence test for PC
double logLikelihood(const std::vector< NodeId > &vars, const std::vector< NodeId > &knowing={})
Return the loglikelihood of vars in the base, conditioned by knowing for the BNLearner.
void setInitialDAG(const DAG &)
sets an initial DAG structure
void useK2(const Sequence< NodeId > &order)
indicate that we wish to use K2
Database scoreDatabase_
the database to be used by the scores and parameter estimators
void allowArcDeletions(bool allow=true)
allow (true)/forbid (false) to delete arcs during learning.
void setMaxTime(double timeout) override
stopping criterion on timeout If the criterion was disabled it will be enabled
double epsilon() const override
Get the value of epsilon.
ScoreType
an enumeration enabling to select easily the score we wish to use
Definition IBNLearner.h:107
double EMEpsilon() const
Get the value of EM's min diff epsilon.
bool useEM_
a Boolean indicating whether we should use EM for parameter learning or not
DAG2BNLearner dag2BN_
the parametric EM
Prior * prior_
the prior used
void EMsetMinEpsilonRate(double rate)
sets the stopping criterion of EM as being the minimal log-likelihood's evolution rate
bool isEnabledMaxTime() const override
void useDatabaseRanges(const std::vector< std::pair< std::size_t, std::size_t > > &new_ranges)
use a new set of database rows' ranges to perform learning
std::pair< double, double > chi2(NodeId id1, NodeId id2, const std::vector< NodeId > &knowing={})
Return the <statistic,pvalue> pair for chi2 test in the database.
double EMMinEpsilonRate() const
Get the value of the minimal log-likelihood evolution rate of EM.
void distributeProgress(const ApproximationScheme *approximationScheme, Size pourcent, double error, double time)
{@ /// distribute signals
void setGreedyThickThinningReversals(bool allow)
enable or disable arc reversals in the thin phase of greedy thick-thinning
void setPeriodSize(Size p) override
how many samples between 2 stopping isEnableds
Size EMMaxIter() const
return the max number of iterations criterion
CorrectedMutualInformation * mutualInfo_
the selected correction for miic
void disableMinEpsilonRate() override
Disable stopping criterion on epsilon rate.
void EMdisableMaxIter()
Disable stopping criterion on max iterations.
BNLearnerPriorType
an enumeration to select the prior
Definition IBNLearner.h:114
bool isEnabledMinEpsilonRate() const override
void erasePossibleEdge(const Edge &edge)
void setNumberOfThreads(Size nb) override
sets the number max of threads that can be used
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.
const std::vector< double > & EMHistory() const
returns the history of the last EM execution
StructuralConstraintNoChildrenNodes constraintNoChildrenNodes_
the constraint on no children nodes
DAG initialDAG()
returns the initial DAG structure
static void isCSVFileName_(std::string_view filename)
checks whether the extension of a CSV filename is correct
gum::learning::FCI algoFCI_
the FCI algorithm
void EMsetVerbosity(bool v)
sets or unsets EM's verbosity
void setPossibleEdges(const EdgeSet &set)
assign a set of possible edges
Size maxIter() const override
void useNoPrior()
use no prior
ParamEstimatorType paramEstimatorType_
the type of the parameter estimator
ScoreType scoreType_
the score selected for learning
bool EMVerbosity() const
returns the EM's verbosity status
std::pair< double, double > G2(NodeId id1, NodeId id2, const std::vector< NodeId > &knowing={})
Return the <statistic,pvalue> pair for for G2 test in the database.
const ApproximationScheme * currentAlgorithm_
IndependenceTest * indepTestPC_
owned independence test object for PC (rebuilt before each learn call)
void eraseForbiddenArc(const Arc &arc)
void useSmoothingPrior(double weight=1)
use the prior smoothing
bool isEnabledEpsilon() const override
DAG learnDag_()
returns the DAG learnt
Database * priorDatabase_
the database used by the Dirichlet a priori
double mutualInformation(NodeId id1, NodeId id2, const std::vector< NodeId > &knowing={})
Return the mutual information of id1 and id2 in the base, conditioned by knowing for the BNLearner.
void createScore_()
create the score used for learning
PriorType getPriorType_() const
returns the type (as a string) of a given prior
void allowArcAdditions(bool allow=true)
allow (true)/forbid (false) to add arcs during learning.
double alphaFci_
FCI parameters.
void useLocalSearchWithTabuList(Size tabu_size=100, Size nb_decrease=2)
indicate that we wish to use a local search with tabu list
void useScoreK2()
indicate that we wish to use a K2 score
double alphaPc_
PC parameters.
StructuralConstraintIndegree constraintIndegree_
the constraint for indegrees
bool allowArcDeletions_
whether we allow or not arc deletions during learning
PDAG learnPDAG()
learn a partial structure from a file (must have read the db before and must have selected miic)
void _setPriorWeight_(double weight)
sets the prior weight
bool verbosity() const override
verbosity
static DatabaseTable readFile_(std::string_view filename, const std::vector< std::string > &missing_symbols)
reads a file and returns a databaseVectInRam
void useGreedyThickThinning()
indicate that we wish to use greedy thick-thinning
void disableMaxTime() override
Disable stopping criterion on timeout.
double currentTime() const override
get the current running time in second (double)
void disableEpsilon() override
Disable stopping criterion on epsilon.
std::string filename_
the filename database
void disableMaxIter() override
Disable stopping criterion on max iterations.
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 useEMWithRateCriterion(const double epsilon, const double noise=default_EM_noise)
use The EM algorithm to learn parameters with the rate stopping criterion
void useNMLCorrection()
indicate that we wish to use the NML correction for and MIIC
void useEM(const double epsilon, const double noise=default_EM_noise)
use The EM algorithm to learn parameters
void useEMWithDiffCriterion(const double epsilon, const double noise=default_EM_noise)
use The EM algorithm to learn parameters with the diff stopping criterion
bool hasMissingValues() const
returns true if the learner's database has missing values
void forbidEM()
prevent using the EM algorithm for parameter learning
NodeId idFromName(std::string_view var_name) const
returns the node id corresponding to a variable name
SimpleMiic algoSimpleMiic_
the MIIC algorithm
Score * score_
the score used
void setPCMaxCondSetSize(Size max_k)
set maximum conditioning set size for PC (default Size(-1) = unlimited)
StructuralConstraintMandatoryArcs constraintMandatoryArcs_
the constraint on mandatory arcs
Miic algoMiic_
the Constraint MIIC algorithm
void unsetSliceOrder()
removes the slice order constraint
void EMenableMaxTime()
sets the stopping criterion of EM as being the minimal difference between two consecutive log-likelih...
void createCorrectedMutualInformation_()
create the Corrected Mutual Information instance for Miic
EMApproximationScheme & EM()
returns the EM parameter learning approximation scheme if EM is enabled
IndepTestType indepTestTypePC_
void useNoCorrection()
indicate that we wish to use the NoCorr correction for MIIC
StructuralConstraintForbiddenArcs constraintForbiddenArcs_
the constraint on forbidden arcs
StructuralConstraintTotalOrder constraintTotalOrder_
the total order ing constraint
void useScoreLog2Likelihood()
indicate that we wish to use a Log2Likelihood score
void setRecordWeight(const std::size_t i, const double weight)
sets the weight of the ith record of the database
void useDirichletPrior(std::string_view filename, double weight=1)
use the Dirichlet prior from a database
void unsetTotalOrder()
removes the current total ordering constraint, if any
GreedyHillClimbing greedyHillClimbing_
the greedy hill climbing algorithm
DAG learnDAG()
learn a structure from a file (must have read the db before)
void useMDLCorrection()
indicate that we wish to use the MDL correction for MIIC
void setFCIAlpha(double alpha)
set the significance threshold alpha for FCI (default 0.05)
bool fciExhaustiveSepSet() const
return true when FCI uses exhaustive sepset mode
void setPCAlpha(double alpha)
set the significance threshold alpha for PC (default 0.05)
void setVerbosity(bool v) override
verbosity
double score(NodeId vars, const std::vector< NodeId > &knowing={})
Return the value of the score currently in use by the BNLearner of a variable given a set of other va...
StructuralConstraintTabuList constraintTabuList_
the constraint for tabu lists
void addForbiddenArc(const Arc &arc)
DAG initialDag_
an initial DAG given to learners
void addNoChildrenNode(NodeId node)
GreedyThickThinning greedyThickThinning_
the greedy thick-thinning algorithm
void EMsetMaxTime(double timeout)
add a stopping criterion on timeout
MixedGraph prepareFCI_()
prepares the initial graph and independence test for FCI
ApproximationSchemeSTATE stateApproximationScheme() const override
history
IBNLearner & operator=(const IBNLearner &)
copy operator
MixedGraph prepareSimpleMiic_()
prepares the initial graph for Simple Miic
gum::learning::PC algoPC_
the PC algorithm
void EMenableMinEpsilonRate()
Enable the log-likelihood evolution rate stopping criterion.
void useScoreMDL()
indicate that we wish to use a MDL score
void setFCIExhaustiveSepSet(bool exhaustive)
enable exhaustive sepset mode for FCI skeleton learning (default false)
Size domainSize(NodeId var) const
learn a structure from a file (must have read the db before)
void useScorefNML()
indicate that we wish to use a fNML score
void setTotalOrder(const Sequence< NodeId > &order)
sets a total order over some nodes
void useScoreAIC()
indicate that we wish to use an AIC score
bool allowArcReversals_
whether we allow or not arc reversals during learning
const std::vector< std::string > & names() const
returns the names of the variables in the database
Size EMPeriodSize() const
sets the stopping criterion of EM as being the minimal difference between two consecutive log-likelih...
void eraseMandatoryArc(const Arc &arc)
double EMCurrentTime() const
get the current running time in second (double)
MixedGraph prepareMiic_()
prepares the initial graph for miic
IBNLearner(std::string_view filename, const std::vector< std::string > &missingSymbols, bool induceTypes=true)
read the database file for the score / parameter estimation and var names
void allowArcReversals(bool allow=true)
allow (true)/forbid (false) to reverse arcs during learning.
void useMIIC()
indicate that we wish to use MIIC
LocalSearchWithTabuList localSearchWithTabuList_
the local search with tabu list algorithm
IndependenceTest * indepTestFCI_
owned independence test object for FCI (rebuilt before each learn call)
std::pair< std::size_t, std::size_t > useCrossValidationFold(const std::size_t learning_fold, const std::size_t k_fold)
sets the ranges of rows to be used for cross-validation learning
void setCurrentApproximationScheme(const ApproximationScheme *approximationScheme)
{@ /// distribute signals
ParamEstimator * createParamEstimator_(const DBRowGeneratorParser &parser, bool take_into_account_score=true)
create the parameter estimator used for learning
StructuralConstraintSliceOrder constraintSliceOrder_
the constraint for 2TBNs
const DatabaseTable & database() const
returns the database used by the BNLearner
bool EMisEnabledMinEpsilonRate() const
static constexpr double default_EM_noise
the default noise amount added to CPTs during EM's initialization (see method useEM())
Definition IBNLearner.h:135
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...
std::vector< double > rawPseudoCount(const std::vector< NodeId > &vars)
Return the pseudo-counts of NodeIds vars in the base in a raw array.
void enableMaxIter() override
Enable stopping criterion on max iterations.
void setPCStable(bool stable)
set stable mode for PC — defer removals to end of each depth level (default true)
bool inducedTypes_
the policy for typing variables
CorrectedMutualInformation::KModeTypes kmodeMiic_
the penalty used in MIIC
double minEpsilonRate() const override
Get the value of the minimal epsilon rate.
double correctedMutualInformation(NodeId id1, NodeId id2, const std::vector< NodeId > &knowing={})
Return the mutual information of id1 and id2 in the base, conditioned by knowing for the BNLearner.
void useScoreBD()
indicate that we wish to use a BD score
bool isConstraintBased() const
indicate if the selected algorithm is constraint-based
std::string EMStateMessage() const
returns the state of the EM algorithm
The base class for all the independence tests used for learning.
The K2 algorithm.
Definition K2.h:63
The local search with tabu list learning algorithm (for directed graphs).
The MIIC learning algorithm.
Definition Miic.h:100
the no a priorclass: corresponds to 0 weight-sample
Definition noPrior.h:65
PC (Peter-Clark) constraint-based structure learning algorithm.
Definition PC.h:74
The base class for estimating parameters of CPTs.
the base class for all a priori
Definition prior.h:81
The base class for all the scores used for learning (BIC, BDeu, etc).
Definition score.h:68
The miic learning algorithm.
Definition SimpleMiic.h:83
the structural constraint for forbidding the creation of some arcs during structure learning
the class for structural constraints limiting the number of parents of nodes in a directed graph
the structural constraint indicating that some arcs shall never be removed or reversed
the structural constraint for forbidding children for some nodes
the structural constraint for forbidding parents for some nodes
the structural constraint for forbidding the creation of some arcs except those defined in the class ...
the structural constraint imposing a partial order over nodes
The class imposing a N-sized tabu list as a structural constraints for learning algorithms.
the structural constraint imposing a total order over some nodes
Class building the essential Graph from a DAGmodel.
The basic class for computing the set of digraph changes allowed by the user to be executed by the le...
The basic class for computing the set of digraph changes allowed by the user to be executed by the le...
The mecanism to compute the next available graph changes for directed structure learning search algor...
The greedy thick-thinning learning algorithm (for directed graphs).
std::size_t Size
In aGrUM, hashed values are unsigned long int.
Definition types.h:74
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.
the class for computing Chi2 scores
the class for computing G2 scores
The local search learning with tabu list algorithm (for directed graphs).
include the inlined functions if necessary
Definition CSVParser.h:55
unsigned int getNumberOfThreads()
returns the max number of threads used by default when entering the next parallel region
the class for estimating parameters of CPTs using Maximum Likelihood
the class for computing AIC scores
the class for computing Bayesian Dirichlet (BD) log2 scores
the class for computing BDeu scores
the class for computing K2 scores (actually their log2 value)
the class for computing fNML scores
the base class for structural constraints imposed by DAGs
the structural constraint for forbidding the creation of some arcs during structure learning
the class for structural constraints limiting the number of parents of nodes in a directed graph
the structural constraint indicating that some arcs shall never be removed or reversed
the structural constraint for forbidding children for some nodes during structure learning
the structural constraint for forbidding parents for some nodes during structure learning
the structural constraint for forbidding the creation of some arcs during structure learning
the structural constraint imposing a partial order over nodes
the class imposing a N-sized tabu list as a structural constraints for learning algorithms
the structural constraint imposing a total ordering over some nodes