aGrUM 2.3.2
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-2025 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-2025 *
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#pragma once
41
42
43#include <algorithm>
44#include <cstdio>
45#include <iostream>
46
48
49namespace gum {
50 template < typename GUM_SCALAR >
51 std::unique_ptr< DiscreteVariable > fastVariable(std::string var_description,
52 Size default_domain_size) {
53 if (default_domain_size < 1)
54 GUM_ERROR(InvalidArgument, "default_domain_size can not be less than 1")
55
56 const std::string domain = "[" + std::to_string(default_domain_size) + "]";
57 return fastVariable< GUM_SCALAR >(var_description, domain);
58 }
59
60 template < typename GUM_SCALAR >
61 std::unique_ptr< DiscreteVariable > fastVariable(std::string var_description,
62 const std::string& default_domain) {
63 Size ds = 0;
64 long range_min = 0;
65 long range_max = 1;
66 std::vector< std::string > labels;
67 std::vector< GUM_SCALAR > ticks;
68 std::string name;
69
70 std::vector< int > values;
71 std::vector< double > numerical_values;
72
73 trim(var_description);
74
75 if (default_domain.size() == 0) GUM_ERROR(InvalidArgument, "default_domain can not be empty")
76
77 auto t = *default_domain.begin();
78 if (t != '[' && t != '{')
80 "default_domain (" << default_domain << ") must start with '[' or '{'")
81
82 if (var_description.find('[') == std::string::npos
83 && var_description.find('{') == std::string::npos) {
84 var_description += default_domain;
85 }
86
87 // [1,3,5]...
88 if (*(var_description.rbegin()) == ']') {
89 auto posBrack = var_description.find('[');
90 if (posBrack != std::string::npos) {
91 name = var_description.substr(0, posBrack);
92 const auto& s_args
93 = var_description.substr(posBrack + 1, var_description.size() - posBrack - 2);
94 const auto& args = split(s_args, ",");
95 if (args.empty()) {
96 // n[]
97 GUM_ERROR(InvalidArgument, "Empty range for variable " << var_description)
98 } else if (args.size() == 1) {
99 // n[4] or n[0:5.5:10]
100
101 const auto& labels = split(args[0], ":");
102
103 if (labels.size() == 3) {
104 // b{1.1:3.31:5}
105 const double fmin = std::stod(labels[0]);
106 const double fmax = std::stod(labels[1]);
107 const int nbr = std::stoi(labels[2]);
108
109 if (fmax <= fmin) { GUM_ERROR(InvalidArgument, "last<=first in " << var_description) }
110 if (nbr <= 1) { GUM_ERROR(InvalidArgument, "nbr<=1 in " << var_description) }
111 const double step = double((fmax - fmin) / nbr);
112 double current = fmin;
113 for (auto i = 0; i <= nbr; i += 1) {
114 ticks.push_back(current);
115 current += step;
116 }
117 ds = ticks.size();
118 } else {
119 // n[4]
120 int n = std::stoi(args[0]);
121 if (n < 2)
122 if (default_domain != "[1]")
123 GUM_ERROR(InvalidArgument, n << " is not >=2 for variable " << var_description)
124 ds = static_cast< Size >(n);
125 range_min = 0;
126 range_max = long(ds) - 1;
127 }
128 } else if (args.size() == 2) {
129 // n[5,10]
130 range_min = std::stol(args[0]);
131 range_max = std::stol(args[1]);
132
133 if (range_max < range_min)
135 "Invalid range for variable " << var_description << ": max<min")
136 if (range_max == range_min && default_domain != "[1]")
138 "Invalid range for variable "
139 << var_description << ": max==min not allowed if default_domain_size>1")
140
141 ds = static_cast< Size >(1 + range_max - range_min);
142 } else {
143 // n[3.14,5,10,12]
144 for (const auto& tick: args) {
145 ticks.push_back(static_cast< GUM_SCALAR >(std::strtod(tick.c_str(), nullptr)));
146 }
147 ds = args.size() - 1;
148 }
149 }
150 // var_description like "n{one|two|three}" or b{1.1:3.31:5}
151 } else if (*(var_description.rbegin()) == '}') {
152 auto posBrack = var_description.find('{');
153 if (posBrack != std::string::npos) {
154 name = var_description.substr(0, posBrack);
155 labels = split(var_description.substr(posBrack + 1, var_description.size() - posBrack - 2),
156 ":");
157 if (labels.size() == 3) {
158 // b{1.1:3.31:5}
159 const auto fmin = std::stod(labels[0]);
160 const auto fmax = std::stod(labels[1]);
161 const int nbr = std::stoi(labels[2]);
162
163 if (fmax <= fmin) { GUM_ERROR(InvalidArgument, "last<=first in " << var_description) }
164 if (nbr <= 1) { GUM_ERROR(InvalidArgument, "nbr<=1 in " << var_description) }
165 const double step = double((fmax - fmin) / (nbr - 1));
166
167 if ((trunc(step) == step) && (trunc(fmin) == fmin) && (trunc(fmax) == fmax)) {
168 // b{1:6:5} => IntegerVariable
169 labels.clear();
170 numerical_values.clear();
171 int v = int(fmin);
172 for (int i = 1; i <= nbr; i++) {
173 labels.push_back(std::to_string(v));
174 v += int(step);
175 }
176 ds = labels.size();
177 } else {
178 // b{1.3:6.3:5} => NumericalDiscreteVariable
179 labels.clear();
180 numerical_values.clear();
181 ds = nbr;
182 double v = fmin;
183 numerical_values.push_back(v);
184 for (auto i = 1; i < nbr - 1; i++) {
185 v += step;
186 numerical_values.push_back(v);
187 }
188 numerical_values.push_back(fmax);
189 }
190 } else {
191 labels
192 = split(var_description.substr(posBrack + 1, var_description.size() - posBrack - 2),
193 "|");
194 if (labels.size() < 2) {
195 if (labels.size() == 1
196 && default_domain != "[1]") // 1 is ok if default_domain_size==1
197 GUM_ERROR(InvalidArgument, "Not enough labels in var_description " << var_description)
198 }
199 if (!hasUniqueElts(labels)) {
200 GUM_ERROR(InvalidArgument, "Duplicate labels in var_description " << var_description)
201 }
202 ds = labels.size();
203 }
204 }
205 } else {
206 name = var_description;
207 }
208
209 if (ds == 0) {
210 GUM_ERROR(InvalidArgument, "No value for variable " << var_description << ".")
211 } else if (ds == 1) {
212 if (default_domain != "[1]")
214 "Only one value for variable " << var_description << " (2 at least are needed).")
215 }
216
217 if (!labels.empty()) {
218 if (std::all_of(labels.cbegin(), labels.cend(), isInteger)) {
219 for (const auto& label: labels)
220 values.push_back(std::stoi(label));
221 if (values.size() >= 2) {
222 // there can be an enumeration of consecutive integers
223 std::sort(values.begin(), values.end());
224 range_min = values[0];
225 auto v = range_min;
226 bool is_range = true;
227 for (const auto item: values) {
228 if (item != v) { is_range = false; }
229 v += 1;
230 }
231 if (is_range) {
232 values.clear(); // not an IntegerVariable but rather a RangeVariable
233 labels.clear();
234 range_max = v - 1;
235 }
236 }
237 } else if (std::all_of(labels.cbegin(), labels.cend(), isNumerical))
238 for (const auto& label: labels)
239 numerical_values.push_back(std::stod(label));
240 }
241
242 trim(name);
243
244 if (!values.empty()) {
245 return std::make_unique< IntegerVariable >(name, name, values);
246 } else if (!numerical_values.empty()) {
247 if (!std::all_of(numerical_values.cbegin(),
248 numerical_values.cend(),
250 GUM_ERROR(DefaultInLabel, "Infinite value is not allowed for variable " << name)
251 }
252 return std::make_unique< NumericalDiscreteVariable >(name, name, numerical_values);
253 } else if (!labels.empty()) {
254 return std::make_unique< LabelizedVariable >(name, name, labels);
255 } else if (!ticks.empty()) {
256 if (!std::all_of(ticks.cbegin(), ticks.cend(), gum::isfinite< double >)) {
257 GUM_ERROR(DefaultInLabel, "Infinite value is not allowed for variable " << name)
258 }
259 // if last character of name is a +, we remove the character from the name and set empirical
260 // to True
261 if (name.back() == '+') {
262 name.pop_back();
263 trim(name);
264 return std::make_unique< DiscretizedVariable< GUM_SCALAR > >(name, name, ticks, true);
265 } else {
266 return std::make_unique< DiscretizedVariable< GUM_SCALAR > >(name, name, ticks);
267 }
268 } else {
269 return std::make_unique< RangeVariable >(name, name, range_min, range_max);
270 }
271 }
272} // 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:72
std::size_t Size
In aGrUM, hashed values are unsigned long int.
Definition types.h:74
bool isNumerical(const std::string &val)
return true is a string contains a numerical (double) value
bool isInteger(const std::string &val)
return true is a string contains an integer value
void trim(std::string &s)
trim from both ends (in place)
std::vector< std::string > split(const std::string &str, const std::string &delim)
Split str using the delimiter.
gum is the global namespace for all aGrUM entities
Definition agrum.h:46
bool isfinite(T arg)
Definition math_utils.h:75
std::unique_ptr< DiscreteVariable > fastVariable(std::string var_description, Size default_domain_size)
Create a pointer on a Discrete Variable from a "fast" syntax.