aGrUM 3.2.0
a C++ library for (probabilistic) graphical models
allDiscreteVariables_tpl.h
Go to the documentation of this file.
1/****************************************************************************
2 * This file is part of the aGrUM/pyAgrum library. *
3 * *
4 * Copyright (c) 2005-2026 by *
5 * - Pierre-Henri WUILLEMIN(_at_LIP6) *
6 * - Christophe GONZALES(_at_AMU) *
7 * *
8 * The aGrUM/pyAgrum library is free software; you can redistribute it *
9 * and/or modify it under the terms of either : *
10 * *
11 * - the GNU Lesser General Public License as published by *
12 * the Free Software Foundation, either version 3 of the License, *
13 * or (at your option) any later version, *
14 * - the MIT license (MIT), *
15 * - or both in dual license, as here. *
16 * *
17 * (see https://agrum.gitlab.io/articles/dual-licenses-lgplv3mit.html) *
18 * *
19 * This aGrUM/pyAgrum library is distributed in the hope that it will be *
20 * useful, but WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, *
21 * INCLUDING BUT NOT LIMITED TO THE WARRANTIES MERCHANTABILITY or FITNESS *
22 * FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE *
23 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER *
24 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, *
25 * ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR *
26 * OTHER DEALINGS IN THE SOFTWARE. *
27 * *
28 * See LICENCES for more details. *
29 * *
30 * SPDX-FileCopyrightText: Copyright 2005-2026 *
31 * - Pierre-Henri WUILLEMIN(_at_LIP6) *
32 * - Christophe GONZALES(_at_AMU) *
33 * SPDX-License-Identifier: LGPL-3.0-or-later OR MIT *
34 * *
35 * Contact : info_at_agrum_dot_org *
36 * homepage : http://agrum.gitlab.io *
37 * gitlab : https://gitlab.com/agrumery/agrum *
38 * *
39 ****************************************************************************/
40
41#pragma once
42
43
44#include <algorithm>
45#include <cstdio>
46#include <iostream>
47
49
50namespace gum {
51 template < GUM_Numeric GUM_SCALAR >
52 std::unique_ptr< DiscreteVariable > fastVariable(std::string var_description,
53 Size default_domain_size) {
54 if (default_domain_size < 1)
55 GUM_ERROR(InvalidArgument, "default_domain_size can not be less than 1")
56
57 const std::string domain = "[" + std::to_string(default_domain_size) + "]";
58 return fastVariable< GUM_SCALAR >(var_description, domain);
59 }
60
61 template < GUM_Numeric GUM_SCALAR >
62 std::unique_ptr< DiscreteVariable > fastVariable(std::string var_description,
63 std::string_view default_domain) {
64 Size ds = 0;
65 long range_min = 0;
66 long range_max = 1;
67 std::vector< std::string > labels;
68 std::vector< GUM_SCALAR > ticks;
69 std::string name;
70
71 std::vector< int > values;
72 std::vector< double > numerical_values;
73
74 trim(var_description);
75
76 if (default_domain.empty()) GUM_ERROR(InvalidArgument, "default_domain can not be empty")
77
78
79 if (auto t = *default_domain.begin(); t != '[' && t != '{')
81 "default_domain (" << default_domain << ") must start with '[' or '{'")
82
83 if (var_description.find('[') == std::string::npos
84 && var_description.find('{') == std::string::npos) {
85 var_description += default_domain;
86 }
87
88 // [1,3,5]...
89 if (*(var_description.rbegin()) == ']') {
90 // The domain spec is the LAST bracket group, not the first: a name may
91 // itself legally contain "[...]" (e.g. gum::KTBN's "base[slice]" engine
92 // names), and such a name must survive round-tripping through toFast().
93 if (auto posBrack = var_description.rfind('['); posBrack != std::string::npos) {
94 name = var_description.substr(0, posBrack);
95 const auto& s_args
96 = var_description.substr(posBrack + 1, var_description.size() - posBrack - 2);
97 const auto& args = split(s_args, ",");
98 if (args.empty()) {
99 // n[]
100 GUM_ERROR(InvalidArgument, "Empty range for variable " << var_description)
101 } else if (args.size() == 1) {
102 // n[4] or n[0:5.5:10]
103
104 const auto& labels = split(args[0], ":");
105
106 if (labels.size() == 3) {
107 // b{1.1:3.31:5}
108 const double fmin = std::stod(labels[0]);
109 const double fmax = std::stod(labels[1]);
110 const int nbr = std::stoi(labels[2]);
111
112 if (fmax <= fmin) { GUM_ERROR(InvalidArgument, "last<=first in " << var_description) }
113 if (nbr <= 1) { GUM_ERROR(InvalidArgument, "nbr<=1 in " << var_description) }
114 const auto step = (fmax - fmin) / nbr;
115 double current = fmin;
116 for (auto i = 0; i <= nbr; i += 1) {
117 ticks.push_back(current);
118 current += step;
119 }
120 ds = ticks.size();
121 } else {
122 // n[4]
123 int n = std::stoi(args[0]);
124 if ((n < 2) && (default_domain != "[1]"))
125 GUM_ERROR(InvalidArgument, n << " is not >=2 for variable " << var_description)
126 ds = static_cast< Size >(n);
127 range_min = 0;
128 range_max = static_cast< long >(ds) - 1;
129 }
130 } else if (args.size() == 2) {
131 // n[5,10]
132 range_min = std::stol(args[0]);
133 range_max = std::stol(args[1]);
134
135 if (range_max < range_min)
137 "Invalid range for variable " << var_description << ": max<min")
138 if (range_max == range_min && default_domain != "[1]")
140 "Invalid range for variable "
141 << var_description << ": max==min not allowed if default_domain_size>1")
142
143 ds = static_cast< Size >(1 + range_max - range_min);
144 } else {
145 // n[3.14,5,10,12]
146 for (const auto& tick: args) {
147 ticks.push_back(static_cast< GUM_SCALAR >(std::strtod(tick.c_str(), nullptr)));
148 }
149 ds = args.size() - 1;
150 }
151 }
152 // var_description like "n{one|two|three}" or b{1.1:3.31:5}
153 } else if (*(var_description.rbegin()) == '}') {
154 if (auto posBrack = var_description.find('{'); posBrack != std::string::npos) {
155 name = var_description.substr(0, posBrack);
156 labels = split(var_description.substr(posBrack + 1, var_description.size() - posBrack - 2),
157 ":");
158 if (labels.size() == 3) {
159 // b{1.1:3.31:5}
160 const auto fmin = std::stod(labels[0]);
161 const auto fmax = std::stod(labels[1]);
162 const int nbr = std::stoi(labels[2]);
163
164 if (fmax <= fmin) { GUM_ERROR(InvalidArgument, "last<=first in " << var_description) }
165 if (nbr <= 1) { GUM_ERROR(InvalidArgument, "nbr<=1 in " << var_description) }
166 const auto step = double((fmax - fmin) / (nbr - 1));
167
168 if ((trunc(step) == step) && (trunc(fmin) == fmin) && (trunc(fmax) == fmax)) {
169 // b{1:6:5} => IntegerVariable
170 labels.clear();
171 numerical_values.clear();
172 int v = int(fmin);
173 for (int i = 1; i <= nbr; i++) {
174 labels.push_back(std::to_string(v));
175 v += int(step);
176 }
177 ds = labels.size();
178 } else {
179 // b{1.3:6.3:5} => NumericalDiscreteVariable
180 labels.clear();
181 numerical_values.clear();
182 ds = nbr;
183 double v = fmin;
184 numerical_values.push_back(v);
185 for (auto i = 1; i < nbr - 1; i++) {
186 v += step;
187 numerical_values.push_back(v);
188 }
189 numerical_values.push_back(fmax);
190 }
191 } else {
192 labels
193 = split(var_description.substr(posBrack + 1, var_description.size() - posBrack - 2),
194 "|");
195 if (labels.size() < 2) {
196 if (labels.size() == 1
197 && default_domain != "[1]") // 1 is ok if default_domain_size==1
198 GUM_ERROR(InvalidArgument, "Not enough labels in var_description " << var_description)
199 }
200 if (!hasUniqueElts(labels)) {
201 GUM_ERROR(InvalidArgument, "Duplicate labels in var_description " << var_description)
202 }
203 ds = labels.size();
204 }
205 }
206 } else {
207 name = var_description;
208 }
209
210 if (ds == 0) {
211 GUM_ERROR(InvalidArgument, "No value for variable " << var_description << ".")
212 } else if (ds == 1) {
213 if (default_domain != "[1]")
215 "Only one value for variable " << var_description << " (2 at least are needed).")
216 }
217
218 if (!labels.empty()) {
219 if (std::all_of(labels.cbegin(), labels.cend(), isInteger)) {
220 for (const auto& label: labels)
221 values.push_back(std::stoi(label));
222 if (values.size() >= 2) {
223 // there can be an enumeration of consecutive integers
224 std::sort(values.begin(), values.end());
225 range_min = values[0];
226 auto v = range_min;
227 bool is_range = true;
228 for (const auto item: values) {
229 if (item != v) { is_range = false; }
230 v += 1;
231 }
232 if (is_range) {
233 values.clear(); // not an IntegerVariable but rather a RangeVariable
234 labels.clear();
235 range_max = v - 1;
236 }
237 }
238 } else if (std::all_of(labels.cbegin(), labels.cend(), isNumerical))
239 for (const auto& label: labels)
240 numerical_values.push_back(std::stod(label));
241 }
242
243 trim(name);
244
245 if (!values.empty()) {
246 return std::make_unique< IntegerVariable >(name, name, values);
247 } else if (!numerical_values.empty()) {
248 if (!std::all_of(numerical_values.cbegin(),
249 numerical_values.cend(),
251 GUM_ERROR(DefaultInLabel, "Infinite value is not allowed for variable " << name)
252 }
253 return std::make_unique< NumericalDiscreteVariable >(name, name, numerical_values);
254 } else if (!labels.empty()) {
255 return std::make_unique< LabelizedVariable >(name, name, labels);
256 } else if (!ticks.empty()) {
257 if (!std::all_of(ticks.cbegin(), ticks.cend(), gum::isfinite< double >)) {
258 GUM_ERROR(DefaultInLabel, "Infinite value is not allowed for variable " << name)
259 }
260 // if last character of name is a +, we remove the character from the name and set empirical
261 // to True
262 if (name.back() == '+') {
263 name.pop_back();
264 trim(name);
265 return std::make_unique< DiscretizedVariable< GUM_SCALAR > >(name, name, ticks, true);
266 } else {
267 return std::make_unique< DiscretizedVariable< GUM_SCALAR > >(name, name, ticks);
268 }
269 } else {
270 return std::make_unique< RangeVariable >(name, name, range_min, range_max);
271 }
272 }
273} // namespace gum
Exception : default in label.
Exception: at least one argument passed to a function is not what was expected.
#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 isInteger(std::string_view val)
return true is a string contains an integer value
GUM_SHARED_PUBLIC void trim(std::string &s)
trim from both ends (in place)
GUM_SHARED_PUBLIC bool isNumerical(std::string_view val)
return true is a string contains a numerical (double) value
std::vector< std::string > split(std::string_view str, std::string_view delim)
Split str using the delimiter.
gum is the global namespace for all aGrUM entities
Definition agrum.h:46
bool isfinite(T arg)
std::unique_ptr< DiscreteVariable > fastVariable(std::string var_description, Size default_domain_size)
Create a pointer on a Discrete Variable from a "fast" syntax.