aGrUM 3.3.2
a C++ library for (probabilistic) graphical models
IKTBNLearner_tpl.h
Go to the documentation of this file.
1/****************************************************************************
2 * This file is part of the aGrUM/pyAgrum library. *
3 * *
4 * Copyright (c) 2005-2026 by *
5 * - Pierre-Henri WUILLEMIN(_at_LIP6) *
6 * - Christophe GONZALES(_at_AMU) *
7 * *
8 * The aGrUM/pyAgrum library is free software; you can redistribute it *
9 * and/or modify it under the terms of either : *
10 * *
11 * - the GNU Lesser General Public License as published by *
12 * the Free Software Foundation, either version 3 of the License, *
13 * or (at your option) any later version, *
14 * - the MIT license (MIT), *
15 * - or both in dual license, as here. *
16 * *
17 * (see https://agrum.gitlab.io/articles/dual-licenses-lgplv3mit.html) *
18 * *
19 * This aGrUM/pyAgrum library is distributed in the hope that it will be *
20 * useful, but WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, *
21 * INCLUDING BUT NOT LIMITED TO THE WARRANTIES MERCHANTABILITY or FITNESS *
22 * FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE *
23 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER *
24 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, *
25 * ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR *
26 * OTHER DEALINGS IN THE SOFTWARE. *
27 * *
28 * See LICENCES for more details. *
29 * *
30 * SPDX-FileCopyrightText: Copyright 2005-2026 *
31 * - Pierre-Henri WUILLEMIN(_at_LIP6) *
32 * - Christophe GONZALES(_at_AMU) *
33 * SPDX-License-Identifier: LGPL-3.0-or-later OR MIT *
34 * *
35 * Contact : info_at_agrum_dot_org *
36 * homepage : http://agrum.gitlab.io *
37 * gitlab : https://gitlab.com/agrumery/agrum *
38 * *
39 ****************************************************************************/
40
41
47
48#pragma once
49
52
53namespace gum {
54
55 namespace learning {
56
57 template < GUM_Numeric GUM_SCALAR >
59 return static_cast< Size >(gum::config().typed< std::int64_t >("learning", "tabuListSize"));
60 }
61
62 template < GUM_Numeric GUM_SCALAR >
64 return static_cast< Size >(gum::config().typed< std::int64_t >("learning", "tabuNbDecrease"));
65 }
66
67 template < GUM_Numeric GUM_SCALAR >
69 return gum::config().typed< double >("learning", "priorWeight");
70 }
71
72 template < GUM_Numeric GUM_SCALAR >
77
78 template < GUM_Numeric GUM_SCALAR >
82
83 template < GUM_Numeric GUM_SCALAR >
87
88 template < GUM_Numeric GUM_SCALAR >
89 std::string IKTBNLearner< GUM_SCALAR >::_encode_(std::string_view base, int slice) const {
90 if (slice == KTBN< GUM_SCALAR >::ATEMPORAL) return std::string{base};
91 return std::string{base} + '[' + std::to_string(slice) + ']';
92 }
93
94 template < GUM_Numeric GUM_SCALAR >
95 std::pair< std::string, int >
96 IKTBNLearner< GUM_SCALAR >::_determineNode_(const std::string& name) const {
97 // check atemporal set first: a name registered as atemporal always maps
98 // to ATEMPORAL, even if it syntactically looks like "base[t]"
100
101 // syntactic parse: look for a trailing "[digits]" suffix
102 const std::size_t bracketPos = name.rfind('[');
103 if (bracketPos == std::string::npos) return {name, KTBN< GUM_SCALAR >::ATEMPORAL};
104
105 const std::string_view bracketContent{name.c_str() + bracketPos + 1,
106 name.size() - bracketPos - 1};
107 if (bracketContent.empty() || bracketContent.back() != ']')
108 return {name, KTBN< GUM_SCALAR >::ATEMPORAL};
109
110 const std::string_view digits = bracketContent.substr(0, bracketContent.size() - 1);
111 if (digits.empty()) return {name, KTBN< GUM_SCALAR >::ATEMPORAL};
112 for (const char c: digits)
113 if (std::isdigit(static_cast< unsigned char >(c)) == 0)
114 return {name, KTBN< GUM_SCALAR >::ATEMPORAL};
115
116 int slice{};
117 try {
118 slice = std::stoi(std::string{digits});
119 } catch (const std::out_of_range&) {
121 "Node name '" << name << "' has a slice index too large to represent as int.")
122 }
123 return {name.substr(0, bracketPos), slice};
124 }
125
126 template < GUM_Numeric GUM_SCALAR >
128 std::string_view head,
129 std::string_view action) const {
130 const int tailSlice = _determineNode_(std::string{tail}).second;
131 const int headSlice = _determineNode_(std::string{head}).second;
132 if (tailSlice != KTBN< GUM_SCALAR >::ATEMPORAL && headSlice == KTBN< GUM_SCALAR >::ATEMPORAL)
134 "cannot " << action << " " << tail << " -> " << head
135 << ": a temporal variable can never be a parent of an atemporal one; "
136 "this constraint is part of the k-TBN definition")
137 if (headSlice < tailSlice)
139 "cannot " << action << " " << tail << " -> " << head
140 << ": its head is at an earlier time slice than its tail, which "
141 "violates temporal causality")
142 }
143
144 template < GUM_Numeric GUM_SCALAR >
145 std::unordered_set< std::string > IKTBNLearner< GUM_SCALAR >::_scanConstantColumns_(
146 std::string_view dirPath,
147 std::string_view csvBaseName,
148 Size nbSamples,
149 const std::vector< std::string >& missingSymbols) {
150 namespace fs = std::filesystem;
151 const fs::path dir{dirPath};
152 const std::string stem{csvBaseName};
153 const std::unordered_set< std::string > missing(missingSymbols.begin(), missingSymbols.end());
154
155 std::vector< std::string > header; // captured from trajectory 1
156 std::vector< std::size_t > candidates; // column indices not yet falsified; shrinks only
157 std::vector< std::string > firstSeen; // per column: first non-missing value THIS trajectory
158 std::vector< bool >
159 haveFirstSeen; // per column: whether firstSeen[c] is set THIS trajectory
160
161 for (Size i = 0; i < nbSamples; ++i) {
162 // once every column has been falsified, nothing left to test can
163 // ever become atemporal again, so remaining trajectories are never
164 // even opened. Not part of the for-condition: `candidates` does not
165 // exist yet before trajectory 1 populates it.
166 if (i > 0 && candidates.empty()) break;
167
168 const fs::path file = dir / (stem + std::to_string(i + 1) + ".csv");
169 std::ifstream is(file, std::ifstream::in);
170 if (!is.is_open()) GUM_ERROR(IOError, "Cannot open " << file.string());
171
172 CSVParser parser(is, file.string());
173 parser.next();
174 const auto& raw = parser.current();
175
176 if (i == 0) {
177 header.assign(raw.begin(), raw.end());
178 candidates.resize(header.size());
179 std::iota(candidates.begin(), candidates.end(), std::size_t{0});
180 } else {
181 bool same = (raw.size() == header.size());
182 for (std::size_t c = 0; same && c < header.size(); ++c)
183 same = (raw[c] == header[c]);
184 if (!same)
186 "Header of " << file.string() << " differs from trajectory 1");
187 }
188
189 haveFirstSeen.assign(header.size(), false);
190 firstSeen.assign(header.size(), {});
191
192 while (parser.next()) {
193 const auto& tokens = parser.current();
194 if (tokens.size() != header.size())
196 "Trajectory " << (i + 1) << ", row " << parser.nbLine() << ": expected "
197 << header.size() << " columns, got " << tokens.size());
198 // iterate only the still-live candidates, swap-erasing any just
199 // falsified so later rows (and later trajectories) never revisit it
200 for (std::size_t idx = 0; idx < candidates.size();) {
201 const std::size_t c = candidates[idx];
202 if (missing.contains(tokens[c])) {
203 ++idx; // uninformative row for this column, still a candidate
204 continue;
205 }
206 if (!haveFirstSeen[c]) {
207 firstSeen[c] = tokens[c];
208 haveFirstSeen[c] = true;
209 ++idx;
210 } else if (tokens[c] != firstSeen[c]) {
211 candidates[idx] = candidates.back(); // falsified: drop, O(1)
212 candidates.pop_back();
213 } else {
214 ++idx;
215 }
216 }
217 if (candidates.empty()) break; // nothing left to test in this file either
218 }
219 }
220
221 std::unordered_set< std::string > atemporalVars;
222 for (const std::size_t c: candidates)
223 atemporalVars.insert(header[c]);
224 return atemporalVars;
225 }
226
227 template < GUM_Numeric GUM_SCALAR >
229 std::string_view context) const {
230 const std::string b{base};
231 if (!_isKnownBase_(b))
233 "unknown base variable '" << base
234 << "': it is not one of this learner's variables")
237 "atemporal variable '" << base << "' cannot appear in " << context
238 << ": it has no per-slice instance")
239 }
240
241 template < GUM_Numeric GUM_SCALAR >
242 void IKTBNLearner< GUM_SCALAR >::_checkMinimalOrder_(Size order, std::string_view label) {
243 if (order < 2)
245 "a k-TBN learner requires "
246 << label << " >= 2: k=1 is a static Bayesian network, use BNLearner instead")
247 }
248
249 } /* namespace learning */
250} /* namespace gum */
Common configuration interface for k-TBN learners.
T typed(std::string_view section, std::string_view key) const
Value of section.key converted according to its declared type.
Exception : input/output problem.
Exception: at least one argument passed to a function is not what was expected.
static constexpr int ATEMPORAL
Conventional time-slice value denoting an atemporal (static) variable.
Definition KTBN.h:204
Class for fast parsing of CSV file (never more than one line in application memory).
Definition CSVParser.h:78
bool next()
gets the next line of the csv stream and parses it
std::size_t nbLine() const
returns the current line number within the stream
const std::vector< std::string > & current() const
returns the current parsed line
Pure-virtual configuration interface shared by all k-TBN learners.
virtual bool _isKnownBase_(std::string_view base) const =0
Whether base is one of this learner's variables, temporal or atemporal. The second subclass-specific ...
virtual IKTBNLearner< GUM_SCALAR > & useSmoothingPrior(double weight)=0
smoothing prior with the default weight (key priorWeight of the section learning of gum::Configuratio...
void _checkBaseIsTemporal_(std::string_view base, std::string_view context) const
Throw InvalidArgument unless base is a known temporal base. context completes "cannot appear in <cont...
void _checkArcTemporallyFeasible_(std::string_view tail, std::string_view head, std::string_view action) const
Reject an arc the k-TBN definition can never contain, so eraseForbiddenArc and addMandatoryArc both f...
static std::unordered_set< std::string > _scanConstantColumns_(std::string_view dirPath, std::string_view csvBaseName, Size nbSamples, const std::vector< std::string > &missingSymbols)
Scans every trajectory and returns the base names classified atemporal: those whose value never chang...
virtual const std::unordered_set< std::string > & _atemporalVarNames_() const =0
The base names of the atemporal (static) variables. The only subclass-specific input to determineNode...
static void _checkMinimalOrder_(Size order, std::string_view label)
Throw InvalidArgument unless order is at least 2, label naming the offending parameter ("k" for the f...
static double defaultPriorWeight_()
IKTBNLearner< GUM_SCALAR > & useLocalSearchWithTabuList()
local search with tabu list and the default parameters (keys tabuListSize and tabuNbDecrease of the s...
std::string _encode_(std::string_view base, int slice) const
(base, slice) -> engine name ("A[1]" / atemporal engine name). Pure function, shared by every learner...
IKTBNLearner< GUM_SCALAR > & useSmoothingPrior()
smoothing prior with the default weight (key priorWeight of the section learning of gum::Configuratio...
virtual IKTBNLearner< GUM_SCALAR > & useLocalSearchWithTabuList(Size tabu_size, Size nb_decrease)=0
local search with tabu list, with the default number of decreasing changes (key tabuNbDecrease of the...
std::pair< std::string, int > _determineNode_(const std::string &name) const
engine name -> (base, slice); atemporal names map to KTBN::ATEMPORAL. Shared by every learner; only t...
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
GUM_SHARED_PUBLIC bool contains(std::string_view s, std::string_view needle)
true if needle in s
include the inlined functions if necessary
Definition CSVParser.h:55
gum is the global namespace for all aGrUM entities
Definition agrum.h:46
Configuration & config()
A short name for Configuration::instance() : gum::config().epsilonStandard(). It is not inline so tha...