aGrUM 3.1.1
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 if (auto posBrack = var_description.find('['); 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 auto step = (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) && (default_domain != "[1]"))
122 GUM_ERROR(InvalidArgument, n << " is not >=2 for variable " << var_description)
123 ds = static_cast< Size >(n);
124 range_min = 0;
125 range_max = static_cast< long >(ds) - 1;
126 }
127 } else if (args.size() == 2) {
128 // n[5,10]
129 range_min = std::stol(args[0]);
130 range_max = std::stol(args[1]);
131
132 if (range_max < range_min)
134 "Invalid range for variable " << var_description << ": max<min")
135 if (range_max == range_min && default_domain != "[1]")
137 "Invalid range for variable "
138 << var_description << ": max==min not allowed if default_domain_size>1")
139
140 ds = static_cast< Size >(1 + range_max - range_min);
141 } else {
142 // n[3.14,5,10,12]
143 for (const auto& tick: args) {
144 ticks.push_back(static_cast< GUM_SCALAR >(std::strtod(tick.c_str(), nullptr)));
145 }
146 ds = args.size() - 1;
147 }
148 }
149 // var_description like "n{one|two|three}" or b{1.1:3.31:5}
150 } else if (*(var_description.rbegin()) == '}') {
151 if (auto posBrack = var_description.find('{'); posBrack != std::string::npos) {
152 name = var_description.substr(0, posBrack);
153 labels = split(var_description.substr(posBrack + 1, var_description.size() - posBrack - 2),
154 ":");
155 if (labels.size() == 3) {
156 // b{1.1:3.31:5}
157 const auto fmin = std::stod(labels[0]);
158 const auto fmax = std::stod(labels[1]);
159 const int nbr = std::stoi(labels[2]);
160
161 if (fmax <= fmin) { GUM_ERROR(InvalidArgument, "last<=first in " << var_description) }
162 if (nbr <= 1) { GUM_ERROR(InvalidArgument, "nbr<=1 in " << var_description) }
163 const auto step = double((fmax - fmin) / (nbr - 1));
164
165 if ((trunc(step) == step) && (trunc(fmin) == fmin) && (trunc(fmax) == fmax)) {
166 // b{1:6:5} => IntegerVariable
167 labels.clear();
168 numerical_values.clear();
169 int v = int(fmin);
170 for (int i = 1; i <= nbr; i++) {
171 labels.push_back(std::to_string(v));
172 v += int(step);
173 }
174 ds = labels.size();
175 } else {
176 // b{1.3:6.3:5} => NumericalDiscreteVariable
177 labels.clear();
178 numerical_values.clear();
179 ds = nbr;
180 double v = fmin;
181 numerical_values.push_back(v);
182 for (auto i = 1; i < nbr - 1; i++) {
183 v += step;
184 numerical_values.push_back(v);
185 }
186 numerical_values.push_back(fmax);
187 }
188 } else {
189 labels
190 = split(var_description.substr(posBrack + 1, var_description.size() - posBrack - 2),
191 "|");
192 if (labels.size() < 2) {
193 if (labels.size() == 1
194 && default_domain != "[1]") // 1 is ok if default_domain_size==1
195 GUM_ERROR(InvalidArgument, "Not enough labels in var_description " << var_description)
196 }
197 if (!hasUniqueElts(labels)) {
198 GUM_ERROR(InvalidArgument, "Duplicate labels in var_description " << var_description)
199 }
200 ds = labels.size();
201 }
202 }
203 } else {
204 name = var_description;
205 }
206
207 if (ds == 0) {
208 GUM_ERROR(InvalidArgument, "No value for variable " << var_description << ".")
209 } else if (ds == 1) {
210 if (default_domain != "[1]")
212 "Only one value for variable " << var_description << " (2 at least are needed).")
213 }
214
215 if (!labels.empty()) {
216 if (std::all_of(labels.cbegin(), labels.cend(), isInteger)) {
217 for (const auto& label: labels)
218 values.push_back(std::stoi(label));
219 if (values.size() >= 2) {
220 // there can be an enumeration of consecutive integers
221 std::sort(values.begin(), values.end());
222 range_min = values[0];
223 auto v = range_min;
224 bool is_range = true;
225 for (const auto item: values) {
226 if (item != v) { is_range = false; }
227 v += 1;
228 }
229 if (is_range) {
230 values.clear(); // not an IntegerVariable but rather a RangeVariable
231 labels.clear();
232 range_max = v - 1;
233 }
234 }
235 } else if (std::all_of(labels.cbegin(), labels.cend(), isNumerical))
236 for (const auto& label: labels)
237 numerical_values.push_back(std::stod(label));
238 }
239
240 trim(name);
241
242 if (!values.empty()) {
243 return std::make_unique< IntegerVariable >(name, name, values);
244 } else if (!numerical_values.empty()) {
245 if (!std::all_of(numerical_values.cbegin(),
246 numerical_values.cend(),
248 GUM_ERROR(DefaultInLabel, "Infinite value is not allowed for variable " << name)
249 }
250 return std::make_unique< NumericalDiscreteVariable >(name, name, numerical_values);
251 } else if (!labels.empty()) {
252 return std::make_unique< LabelizedVariable >(name, name, labels);
253 } else if (!ticks.empty()) {
254 if (!std::all_of(ticks.cbegin(), ticks.cend(), gum::isfinite< double >)) {
255 GUM_ERROR(DefaultInLabel, "Infinite value is not allowed for variable " << name)
256 }
257 // if last character of name is a +, we remove the character from the name and set empirical
258 // to True
259 if (name.back() == '+') {
260 name.pop_back();
261 trim(name);
262 return std::make_unique< DiscretizedVariable< GUM_SCALAR > >(name, name, ticks, true);
263 } else {
264 return std::make_unique< DiscretizedVariable< GUM_SCALAR > >(name, name, ticks);
265 }
266 } else {
267 return std::make_unique< RangeVariable >(name, name, range_min, range_max);
268 }
269 }
270} // 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
std::vector< std::string > split(std::string_view str, std::string_view delim)
Split str using the delimiter.
bool isInteger(std::string_view val)
return true is a string contains an integer value
void trim(std::string &s)
trim from both ends (in place)
bool isNumerical(std::string_view val)
return true is a string contains a numerical (double) value
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.