aGrUM 3.3.2
a C++ library for (probabilistic) graphical models
IBNLearner_inl.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
53// to help IDE parser
57
58namespace gum::learning {
59
60
61 // returns the row filter
63
64 // returns the modalities of the variables
65 INLINE const std::vector< std::size_t >& IBNLearner::Database::domainSizes() const {
66 return _domain_sizes_;
67 }
68
69 // returns the names of the variables in the database
70 INLINE const std::vector< std::string >& IBNLearner::Database::names() const {
71 return _database_.variableNames();
72 }
73
75 INLINE void IBNLearner::Database::setDatabaseWeight(const double new_weight) {
76 if (_database_.nbRows() == std::size_t(0)) return;
77 const double weight = new_weight / double(_database_.nbRows());
78 _database_.setAllRowsWeight(weight);
79 }
80
81 // returns the node id corresponding to a variable name
82 INLINE NodeId IBNLearner::Database::idFromName(std::string_view var_name) const {
83 try {
84 const auto cols = _database_.columnsFromVariableName(var_name);
85 return _nodeId2cols_.first(cols[0]);
86 } catch (...) {
88 "Variable " << var_name << " could not be found in the database")
89 }
90 }
91
92 // returns the variable name corresponding to a given node id
93 INLINE const std::string& IBNLearner::Database::nameFromId(NodeId id) const {
94 try {
95 return _database_.variableName(_nodeId2cols_.second(id));
96 } catch (...) {
98 "Variable of Id " << id << " could not be found in the database")
99 }
100 }
101
104
106 INLINE const std::vector< std::string >& IBNLearner::Database::missingSymbols() const {
107 return _database_.missingSymbols();
108 }
109
114
116 INLINE std::size_t IBNLearner::Database::nbRows() const { return _database_.nbRows(); }
117
119 INLINE std::size_t IBNLearner::Database::size() const { return _database_.size(); }
120
122 INLINE void IBNLearner::Database::setWeight(const std::size_t i, const double weight) {
123 _database_.setWeight(i, weight);
124 }
125
127 INLINE double IBNLearner::Database::weight(const std::size_t i) const {
128 return _database_.weight(i);
129 }
130
132 INLINE double IBNLearner::Database::weight() const { return _database_.weight(); }
133
134 // ===========================================================================
135
136 // returns the node id corresponding to a variable name
137 INLINE NodeId IBNLearner::idFromName(std::string_view var_name) const {
138 return scoreDatabase_.idFromName(var_name);
139 }
140
141 // returns the variable name corresponding to a given node id
142 INLINE const std::string& IBNLearner::nameFromId(NodeId id) const {
143 return scoreDatabase_.nameFromId(id);
144 }
145
147 INLINE void IBNLearner::setDatabaseWeight(const double new_weight) {
149 }
150
152 INLINE void IBNLearner::setRecordWeight(const std::size_t i, const double new_weight) {
153 scoreDatabase_.setWeight(i, new_weight);
154 }
155
157 INLINE double IBNLearner::recordWeight(const std::size_t i) const {
158 return scoreDatabase_.weight(i);
159 }
160
162 INLINE double IBNLearner::databaseWeight() const { return scoreDatabase_.weight(); }
163
164 // sets an initial DAG structure
165 INLINE void IBNLearner::setInitialDAG(const DAG& dag) { initialDag_ = dag; }
166
168
169 // indicate that we wish to use an AIC score
174
175 // indicate that we wish to use a BD score
180
181 // indicate that we wish to use a BDeu score
186
187 // indicate that we wish to use a BIC score
192
193 // indicate that we wish to use a fNML score
198
199 // indicate that we wish to use a K2 score
204
205 // indicate that we wish to use a Log2Likelihood score
210
211 // indicate that we wish to use a MDL score
216
217 // sets the max indegree
218 INLINE void IBNLearner::setMaxIndegree(Size max_indegree) {
220 }
221
222 // indicate that we wish to use MIIC with constraints
224
225 // indicate that we wish to use the PC algorithm
227
228 // indicate that we wish to use the FCI algorithm
230
231 // select Chi2 independence test for FCI (default)
234 GUM_ERROR(OperationNotAllowed, "useFCIChi2Test() is only valid when using the FCI algorithm")
235 }
237 }
238
239 // select G2 independence test for FCI
242 GUM_ERROR(OperationNotAllowed, "useFCIG2Test() is only valid when using the FCI algorithm")
243 }
245 }
246
247 // set alpha threshold for FCI
248 INLINE void IBNLearner::setFCIAlpha(double alpha) {
250 GUM_ERROR(OperationNotAllowed, "setFCIAlpha() is only valid when using the FCI algorithm")
251 }
252 alphaFci_ = alpha;
253 }
254
255 // set max discriminating-path length for FCI R4 (Size(-1) = unlimited)
259 "setFCIMaxPathLength() is only valid when using the FCI algorithm")
260 }
261 maxPathLengthFci_ = max_len;
262 }
263
264 INLINE void IBNLearner::setFCIExhaustiveSepSet(bool exhaustive) {
267 "setFCIExhaustiveSepSet() is only valid when using the FCI algorithm")
268 }
269 exhaustiveSepSetFci_ = exhaustive;
270 }
271
275 "fciExhaustiveSepSet() is only valid when using the FCI algorithm")
276 }
278 }
279
280 // select Chi2 independence test for PC (default)
283 GUM_ERROR(OperationNotAllowed, "useChi2Test() is only valid when using the PC algorithm")
284 }
286 }
287
288 // select G2 independence test for PC
289 INLINE void IBNLearner::useG2Test() {
291 GUM_ERROR(OperationNotAllowed, "useG2Test() is only valid when using the PC algorithm")
292 }
294 }
295
296 // set the alpha threshold for PC
297 INLINE void IBNLearner::setPCAlpha(double alpha) {
299 GUM_ERROR(OperationNotAllowed, "setPCAlpha() is only valid when using the PC algorithm")
300 }
301 alphaPc_ = alpha;
302 }
303
304 // set stable mode for PC
305 INLINE void IBNLearner::setPCStable(bool stable) {
307 GUM_ERROR(OperationNotAllowed, "setPCStable() is only valid when using the PC algorithm")
308 }
309 stablePc_ = stable;
310 }
311
312 // set max conditioning set size for PC (Size(-1) = unlimited)
316 "setPCMaxCondSetSize() is only valid when using the PC algorithm")
317 }
318 maxCondSetSizePc_ = max_k;
319 }
320
321 // set unshielded-collider ordering for PC
325 "setPCUnshieldedColliderSorted() is only valid when using the PC algorithm")
326 }
327 sortedUCPc_ = sorted;
328 }
329
334
339
344
346 INLINE std::vector< Arc > IBNLearner::latentVariables() const {
347 return algoMiic_.latentVariables();
348 }
349
350 // indicate that we wish to use a K2 algorithm
351 INLINE void IBNLearner::useK2(const Sequence< NodeId >& order) {
353 algoK2_.setOrder(order);
354 }
355
356 // indicate that we wish to use a K2 algorithm
357 INLINE void IBNLearner::useK2(const std::vector< NodeId >& order) {
359 algoK2_.setOrder(order);
360 }
361
362 // indicate that we wish to use a greedy hill climbing algorithm
366
367 // indicate that we wish to use a greedy hill climbing algorithm
371
372 // indicate that we wish to use greedy thick-thinning
376
377 // enable or disable arc reversals in the thin phase of greedy thick-thinning
381
382 // returns whether arc reversals are allowed in the thin phase
386
387 // indicate that we wish to use a local search with tabu list and the default parameters
390 static_cast< Size >(gum::config().typed< std::int64_t >("learning", "tabuListSize")),
391 static_cast< Size >(gum::config().typed< std::int64_t >("learning", "tabuNbDecrease")));
392 }
393
394 // indicate that we wish to use a local search with tabu list and the default nb_decrease
397 tabu_size,
398 static_cast< Size >(gum::config().typed< std::int64_t >("learning", "tabuNbDecrease")));
399 }
400
401 // indicate that we wish to use a local search with tabu list
409
411 INLINE void IBNLearner::useEM(const double epsilon) {
412 useEM(epsilon, gum::config().typed< double >("learning", "emNoise"));
413 }
414
416 INLINE void IBNLearner::useEM(const double epsilon, const double noise) {
417 if (epsilon < 0.0)
418 GUM_ERROR(OutOfBounds, "EM's min log-likelihood evolution rate must be non-negative");
419 if ((noise < 0.0) || (noise > 1.0))
420 GUM_ERROR(OutOfBounds, "EM's noise must belong to interval [0,1]");
421 if (epsilon > 0) {
422 useEM_ = true;
424 dag2BN_.setNoise(noise);
425 } else {
426 useEM_ = false; // epsilon == 0
427 }
428 }
429
432 INLINE void IBNLearner::useEMWithRateCriterion(const double epsilon) {
433 useEMWithRateCriterion(epsilon, gum::config().typed< double >("learning", "emNoise"));
434 }
435
437 INLINE void IBNLearner::useEMWithRateCriterion(const double epsilon, const double noise) {
438 if (epsilon <= 0.0)
439 GUM_ERROR(OutOfBounds, "EM's min log-likelihood evolution rate must be positive");
440 useEM(epsilon, noise);
441 }
442
445 INLINE void IBNLearner::useEMWithDiffCriterion(const double epsilon) {
446 useEMWithDiffCriterion(epsilon, gum::config().typed< double >("learning", "emNoise"));
447 }
448
450 INLINE void IBNLearner::useEMWithDiffCriterion(const double epsilon, const double noise) {
451 if (epsilon <= 0.0)
452 GUM_ERROR(OutOfBounds, "EM's min log-likelihood differences must be positive");
453 if ((noise < 0.0) || (noise > 1.0))
454 GUM_ERROR(OutOfBounds, "EM's noise must belong to interval [0,1]");
455 useEM_ = true;
457 dag2BN_.setNoise(noise);
458 }
459
461 INLINE void IBNLearner::forbidEM() { useEM_ = false; }
462
464 INLINE bool IBNLearner::isUsingEM() const { return useEM_; }
465
468 if (useEM_) return dag2BN_;
469 else GUM_ERROR(NotFound, "EM is currently forbidden. Please enable it with useEM()")
470 }
471
477
479 INLINE std::string IBNLearner::EMStateMessage() const {
481 else return "EM is currently forbidden. Please enable it with useEM()";
482 }
483
484 // allow (true)/forbid (false) to add arcs during learning
485 INLINE void IBNLearner::allowArcAdditions(bool allow) { allowArcAdditions_ = allow; }
486
487 // allow (true)/forbid (false) to delete arcs during learning
488 INLINE void IBNLearner::allowArcDeletions(bool allow) { allowArcDeletions_ = allow; }
489
490 // allow (true)/forbid (false) to reverse arcs during learning
491 INLINE void IBNLearner::allowArcReversals(bool allow) { allowArcReversals_ = allow; }
492
493 // allow (true)/forbid (false) to delete arc triangles during learning
496 }
497
501
502 // assign a set of forbidden edges
506
507 // assign a set of forbidden edges from an UndiGraph
511
512 // assign a new possible edge
513 INLINE void IBNLearner::addPossibleEdge(const Edge& edge) {
515 }
516
517 // remove a forbidden edge
518 INLINE void IBNLearner::erasePossibleEdge(const Edge& edge) {
520 }
521
522 // assign a new forbidden edge
523 INLINE void IBNLearner::addPossibleEdge(const NodeId tail, const NodeId head) {
524 addPossibleEdge(Edge(tail, head));
525 }
526
527 // remove a forbidden edge
528 INLINE void IBNLearner::erasePossibleEdge(const NodeId tail, const NodeId head) {
529 erasePossibleEdge(Edge(tail, head));
530 }
531
532 // assign a new forbidden edge
533 INLINE void IBNLearner::addPossibleEdge(std::string_view tail, std::string_view head) {
535 }
536
537 // remove a forbidden edge
538 INLINE void IBNLearner::erasePossibleEdge(std::string_view tail, std::string_view head) {
540 }
541
542 // assign a set of forbidden arcs
543 INLINE void IBNLearner::setForbiddenArcs(const ArcSet& set) {
545 }
546
547 // assign a new forbidden arc
549
550 // remove a forbidden arc
551 INLINE void IBNLearner::eraseForbiddenArc(const Arc& arc) {
553 }
554
555 // assign a new forbidden arc
556 INLINE void IBNLearner::addForbiddenArc(const NodeId tail, const NodeId head) {
557 addForbiddenArc(Arc(tail, head));
558 }
559
560 // remove a forbidden arc
561 INLINE void IBNLearner::eraseForbiddenArc(const NodeId tail, const NodeId head) {
562 eraseForbiddenArc(Arc(tail, head));
563 }
564
565 // assign a new forbidden arc
566 INLINE void IBNLearner::addForbiddenArc(std::string_view tail, std::string_view head) {
568 }
569
570 // remove a forbidden arc
571 INLINE void IBNLearner::eraseForbiddenArc(std::string_view tail, std::string_view head) {
573 }
574
575 // assign a set of forbidden arcs
576 INLINE void IBNLearner::setMandatoryArcs(const ArcSet& set) {
578 }
579
580 // assign a new forbidden arc
582
583 // remove a forbidden arc
584 INLINE void IBNLearner::eraseMandatoryArc(const Arc& arc) {
586 }
587
589
590 INLINE void IBNLearner::addNoParentNode(std::string_view name) {
592 }
593
597
598 INLINE void IBNLearner::eraseNoParentNode(std::string_view name) {
600 }
601
605
606 INLINE void IBNLearner::addNoChildrenNode(std::string_view name) {
608 }
609
613
614 INLINE void IBNLearner::eraseNoChildrenNode(std::string_view name) {
616 }
617
618 // assign a new forbidden arc
619 INLINE void IBNLearner::addMandatoryArc(std::string_view tail, std::string_view head) {
621 }
622
623 // remove a forbidden arc
624 INLINE void IBNLearner::eraseMandatoryArc(std::string_view tail, std::string_view head) {
626 }
627
628 // assign a new forbidden arc
629 INLINE void IBNLearner::addMandatoryArc(NodeId tail, NodeId head) {
630 addMandatoryArc(Arc(tail, head));
631 }
632
633 // remove a forbidden arc
635 eraseMandatoryArc(Arc(tail, head));
636 }
637
638 // sets a partial order on the nodes
642
643 INLINE void IBNLearner::setSliceOrder(const std::vector< std::vector< std::string > >& slices) {
644 NodeProperty< NodeId > slice_order;
645 NodeId rank = 0;
646 for (const auto& slice: slices) {
647 for (const auto& name: slice) {
648 slice_order.insert(idFromName(name), rank);
649 }
650 rank++;
651 }
652 setSliceOrder(slice_order);
653 }
654
656
657 // sets a total order over some nodes
661
662 // sets a total order over some nodes
663 INLINE void IBNLearner::setTotalOrder(const std::vector< std::string >& order) {
664 Sequence< NodeId > sequence;
665 for (const auto& name: order) {
666 sequence.insert(idFromName(name));
667 }
668 setTotalOrder(sequence);
669 }
670
671 // removes the current total ordering constraint, if any
673
674 // sets the prior weight
675 INLINE void IBNLearner::_setPriorWeight_(double weight) {
676 if (weight < 0) { GUM_ERROR(OutOfBounds, "the weight of the prior must be positive") }
677
678 priorWeight_ = weight;
680 }
681
682 // use the prior smoothing
687
688 // use the prior smoothing with the default weight
690 useSmoothingPrior(gum::config().typed< double >("learning", "priorWeight"));
691 }
692
693 // use the prior smoothing
694 INLINE void IBNLearner::useSmoothingPrior(double weight) {
695 if (weight < 0) { GUM_ERROR(OutOfBounds, "the weight of the prior must be positive") }
696
698 _setPriorWeight_(weight);
699
701 }
702
703 // use the Dirichlet prior with the default weight
704 INLINE void IBNLearner::useDirichletPrior(std::string_view filename) {
705 useDirichletPrior(filename, gum::config().typed< double >("learning", "priorWeight"));
706 }
707
708 // use the Dirichlet prior
709 INLINE void IBNLearner::useDirichletPrior(std::string_view filename, double weight) {
710 if (weight < 0) { GUM_ERROR(OutOfBounds, "the weight of the prior must be positive") }
711
712 priorDbname_ = filename;
714 _setPriorWeight_(weight);
715
717 }
718
719 // use the prior BDeu with the default weight
721 useBDeuPrior(gum::config().typed< double >("learning", "priorWeight"));
722 }
723
724 // use the prior BDeu
725 INLINE void IBNLearner::useBDeuPrior(double weight) {
726 if (weight < 0) { GUM_ERROR(OutOfBounds, "the weight of the prior must be positive") }
727
729 _setPriorWeight_(weight);
730
732 }
733
734 // returns the type (as a string) of a given prior
736 switch (priorType_) {
738 case NO_prior : return PriorType::NoPriorType;
739 case SMOOTHING : return PriorType::SmoothingPriorType;
740 case DIRICHLET_FROM_DATABASE :
741 case DIRICHLET_FROM_BAYESNET : return PriorType::DirichletPriorType;
742 case BDEU : return PriorType::BDeuPriorType;
743 default :
745 "IBNLearner getPriorType does "
746 "not support yet this prior")
747 }
748 }
749
750 // returns the names of the variables in the database
751 INLINE const std::vector< std::string >& IBNLearner::names() const {
752 return scoreDatabase_.names();
753 }
754
755 // returns the modalities of the variables in the database
756 INLINE const std::vector< std::size_t >& IBNLearner::domainSizes() const {
758 }
759
760 // returns the modalities of a variable in the database
761 INLINE Size IBNLearner::domainSize(NodeId var) const { return scoreDatabase_.domainSizes()[var]; }
762
763 // returns the modalities of a variables in the database
764 INLINE Size IBNLearner::domainSize(std::string_view var) const {
766 }
767
769 INLINE const std::vector< std::pair< std::size_t, std::size_t > >&
771 return ranges_;
772 }
773
775 INLINE void IBNLearner::clearDatabaseRanges() { ranges_.clear(); }
776
778 INLINE const DatabaseTable& IBNLearner::database() const {
780 }
781
782 INLINE Size IBNLearner::nbCols() const { return scoreDatabase_.domainSizes().size(); }
783
785
786 // sets the number max of threads that can be used
791
792 // ===========================================================================
793 // IBNLearner — inline implementations migrated from class body
794 // ===========================================================================
795
796 INLINE bool IBNLearner::isConstraintBased() const {
797 switch (selectedAlgo_) {
798 case AlgoType::K2 :
802 case AlgoType::GREEDY_THICK_THINNING : return false;
803 case AlgoType::MIIC :
804 case AlgoType::PC :
805 case AlgoType::FCI : return true;
806 default : throw OperationNotAllowed("Unknown algorithm");
807 }
808 }
809
810 INLINE bool IBNLearner::isScoreBased() const { return !isConstraintBased(); }
811
812 INLINE void
814 currentAlgorithm_ = approximationScheme;
815 }
816
817 INLINE void IBNLearner::distributeProgress(const ApproximationScheme* approximationScheme,
818 Size pourcent,
819 double error,
820 double time) {
821 setCurrentApproximationScheme(approximationScheme);
822 if (onProgress.hasListener()) GUM_EMIT3(onProgress, pourcent, error, time);
823 }
824
825 INLINE void IBNLearner::distributeStop(const ApproximationScheme* approximationScheme,
826 std::string_view message) {
827 setCurrentApproximationScheme(approximationScheme);
828 if (onStop.hasListener()) GUM_EMIT1(onStop, message);
829 }
830
837
838 INLINE double IBNLearner::epsilon() const {
839 if (currentAlgorithm_ != nullptr) return currentAlgorithm_->epsilon();
840 else GUM_ERROR(FatalError, "No chosen algorithm for learning")
841 }
842
849
856
857 INLINE bool IBNLearner::isEnabledEpsilon() const {
858 if (currentAlgorithm_ != nullptr) return currentAlgorithm_->isEnabledEpsilon();
859 else GUM_ERROR(FatalError, "No chosen algorithm for learning")
860 }
861
868
869 INLINE double IBNLearner::minEpsilonRate() const {
870 if (currentAlgorithm_ != nullptr) return currentAlgorithm_->minEpsilonRate();
871 else GUM_ERROR(FatalError, "No chosen algorithm for learning")
872 }
873
880
887
890 else GUM_ERROR(FatalError, "No chosen algorithm for learning")
891 }
892
899
900 INLINE Size IBNLearner::maxIter() const {
901 if (currentAlgorithm_ != nullptr) return currentAlgorithm_->maxIter();
902 else GUM_ERROR(FatalError, "No chosen algorithm for learning")
903 }
904
911
918
919 INLINE bool IBNLearner::isEnabledMaxIter() const {
920 if (currentAlgorithm_ != nullptr) return currentAlgorithm_->isEnabledMaxIter();
921 else GUM_ERROR(FatalError, "No chosen algorithm for learning")
922 }
923
924 INLINE void IBNLearner::setMaxTime(double timeout) {
928 dag2BN_.setMaxTime(timeout);
929 }
930
931 INLINE double IBNLearner::maxTime() const {
932 if (currentAlgorithm_ != nullptr) return currentAlgorithm_->maxTime();
933 else GUM_ERROR(FatalError, "No chosen algorithm for learning")
934 }
935
936 INLINE double IBNLearner::currentTime() const {
937 if (currentAlgorithm_ != nullptr) return currentAlgorithm_->currentTime();
938 else GUM_ERROR(FatalError, "No chosen algorithm for learning")
939 }
940
947
954
955 INLINE bool IBNLearner::isEnabledMaxTime() const {
956 if (currentAlgorithm_ != nullptr) return currentAlgorithm_->isEnabledMaxTime();
957 else GUM_ERROR(FatalError, "No chosen algorithm for learning")
958 }
959
966
968 if (currentAlgorithm_ != nullptr) return currentAlgorithm_->periodSize();
969 else GUM_ERROR(FatalError, "No chosen algorithm for learning")
970 }
971
978
979 INLINE bool IBNLearner::verbosity() const {
980 if (currentAlgorithm_ != nullptr) return currentAlgorithm_->verbosity();
981 else GUM_ERROR(FatalError, "No chosen algorithm for learning")
982 }
983
987 else GUM_ERROR(FatalError, "No chosen algorithm for learning")
988 }
989
991 if (currentAlgorithm_ != nullptr) return currentAlgorithm_->nbrIterations();
992 else GUM_ERROR(FatalError, "No chosen algorithm for learning")
993 }
994
995 INLINE const std::vector< double >& IBNLearner::history() const {
996 if (currentAlgorithm_ != nullptr) return currentAlgorithm_->history();
997 else GUM_ERROR(FatalError, "No chosen algorithm for learning")
998 }
999
1000 // EM methods
1001
1002 INLINE void IBNLearner::EMsetEpsilon(double eps) { dag2BN_.setEpsilon(eps); }
1003
1004 INLINE double IBNLearner::EMEpsilon() const { return dag2BN_.epsilon(); }
1005
1007
1009
1011
1013
1014 INLINE double IBNLearner::EMMinEpsilonRate() const { return dag2BN_.minEpsilonRate(); }
1015
1017
1019
1022 }
1023
1025
1026 INLINE Size IBNLearner::EMMaxIter() const { return dag2BN_.maxIter(); }
1027
1029
1031
1033
1034 INLINE void IBNLearner::EMsetMaxTime(double timeout) { dag2BN_.setMaxTime(timeout); }
1035
1036 INLINE double IBNLearner::EMMaxTime() const { return dag2BN_.maxTime(); }
1037
1038 INLINE double IBNLearner::EMCurrentTime() const { return dag2BN_.currentTime(); }
1039
1041
1043
1045
1047
1049
1051
1052 INLINE bool IBNLearner::EMVerbosity() const { return dag2BN_.verbosity(); }
1053
1058
1060
1061 INLINE const std::vector< double >& IBNLearner::EMHistory() const { return dag2BN_.history(); }
1062
1063 /* namespace learning */
1064} // namespace gum::learning
A class for generic framework of learning algorithms that can easily be used.
bool isEnabledEpsilon() const override
Returns true if stopping criterion on epsilon is enabled, false otherwise.
void setMaxIter(Size max) override
Stopping criterion on number of iterations.
void disableMaxTime() override
Disable stopping criterion on timeout.
void setMaxTime(double timeout) override
Stopping criterion on timeout.
void enableMaxIter() override
Enable stopping criterion on max iterations.
double minEpsilonRate() const override
Returns the value of the minimal epsilon rate.
void setMinEpsilonRate(double rate) override
Given that we approximate f(t), stopping criterion on d/dt(|f(t+1)-f(t)|).
void disableEpsilon() override
Disable stopping criterion on epsilon.
double epsilon() const override
Returns the value of epsilon.
void setPeriodSize(Size p) override
How many samples between two stopping is enable.
bool isEnabledMaxTime() const override
Returns true if stopping criterion on timeout is enabled, false otherwise.
ApproximationSchemeSTATE stateApproximationScheme() const override
Returns the approximation scheme state.
void enableEpsilon() override
Enable stopping criterion on epsilon.
double currentTime() const override
Returns the current running time in second.
bool isEnabledMinEpsilonRate() const override
Returns true if stopping criterion on epsilon rate is enabled, false otherwise.
double maxTime() const override
Returns the timeout (in seconds).
void disableMinEpsilonRate() override
Disable stopping criterion on epsilon rate.
Size periodSize() const override
Returns the period size.
void enableMaxTime() override
Enable stopping criterion on timeout.
Size nbrIterations() const override
Returns the number of iterations.
const std::vector< double > & history() const override
Returns the scheme history.
Size maxIter() const override
Returns the criterion on number of iterations.
void enableMinEpsilonRate() override
Enable stopping criterion on epsilon rate.
bool verbosity() const override
Returns true if verbosity is enabled.
bool isEnabledMaxIter() const override
Returns true if stopping criterion on max iterations is enabled, false otherwise.
void disableMaxIter() override
Disable stopping criterion on max iterations.
void setVerbosity(bool v) override
Set the verbosity on (true) or off (false).
void setEpsilon(double eps) override
Given that we approximate f(t), stopping criterion on |f(t+1)-f(t)|.
The base class for all directed edges.
Arc(NodeId tail, NodeId head)
basic constructor. Creates tail -> head.
Base class for dag.
Definition DAG.h:121
const EdgeSet & edges() const
returns the set of edges stored within the EdgeGraphPart
The base class for all undirected edges.
Edge(NodeId aN1, NodeId aN2)
constructs a new edge (aN1,aN2)
Exception : fatal (unknown ?) error.
value_type & insert(const Key &key, const Val &val)
Adds a new element (actually a copy of this element) into the hash table.
Signaler< Size, double, double > onProgress
Progression, error and time.
ApproximationSchemeSTATE
The different state of an approximation scheme.
std::string messageApproximationScheme() const
Returns the approximation scheme message.
Signaler< std::string_view > onStop
Criteria messageApproximationScheme.
Error: A name of variable is not found in the database.
Exception : the element we looked for cannot be found.
Exception : operation not allowed.
Exception : out of bound.
void setNumberOfThreads(Size nb) override
sets the number max of threads to be used by the class containing this ThreadNumberManager
Base class for undirected graphs.
Definition undiGraph.h:134
const std::vector< Arc > latentVariables() const
DAG2BNLearner & setNoise(const double noise)
sets the noise amount used to perturb the initial CPTs used by EM
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.
A class for parameterizing EM's parameter learning approximations.
void setMinEpsilonRate(double rate) override
sets the stopping criterion of EM as being the minimal log-likelihood's evolution rate
void setEpsilon(double eps) override
sets the stopping criterion of EM as being the minimal difference between two consecutive log-likelih...
void setAllowReversalsInThinPhase(bool allow)
enable or disable arc reversals during the thin phase (default: false)
bool allowReversalsInThinPhase() const
returns whether arc reversals are allowed in the thin phase
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
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
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
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
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...
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
void usePC()
indicate that we wish to use PC (Chi2 test by default)
StructuralConstraintPossibleEdges constraintPossibleEdges_
the constraint on possible Edges
StructuralConstraintNoParentNodes constraintNoParentNodes_
the constraint on no parent nodes
void useBDeuPrior()
use the BDeu prior with the default weight (key priorWeight of the section learning)
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)
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
double priorWeight_
the weight of the prior. It is always written by the useXxxPrior() methods, which read learning....
void enableEpsilon() override
Enable stopping criterion on epsilon.
double maxTime() const override
returns the timeout (in seconds)
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
std::string checkScorePriorCompatibility() const
checks whether the current score and prior are compatible
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
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)
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 useSmoothingPrior(double weight)
use the prior smoothing
void setMaxIter(Size max) override
stopping criterion on number of iterationsIf the criterion was disabled it will be enabled
void useEMWithRateCriterion(const double epsilon, const double noise)
use The EM algorithm to learn parameters with the rate stopping criterion
K2 algoK2_
the K2 algorithm
IndepTestType indepTestTypeFCI_
independence test type for FCI (reuses IndepTestType defined above)
void addMandatoryArc(const Arc &arc)
AlgoType selectedAlgo_
the learning algorithm ; it is initialized from the configuration, see preferredAlgo()
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.
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
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
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.
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
void EMsetMinEpsilonRate(double rate)
sets the stopping criterion of EM as being the minimal log-likelihood's evolution rate
bool isEnabledMaxTime() const override
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
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:117
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
void useEMWithDiffCriterion(const double epsilon, const double noise)
use The EM algorithm to learn parameters with the diff stopping criterion
StructuralConstraintNoChildrenNodes constraintNoChildrenNodes_
the constraint on no children nodes
DAG initialDAG()
returns the initial DAG structure
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
ScoreType scoreType_
the score selected for learning
bool EMVerbosity() const
returns the EM's verbosity status
const ApproximationScheme * currentAlgorithm_
void eraseForbiddenArc(const Arc &arc)
bool isEnabledEpsilon() const override
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 the threshold of the tests ; it is initialized from the key learning....
void useScoreK2()
indicate that we wish to use a K2 score
double alphaPc_
PC parameters the threshold of the tests ; it is initialized from the key learning....
StructuralConstraintIndegree constraintIndegree_
the constraint for indegrees
bool allowArcDeletions_
whether we allow or not arc deletions during learning
void _setPriorWeight_(double weight)
sets the prior weight
bool verbosity() const override
verbosity
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.
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 useNMLCorrection()
indicate that we wish to use the NML correction for and MIIC
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
void useLocalSearchWithTabuList()
indicate that we wish to use a local search with tabu list and the default parameters
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...
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 useLocalSearchWithTabuList(Size tabu_size, Size nb_decrease)
indicate that we wish to use a local search with tabu list
void unsetTotalOrder()
removes the current total ordering constraint, if any
GreedyHillClimbing greedyHillClimbing_
the greedy hill climbing algorithm
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 setVerbosity(bool v) override
verbosity
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
ApproximationSchemeSTATE stateApproximationScheme() const override
history
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)
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
void setCurrentApproximationScheme(const ApproximationScheme *approximationScheme)
{@ /// distribute signals
StructuralConstraintSliceOrder constraintSliceOrder_
the constraint for 2TBNs
const DatabaseTable & database() const
returns the database used by the BNLearner
bool EMisEnabledMinEpsilonRate() const
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 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)
CorrectedMutualInformation::KModeTypes kmodeMiic_
the penalty used in MIIC
double minEpsilonRate() const override
Get the value of the minimal epsilon rate.
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
void useBDeuPrior(double weight)
use the BDeu prior
std::size_t size() const noexcept
returns the number of records (rows) in the database
bool hasMissingValues() const
indicates whether the database contains some missing values
void setOrder(const Sequence< NodeId > &order)
sets the order on the variables
ApproximationScheme & approximationScheme()
returns the approximation policy of the learning algorithm
void setMaxNbDecreasingChanges(Size nb)
set the max number of changes decreasing the score that we allow to apply
void setNumberOfThreads(Size nb) override
sets the number max of threads that can be used
void addArc(const Arc &arc)
assign a new forbidden arc
void eraseArc(const Arc &arc)
remove a forbidden arc
void setArcs(const ArcSet &set)
assign a set of forbidden arcs
void setMaxIndegree(Size max_indegree, bool update_all_node=false)
resets the default max indegree and possibly updates the indegree of all nodes
void setArcs(const ArcSet &set)
assign a set of forbidden arcs
void eraseArc(const Arc &arc)
remove a forbidden arc
void addArc(const Arc &arc)
assign a new forbidden arc
void addNode(NodeId node)
assign a new node without children
void eraseNode(NodeId node)
remove a forbidden w node without children
void addNode(NodeId node)
assign a new node without parent
void eraseNode(NodeId node)
remove a node without parent
void addEdge(const Edge &edge)
assign a new forbidden arc
void setEdges(const EdgeSet &set)
assign a set of forbidden arcs
void eraseEdge(const Edge &edge)
remove a forbidden arc
void setTabuListSize(Size new_size)
sets the size of the tabu list
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
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
Configuration & config()
A short name for Configuration::instance() : gum::config().epsilonStandard(). It is not inline so tha...
#define GUM_EMIT1(signal, arg1)
Definition signaler.h:289
#define GUM_EMIT3(signal, arg1, arg2, arg3)
Definition signaler.h:291
Base classes for undirected graphs.