aGrUM 3.3.2
a C++ library for (probabilistic) graphical models
discretizedVariable_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
43#include <agrum/base/variables/discretizedVariable.h> // to ease IDE parser
44#pragma once
45
46#ifndef DOXYGEN_SHOULD_SKIP_THIS
47# include <limits>
48# include <sstream>
49
51
54
55namespace gum {
56 template < typename T_TICKS >
58 eraseTicks();
60 _is_empirical = aDRV._is_empirical;
61 _ticks_ = aDRV._ticks_;
62 }
63
64 template < typename T_TICKS >
65 Idx DiscretizedVariable< T_TICKS >::pos_(const T_TICKS& target) const {
66 if (_ticks_.empty()) { GUM_ERROR(OutOfBounds, "No tick defined for variable " << name()) }
67
68 if (target < _ticks_[0]) return static_cast< Idx >(0);
69 if (target > _ticks_[_ticks_.size() - 1]) return static_cast< Idx >(_ticks_.size() - 2);
70 // now target is in the range [T1,Tn]
71 const Idx res = std::lower_bound(_ticks_.begin(), _ticks_.end(), target) - _ticks_.begin();
72 if (res + 1 >= _ticks_.size()) return static_cast< Idx >(_ticks_.size() - 2);
73 if (_ticks_[res] == target) return res;
74 // here res>0 because target>=_ticks_[0]
75 return res - 1;
76 }
77
78 template < typename T_TICKS >
79 Idx DiscretizedVariable< T_TICKS >::index(const T_TICKS target) const {
80 const Idx ind = std::lower_bound(_ticks_.begin(), _ticks_.end(), target) - _ticks_.begin();
81 if (ind + 1 >= _ticks_.size()) {
82 GUM_ERROR(OutOfBounds, target << " is not a tick in " << *this)
83 }
84 if (_ticks_[ind] == target) return ind;
85
86 GUM_ERROR(OutOfBounds, target << " is not a tick in " << *this)
87 }
88
89 template < typename T_TICKS >
90 bool DiscretizedVariable< T_TICKS >::isTick(const T_TICKS& target) const {
91 const Size ind = std::lower_bound(_ticks_.begin(), _ticks_.end(), target) - _ticks_.begin();
92 if (ind >= _ticks_.size()) { return false; }
93 return (_ticks_[ind] == target);
94 }
95
96 template < typename T_TICKS >
98 std::string_view aDesc) :
99 IDiscretizedVariable(aName, aDesc) {
100 GUM_CONSTRUCTOR(DiscretizedVariable);
101 _is_empirical = false;
102 _ticks_.reserve(10);
103 }
104
105 template < typename T_TICKS >
106 DiscretizedVariable< T_TICKS >::DiscretizedVariable(std::string_view aName,
107 std::string_view aDesc,
108 const std::vector< T_TICKS >& ticks,
109 bool is_empirical) :
110 IDiscretizedVariable(aName, aDesc) {
111 GUM_CONSTRUCTOR(DiscretizedVariable)
112 _is_empirical = is_empirical;
113 _ticks_.reserve(ticks.size());
114 for (const auto tick: ticks) {
115 if (!gum::isfinite< double >(tick)) {
116 GUM_ERROR(DefaultInLabel, "Value '" << tick << "' is not allowed for variable " << aName)
117 }
118 if (!isTick(tick)) { _ticks_.push_back(tick); }
119 }
120 std::sort(_ticks_.begin(), _ticks_.end());
121 }
122
123 template < typename T_TICKS >
124 DiscretizedVariable< T_TICKS >::DiscretizedVariable(const DiscretizedVariable< T_TICKS >& aDRV) :
125 IDiscretizedVariable(aDRV) {
126 GUM_CONS_CPY(DiscretizedVariable);
127 copy_(aDRV);
128 }
129
130 template < typename T_TICKS >
131 DiscretizedVariable< T_TICKS >::~DiscretizedVariable() {
132 GUM_DESTRUCTOR(DiscretizedVariable);
133 }
134
135 template < typename T_TICKS >
136 DiscretizedVariable< T_TICKS >* DiscretizedVariable< T_TICKS >::clone() const {
137 return new DiscretizedVariable< T_TICKS >(*this);
138 }
139
140 template < typename T_TICKS >
141 DiscretizedVariable< T_TICKS >&
142 DiscretizedVariable< T_TICKS >::operator=(const DiscretizedVariable< T_TICKS >& aDRV) {
143 copy_(aDRV);
144 return *this;
145 }
146
147 template < typename T_TICKS >
148 DiscretizedVariable< T_TICKS >& DiscretizedVariable< T_TICKS >::addTick(const T_TICKS& aTick) {
149 // check if aTick is a float or a special value (infinity or not a number)
150 if (!gum::isfinite(aTick)) {
151 GUM_ERROR(DefaultInLabel, "Tick '" << aTick << "' is not allowed for variable " << name())
152 }
153 if (isTick(aTick)) {
154 GUM_ERROR(DefaultInLabel, "Tick '" << aTick << "' already used for variable " << name())
155 }
156
157 _ticks_.push_back(aTick);
158 std::sort(_ticks_.begin(), _ticks_.end());
159
160 return *this;
161 }
162
163 template < typename T_TICKS >
164 void DiscretizedVariable< T_TICKS >::eraseTicks() {
165 _ticks_.clear();
166 }
167
168 template < typename T_TICKS >
169 std::string DiscretizedVariable< T_TICKS >::label(Idx i) const {
170 if (i + 1 >= _ticks_.size()) { GUM_ERROR(OutOfBounds, "Unexisting label index") }
171
172 const char open = ((i == 0) && _is_empirical) ? '(' : '[';
173 const char close = (i == _ticks_.size() - 2) ? (_is_empirical ? ')' : ']') : '[';
174
175 return std::format("{}{};{}{}", open, _ticks_[i], _ticks_[i + 1], close);
176 }
177
183 template < typename T_TICKS >
184 double DiscretizedVariable< T_TICKS >::numerical(Idx index) const {
185 if (index >= _ticks_.size() - 1) {
186 GUM_ERROR(OutOfBounds, "Unexisting label index (" << index << ") for " << *this << ".")
187 }
188 const auto& a = static_cast< double >(_ticks_[index]);
189 const auto& b = static_cast< double >(_ticks_[index + 1]);
190
191 return (b + a) / 2.0;
192 }
193
199 template < typename T_TICKS >
200 double DiscretizedVariable< T_TICKS >::draw(Idx indice) const {
201 if (indice >= _ticks_.size() - 1) {
202 GUM_ERROR(OutOfBounds, "Unexisting label index (" << indice << ") for " << *this << ".")
203 }
204 const auto& a = static_cast< double >(_ticks_[indice]);
205 const auto& b = static_cast< double >(_ticks_[indice + 1]);
206
207 auto p = gum::randomProba() * (b - a) + a;
208 if (indice < _ticks_.size() - 2) { // p can not be b. We iterate 3 times before returning the
209 // median (should not be possible)
210 if (p == b) p = gum::randomProba() * (b - a) + a;
211 if (p == b) p = gum::randomProba() * (b - a) + a;
212 if (p == b) p = (b - a) / 2;
213 }
214
215 return p;
216 }
217
218 template < typename T_TICKS >
219 Idx DiscretizedVariable< T_TICKS >::index(std::string_view label) const {
220 if (empty()) { GUM_ERROR(OutOfBounds, "empty variable : " + toString()) }
221
222 // first check if label contains a numeric value
223 std::istringstream i(std::string{label});
224 T_TICKS target;
225 if (i >> target) {
226 const double epsilon = config().epsilonFine();
227 if (target < _ticks_[0]) {
228 if (_ticks_[0] - target < epsilon * (1.0 + std::abs(static_cast< double >(_ticks_[0]))))
229 return 0;
230 if (_is_empirical) return 0;
231 else
233 "less than first range (< " << _ticks_[0] << ") for " << target << " in "
234 << *this)
235 }
236
237 if (const auto size = _ticks_.size(); target > _ticks_[size - 1]) {
238 if (target - _ticks_[size - 1]
239 < epsilon * (1.0 + std::abs(static_cast< double >(_ticks_[size - 1])))) {
240 return size - 2;
241 }
242 if (_is_empirical) {
243 return size - 2;
244 } else
246 "more than last range (> " << _ticks_[size - 1] << ") for " << target << " in "
247 << *this << ":" << target - _ticks_[size - 1])
248 }
249
250 return pos_(target);
251 }
252
253 // second check if label contains an interval '[t1;t2]'
254 std::istringstream ii(std::string{label});
255 T_TICKS t2;
256 char c1;
257 char c2;
258 char c3;
259 if (!(ii >> c1 >> target >> c2 >> t2 >> c3)) {
260 GUM_ERROR(NotFound, "Bad label : " << label << " for " << *this)
261 }
262
263 // check if a char is in a string
264 const std::string s1{"[]()"};
265 if (const std::string s2{",;"}; s1.find(c1) == std::string::npos
266 || (s1.find(c3) == std::string::npos)
267 || (s2.find(c2) == std::string::npos)) {
268 GUM_ERROR(NotFound, "Bad syntax for interval : " << label << " for " << *this)
269 }
270
271 const Idx it1 = pos_(target);
272
273 if ((it1 + 1 >= _ticks_.size()) || (t2 != _ticks_[it1 + 1])) {
274 GUM_ERROR(NotFound, "Bad interval : " << label << " for " << *this)
275 }
276
277 return it1;
278 }
279
280 template < typename T_TICKS >
281 bool DiscretizedVariable< T_TICKS >::_checkSameDomain_(const gum::Variable& aRV) const {
282 // we can assume that aRV is a DiscretizedVariable
283 const auto& cv = static_cast< const DiscretizedVariable< T_TICKS >& >(aRV);
284 if (domainSize() != cv.domainSize()) { return false; }
285 return cv._ticks_ == _ticks_ && cv._is_empirical == _is_empirical;
286 }
287
288 template < typename T_TICKS >
289 Idx DiscretizedVariable< T_TICKS >::closestIndex(double val) const {
290 if (val <= _ticks_[0]) { return 0; }
291 if (val >= _ticks_[_ticks_.size() - 1]) { return _ticks_.size() - 2; }
292 return pos_(static_cast< T_TICKS >(val));
293 }
294
299 template < typename T_TICKS >
300 Size DiscretizedVariable< T_TICKS >::domainSize() const {
301 return (_ticks_.size() < 2) ? static_cast< Size >(0) : static_cast< Size >(_ticks_.size() - 1);
302 }
303
304 template < typename T_TICKS >
305 VarType DiscretizedVariable< T_TICKS >::varType() const {
306 return VarType::DISCRETIZED;
307 }
308
309 template < typename T_TICKS >
310 const T_TICKS& DiscretizedVariable< T_TICKS >::tick(Idx i) const {
311 if (i >= _ticks_.size()) {
312 GUM_ERROR(OutOfBounds, "There is no such tick " << i << " for " << *this << ".")
313 }
314
315 return _ticks_[i];
316 }
317
318 template < typename T_TICKS >
319 std::string DiscretizedVariable< T_TICKS >::domain() const {
320 std::string result = "<";
321
322 if (domainSize() > 0) {
323 result += label(0);
324
325 for (Idx i = 1; i < domainSize(); ++i) {
326 result += ",";
327 result += label(i);
328 }
329 }
330
331 result += ">";
332
333 return result;
334 }
335
336 template < typename T_TICKS >
337 const std::vector< T_TICKS >& DiscretizedVariable< T_TICKS >::ticks() const {
338 return this->_ticks_;
339 }
340
341 template < typename T_TICKS >
342 std::vector< double > DiscretizedVariable< T_TICKS >::ticksAsDoubles() const {
343 const std::size_t size = _ticks_.size();
344 std::vector< double > ticks(size);
345 for (auto i = static_cast< std::size_t >(0); i < size; ++i)
346 ticks[i] = static_cast< double >(_ticks_[i]);
347 return ticks;
348 }
349
350 template < typename T_TICKS >
351 std::string DiscretizedVariable< T_TICKS >::toFast() const {
352 std::string result = name();
353 if (_is_empirical) result += "+";
354 result += "[";
355 bool first = true;
356 for (const auto& t: _ticks_) {
357 if (!first) result += ",";
358 else first = false;
359 result += std::format("{}", t);
360 }
361 result += "]";
362 return result;
363 }
364
365 template < typename T_TICKS >
366 std::string DiscretizedVariable< T_TICKS >::stype() const {
367 return "Discretized";
368 }
369} /* namespace gum */
370
371#endif /* DOXYGEN_SHOULD_SKIP_THIS */
double epsilonFine() const noexcept
Exception : default in label.
Class for discretized random variable.
DiscretizedVariable(std::string_view aName, std::string_view aDesc)
Constructor.
bool isTick(const T_TICKS &aTick) const
void copy_(const DiscretizedVariable< T_TICKS > &aDRV)
make a copy
Idx pos_(const T_TICKS &target) const
search the class of target (internally use dichotomy_)
Idx index(std::string_view label) const override
from the label to its index in var.
A base class for discretized variables, independent of the ticks type.
Exception : the element we looked for cannot be found.
Exception : out of bound.
Base class for every random variable.
Definition variable.h:81
void copy_(const Variable &aRV)
protected copy
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
Size Idx
Type for indexes.
Definition types.h:79
GUM_SHARED_PUBLIC double randomProba()
Returns a random double between 0 and 1 included (i.e.
Useful macros for maths.
gum is the global namespace for all aGrUM entities
Definition agrum.h:46
bool isfinite(T arg)
Configuration & config()
A short name for Configuration::instance() : gum::config().epsilonStandard(). It is not inline so tha...
VarType
Definition variable.h:62
Contains useful methods for random stuff.