aGrUM 2.3.2
a C++ library for (probabilistic) graphical models
Utilities

About aGrUM utilities. More...

Collaboration diagram for Utilities:

Topics

 Math
 All the maths you'll need.
 Configuration
 About aGrUM configuration.
 Smart Pointers
 RefPtr are a replacement for the usual pointers: they keep track of the number of "smart" pointers pointing to a given element.
template<typename T1, typename T2>
using gum::forbidden_type = typename std::enable_if< !std::is_same< T1, T2 >::value, int >::type
 Forbidden_type<T1,T2> return the "int" type if T1 and T2 are of the same type, else nothing.
bool gum::Memcmp (const void *const in_, const void *const out_, unsigned long size)
 Cross-platform replacement for memcmp.
void gum::_atexit_ ()
 Used for debug purpose.
template<typename T1, typename T2>
ostream & std::operator<< (ostream &stream, const pair< T1, T2 > &val)
 'std::cout<<' operator for pairs.
template<typename T0, typename... T>
std::ostream & std::operator<< (std::ostream &os, const std::tuple< T0, T... > &t)
 'std::cout<<' operator for vectors.
template<typename T>
ostream & std::operator<< (ostream &stream, const vector< T > &val)
 'std::cout<<' operator for vectors.
template<typename T>
bool std::hasUniqueElts (std::vector< T > const &x)
 

Idx gum::randomValue (const Size max=2)
 Returns a random Idx between 0 and max-1 included.
double gum::randomProba ()
 Returns a random double between 0 and 1 included (i.e.
template<typename GUM_SCALAR>
std::vector< GUM_SCALAR > gum::randomDistribution (Size n)
 Return a random discrete distribution.
unsigned int gum::randomGeneratorSeed ()
 Returns the aGrUM's seed used by the std::generators.
unsigned int gum::currentRandomGeneratorValue ()
 returns the current generator's value
void gum::initRandom (unsigned int seed=0)
 Initialize random generator seed.
std::mt19937 & gum::randomGenerator ()
 define a random_engine with correct seed
std::string gum::getUniqueFileName ()
 Returns a path to a unique file name.
bool gum::endsWith (std::string const &value, std::string const &ending)
 Returns true if value ends with ending.
std::vector< std::string > gum::split (const std::string &orig, const std::string &delimiter)
 Split str using the delimiter.
std::string gum::replace (const std::string &s, const std::string &val, const std::string &new_val)
 not usable for gcc 4.8 std::vector<std::string> split( const std::string& orig, const std::string& delimiter ) {
bool gum::isIntegerWithResult (const std::string &val, int *res)
 return true is a string contains an integer value
bool gum::isNumericalWithResult (const std::string &val, double *res)
 return true is a string contains a numerical (double) value
std::string gum::toLower (std::string str)
 Returns the lowercase version of str.
bool gum::isInteger (const std::string &val)
 return true is a string contains an integer value
bool gum::isNumerical (const std::string &val)
 return true is a string contains a numerical (double) value
void gum::ltrim (std::string &s)
 trim from start (in place)
void gum::rtrim (std::string &s)
 trim from end (in place)
void gum::trim (std::string &s)
 trim from both ends (in place)
std::string gum::trim_copy (const std::string &s)
 trim from both ends (copying)
std::string gum::remove_newline (const std::string &s)
 remove all newlines in a string
template<typename T>
std::string gum::compact_tostr (T value)
 Returns a path to a unique file name.

Detailed Description

About aGrUM utilities.

Typedef Documentation

◆ forbidden_type

template<typename T1, typename T2>
using gum::forbidden_type = typename std::enable_if< !std::is_same< T1, T2 >::value, int >::type

Forbidden_type<T1,T2> return the "int" type if T1 and T2 are of the same type, else nothing.

Use it as a guard in template specification :

// Creates a template except if T is int or char
template<T,forbidden_type<T,int> =0,forbidden_type<T,char> =0> // ...
Parameters
T1The type to test for.
T2The expected type.

Definition at line 143 of file utils_misc.h.

Function Documentation

◆ _atexit_()

void gum::_atexit_ ( )

Used for debug purpose.

Definition at line 67 of file utils_misc.cpp.

67 {
68#ifdef GUM_DEBUG_MODE
69 gum::__debug__::_atexit_();
70#endif
71 }

◆ compact_tostr()

template<typename T>
std::string gum::compact_tostr ( T value)
inline

Returns a path to a unique file name.

Returns
Returns a path to a unique file name.

Definition at line 161 of file utils_string.h.

161 {
162 std::ostringstream s;
163 s.precision(7);
164 s << value;
165 return s.str();
166 }

◆ currentRandomGeneratorValue()

INLINE unsigned int gum::currentRandomGeneratorValue ( )

returns the current generator's value

Definition at line 85 of file utils_random_inl.h.

85{ return _rand_namespace_::generator()(); }
std::mt19937 & generator()

References gum::_rand_namespace_::generator().

Here is the call graph for this function:

◆ endsWith()

bool gum::endsWith ( std::string const & value,
std::string const & ending )

Returns true if value ends with ending.

Returns
Returns true if value ends with ending.

Definition at line 83 of file utils_string.cpp.

83 {
84 if (ending.size() > value.size()) return false;
85 return std::equal(ending.rbegin(), ending.rend(), value.rbegin());
86 }

Referenced by gum::prm::o3prm::O3NameSolver< GUM_SCALAR >::resolveClass(), gum::prm::o3prm::O3NameSolver< GUM_SCALAR >::resolveClassElement(), gum::prm::o3prm::O3NameSolver< GUM_SCALAR >::resolveInterface(), gum::prm::o3prm::O3NameSolver< GUM_SCALAR >::resolveSlotType(), and gum::prm::o3prm::O3NameSolver< GUM_SCALAR >::resolveType().

Here is the caller graph for this function:

◆ getUniqueFileName()

std::string gum::getUniqueFileName ( )

Returns a path to a unique file name.

Returns
Returns a path to a unique file name.

Definition at line 63 of file utils_string.cpp.

63 {
64 // Get the temporary directory path
65 std::filesystem::path temp_dir = std::filesystem::temp_directory_path();
66
67 // Generate a unique file name using a timestamp and a random number
68 auto now = std::chrono::system_clock::now();
69 auto timestamp
70 = std::chrono::duration_cast< std::chrono::milliseconds >(now.time_since_epoch()).count();
71
72 auto dis = gum::randomValue(1000);
73
74 std::string filename
75 = "tempfile_" + std::to_string(timestamp) + "_" + std::to_string(dis) + ".tmp";
76
77 // Combine the directory path and the file name
78 std::filesystem::path temp_file_path = temp_dir / filename;
79
80 return temp_file_path.string();
81 }
Idx randomValue(const Size max=2)
Returns a random Idx between 0 and max-1 included.

References randomValue().

Referenced by gum::credal::CredalNet< GUM_SCALAR >::_H2Vlrs_().

Here is the call graph for this function:
Here is the caller graph for this function:

◆ hasUniqueElts()

template<typename T>
bool std::hasUniqueElts ( std::vector< T > const & x)

check if a vector consists in unique values (no duplicate).

Template Parameters
TThe vector's elements type.
Parameters
xthe vector
Returns
Returns true if the vector has no duplicate.

Definition at line 108 of file utils_misc_tpl.h.

108 {
109 if (x.size() <= 1) return true;
110 if (x.size() == 2) return x[0] != x[1];
111
112 auto refless = [](T const* l, T const* r) { return *l < *r; };
113 auto refeq = [](T const* l, T const* r) { return *l == *r; };
114
115 std::vector< T const* > vp;
116 vp.reserve(x.size());
117 for (size_t i = 0; i < x.size(); ++i)
118 vp.push_back(&x[i]);
119 sort(vp.begin(), vp.end(), refless); // O(N log N)
120 // if no adjacent pair (vp_n,vp_n+1) has *vp_n == *vp_n+1
121 return std::adjacent_find(vp.begin(), vp.end(), refeq) == vp.end();
122 }

◆ initRandom()

INLINE void gum::initRandom ( unsigned int seed = 0)

Initialize random generator seed.

Definition at line 77 of file utils_random_inl.h.

77 {
78 if (seed == 0) seed = (unsigned int)std::chrono::system_clock::now().time_since_epoch().count();
79 std::seed_seq seq{seed + 1, seed + 2, seed + 3, seed + 4, seed + 5};
81 }

References gum::_rand_namespace_::generator().

Here is the call graph for this function:

◆ isInteger()

INLINE bool gum::isInteger ( const std::string & val)

return true is a string contains an integer value

Parameters
sA string
Returns
true if s exactly contains an int (s can start with "-" or "+")

Definition at line 95 of file utils_string_inl.h.

95{ return isIntegerWithResult(val, nullptr); }
bool isIntegerWithResult(const std::string &val, int *res)
return true is a string contains an integer value

References isIntegerWithResult().

Referenced by fastVariable().

Here is the call graph for this function:
Here is the caller graph for this function:

◆ isIntegerWithResult()

bool gum::isIntegerWithResult ( const std::string & val,
int * res )

return true is a string contains an integer value

Parameters
sA string
Returns
true if s exactly contains an int (s can start with "-" or "+")

Definition at line 124 of file utils_string.cpp.

124 {
125 if (val.empty()) return false;
126 std::size_t pos = 0;
127 if ((val[0] == '+') || (val[0] == '-')) { pos = 1; }
128
129 if (val.find_first_not_of("0123456789", pos) != std::string::npos) return false;
130
131 if (res != nullptr) {
132 const char* p = (val[0] == '+') ? 1 + val.c_str() : val.c_str();
133 *res = std::stoi(p);
134 }
135
136 return true;
137 }

Referenced by isInteger().

Here is the caller graph for this function:

◆ isNumerical()

INLINE bool gum::isNumerical ( const std::string & val)

return true is a string contains a numerical (double) value

Parameters
sA string
Returns
true if s exactly contains a double

Definition at line 98 of file utils_string_inl.h.

98{ return isNumericalWithResult(val, nullptr); }
bool isNumericalWithResult(const std::string &val, double *res)
return true is a string contains a numerical (double) value

References isNumericalWithResult().

Referenced by fastVariable().

Here is the call graph for this function:
Here is the caller graph for this function:

◆ isNumericalWithResult()

bool gum::isNumericalWithResult ( const std::string & val,
double * res )

return true is a string contains a numerical (double) value

Parameters
sA string *
Returns
true if s exactly contains a double

Definition at line 139 of file utils_string.cpp.

139 {
140 char* endptr = nullptr;
141 const char* str = val.c_str();
142 double d = std::strtod(str, &endptr);
143
144 if (*endptr != '\0' || endptr == str) return false;
145 if (res != nullptr) *res = d;
146
147 return true;
148 }

Referenced by isNumerical().

Here is the caller graph for this function:

◆ ltrim()

INLINE void gum::ltrim ( std::string & s)

trim from start (in place)

Parameters
sA string

Definition at line 65 of file utils_string_inl.h.

65 {
66 s.erase(s.begin(),
67 std::find_if(s.begin(), s.end(), [](unsigned char ch) { return !std::isspace(ch); }));
68 }

Referenced by trim().

Here is the caller graph for this function:

◆ Memcmp()

bool gum::Memcmp ( const void *const in_,
const void *const out_,
unsigned long size )

Cross-platform replacement for memcmp.

Parameters
in_A pointer to the block of memory to copy.
out_A pointer to the block of memory receiving copy.
sizeNumber of bytes to copy.
Returns
Returns true if OK.

Definition at line 57 of file utils_misc.cpp.

57 {
58 unsigned char* in = (unsigned char*)in_;
59 unsigned char* out = (unsigned char*)out_;
60
61 for (unsigned long i = 0; i < size; ++i)
62 if (*(in++) != *(out++)) return false;
63
64 return true;
65 }

◆ operator<<() [1/3]

template<typename T1, typename T2>
ostream & std::operator<< ( ostream & stream,
const pair< T1, T2 > & val )

'std::cout<<' operator for pairs.

Template Parameters
T1The pair's first's type.
T2The pair's second's type.
Parameters
streamThe stream to print to.
valThe pair to print to stream.
Returns
Returns stream.

Definition at line 78 of file utils_misc_tpl.h.

78 {
79 stream << "(" << val.first << "," << val.second << ")";
80 return stream;
81 }

◆ operator<<() [2/3]

template<typename T>
ostream & std::operator<< ( ostream & stream,
const vector< T > & val )

'std::cout<<' operator for vectors.

Template Parameters
TThe vector's elements type.
Parameters
streamThe stream to print to.
valThe std::vector to print to stream.
Returns
Returns stream.

Definition at line 62 of file utils_misc_tpl.h.

62 {
63 bool deja = false;
64 stream << "[";
65
66 for (const auto& v: val) {
67 if (deja) stream << " , ";
68 else deja = true;
69 stream << v;
70 }
71
72 stream << "]";
73
74 return stream;
75 }

◆ operator<<() [3/3]

template<typename T0, typename... T>
std::ostream & std::operator<< ( std::ostream & os,
const std::tuple< T0, T... > & t )

'std::cout<<' operator for vectors.

Parameters
streamThe stream to print to.
Template Parameters
tThe std::tuple
Parameters
valThe std::vector to print to stream.
Returns
Returns stream.

Definition at line 100 of file utils_misc_tpl.h.

100 {
101 char quote = (std::is_convertible< T0, std::string >::value) ? '"' : 0;
102 os << '(' << quote << std::get< 0 >(t) << quote;
104 return os << ')';
105 }
static std::enable_if<(N< sizeof...(T))>::type print(std::ostream &os, const std::tuple< T... > &t)

References std::_auxiliary_print_tuple_< N >::print().

Here is the call graph for this function:

◆ randomDistribution()

template<typename GUM_SCALAR>
std::vector< GUM_SCALAR > gum::randomDistribution ( Size n)

Return a random discrete distribution.

Parameters
nThe number of modalities for the ditribution.
Returns
Return a random discrete distribution.
Template Parameters
GUM_SCALARThe type used for representing probabilities.

Definition at line 54 of file utils_random_tpl.h.

54 {
55 if (n < 2) n = 2;
56
57 // using sort method for uniformly distributed distributions
58 // https://doi.org/10.1016/0377-2217(82)90161-8
59 std::vector< GUM_SCALAR > v(n + 1);
60 std::vector< GUM_SCALAR > res(n);
61 v[0] = (GUM_SCALAR)0.0;
62 v[n] = (GUM_SCALAR)1.0;
63 for (Idx i = 1; i < n; i++) {
64 v[i] = (GUM_SCALAR)randomProba();
65 }
66 std::sort(v.begin(), v.end());
67
68 for (Idx i = 0; i < n; i++) {
69 res[i] = v[i + 1] - v[i];
70 }
71
72 return res;
73 }
Size Idx
Type for indexes.
Definition types.h:79
double randomProba()
Returns a random double between 0 and 1 included (i.e.

References randomProba().

Referenced by gum::Tensor< GUM_SCALAR >::randomCPT(), and gum::Tensor< GUM_SCALAR >::randomDistribution().

Here is the call graph for this function:
Here is the caller graph for this function:

◆ randomGenerator()

INLINE std::mt19937 & gum::randomGenerator ( )

define a random_engine with correct seed

Definition at line 96 of file utils_random_inl.h.

References gum::_rand_namespace_::generator().

Referenced by gum::MultiDimFunctionGraphGenerator::_generateVarPos_(), gum::Dirichlet::operator()(), gum::Dirichlet::operator()(), and gum::learning::BNDatabaseGenerator< GUM_SCALAR >::setRandomVarOrder().

Here is the call graph for this function:
Here is the caller graph for this function:

◆ randomGeneratorSeed()

INLINE unsigned int gum::randomGeneratorSeed ( )

Returns the aGrUM's seed used by the std::generators.

Returns
Returns the aGrUM's seed used by the std::generators.

Definition at line 89 of file utils_random_inl.h.

89 {
90 return (unsigned int)((GUM_RANDOMSEED == 0)
91 ? std::chrono::system_clock::now().time_since_epoch().count()
92 : GUM_RANDOMSEED);
93 }

◆ randomProba()

INLINE double gum::randomProba ( )

Returns a random double between 0 and 1 included (i.e.

a proba).

Returns
Returns a random double between 0 and 1 included (i.e. a proba).

Definition at line 71 of file utils_random_inl.h.

71 {
72 std::uniform_real_distribution uni_real(0.0, 1.0);
73 return uni_real(_rand_namespace_::generator());
74 }

References gum::_rand_namespace_::generator().

Referenced by gum::MultiDimFunctionGraphGenerator::_createLeaf_(), gum::prm::ClusteredLayerGenerator< GUM_SCALAR >::_generateClassDag_(), gum::prm::LayerGenerator< GUM_SCALAR >::_generateClassDag_(), gum::prm::ClusteredLayerGenerator< GUM_SCALAR >::_generateSystem_(), gum::prm::LayerGenerator< GUM_SCALAR >::_generateSystem_(), gum::MCBayesNetGenerator< GUM_SCALAR, SimpleCPTGenerator, SimpleCPTDisturber >::disturbReducCPT(), gum::Tensor< GUM_SCALAR >::draw(), gum::learning::BNDatabaseGenerator< GUM_SCALAR >::drawSamples(), gum::MultiDimFunctionGraphGenerator::generate(), gum::SimpleBayesNetGenerator< GUM_SCALAR, ICPTGenerator >::generateBN(), gum::InfluenceDiagramGenerator< GUM_SCALAR >::generateID(), gum::SimpleUTGenerator::generateUT(), gum::SimpleUTGenerator::generateUT(), gum::FMDPSimulator::perform(), gum::Tensor< GUM_SCALAR >::random(), randomDistribution(), and gum::E_GreedyDecider::stateOptimalPolicy().

Here is the call graph for this function:
Here is the caller graph for this function:

◆ randomValue()

INLINE Idx gum::randomValue ( const Size max = 2)

Returns a random Idx between 0 and max-1 included.

Returns
Returns a random idx between 0 and max-1 included . By default, max=2

Definition at line 65 of file utils_random_inl.h.

65 {
66 std::uniform_int_distribution< Idx > uni_int(0, int(max) - 1);
67 return uni_int(_rand_namespace_::generator());
68 }

References gum::_rand_namespace_::generator().

Referenced by gum::MCBayesNetGenerator< GUM_SCALAR, ICPTGenerator, ICPTDisturber >::_chooseCloseNodes_(), gum::MCBayesNetGenerator< GUM_SCALAR, ICPTGenerator, ICPTDisturber >::_createPartTree_(), gum::MCBayesNetGenerator< GUM_SCALAR, ICPTGenerator, ICPTDisturber >::_createTree_(), gum::prm::ClusteredLayerGenerator< GUM_SCALAR >::_generateClass_(), gum::prm::ClusteredLayerGenerator< GUM_SCALAR >::_generateClassDag_(), gum::prm::LayerGenerator< GUM_SCALAR >::_generateClassDag_(), gum::prm::LayerGenerator< GUM_SCALAR >::_generateClasses_(), gum::prm::ClusteredLayerGenerator< GUM_SCALAR >::_generateCluster_(), gum::prm::ClusteredLayerGenerator< GUM_SCALAR >::_generateSystem_(), gum::prm::LayerGenerator< GUM_SCALAR >::_generateSystem_(), gum::credal::CNMonteCarloSampling< GUM_SCALAR, BNInferenceEngine >::_verticesSampling_(), gum::IBayesNetGenerator< GUM_SCALAR, SimpleCPTGenerator >::fillCPT(), gum::MultiDimFunctionGraphGenerator::generate(), gum::SimpleBayesNetGenerator< GUM_SCALAR, ICPTGenerator >::generateBN(), gum::InfluenceDiagramGenerator< GUM_SCALAR >::generateID(), getUniqueFileName(), gum::credal::CNLoopyPropagation< GUM_SCALAR >::makeInferenceByRandomOrder_(), gum::GibbsOperator< GUM_SCALAR >::nextSample(), gum::AbstractSimulator::randomState_(), gum::SDYNA::takeAction(), and gum::IncrementalGraphLearner< AttributeSelection, isScalar >::updateNode_().

Here is the call graph for this function:
Here is the caller graph for this function:

◆ remove_newline()

INLINE std::string gum::remove_newline ( const std::string & s)

remove all newlines in a string

Parameters
sA string
Returns
the new string with no newline

Definition at line 87 of file utils_string_inl.h.

87 {
88 std::string res{s};
89 std::erase(res, '\n');
90 std::erase(res, '\r');
91 return res;
92 }

Referenced by gum::BayesNet< GUM_SCALAR >::fastPrototype(), and gum::InfluenceDiagram< GUM_SCALAR >::fastPrototype().

Here is the caller graph for this function:

◆ replace()

std::string gum::replace ( const std::string & s,
const std::string & val,
const std::string & new_val )

not usable for gcc 4.8 std::vector<std::string> split( const std::string& orig, const std::string& delimiter ) {

Replace val by new_val in s.

std::regex rgx( delimiter );

std::sregex_token_iterator first{begin( orig ), end( orig ), rgx, -1}, last;

return {first, last}; }

Parameters
sA string.
valThe value to replace in s.
new_valThe new value to replace val in s.
Returns
A new string with val replaced by new_val.

Definition at line 112 of file utils_string.cpp.

112 {
113 auto retVal = s;
114 auto pos = retVal.find(val);
115 while (pos != std::string::npos) {
116 std::stringstream sBuff;
117 sBuff << s.substr(0, pos) << new_val << s.substr(pos + val.size(), std::string::npos);
118 retVal = sBuff.str();
119 pos = retVal.find(val);
120 }
121 return retVal;
122 }

Referenced by gum::prm::o3prm::O3prmReader< GUM_SCALAR >::_clean_().

Here is the caller graph for this function:

◆ rtrim()

INLINE void gum::rtrim ( std::string & s)

trim from end (in place)

Parameters
sA string

Definition at line 72 of file utils_string_inl.h.

72 {
73 s.erase(std::find_if(s.rbegin(), s.rend(), [](unsigned char ch) { return !std::isspace(ch); })
74 .base(),
75 s.end());
76 }

Referenced by trim().

Here is the caller graph for this function:

◆ split()

std::vector< std::string > gum::split ( const std::string & orig,
const std::string & delimiter )

Split str using the delimiter.

Parameters
origsearched string
delimiterstring
Returns
Vector of splitted strings

Definition at line 88 of file utils_string.cpp.

88 {
89 std::vector< std::string > tokens;
90 size_t prev = 0, pos = 0;
91 do {
92 pos = str.find(delim, prev);
93 if (pos == std::string::npos) pos = str.length();
94 std::string token = str.substr(prev, pos - prev);
95 if (!token.empty()) tokens.push_back(token);
96 prev = pos + delim.length();
97 } while (pos < str.length() && prev < str.length());
98 return tokens;
99 }

Referenced by gum::BayesNet< GUM_SCALAR >::fastPrototype(), gum::InfluenceDiagram< GUM_SCALAR >::fastPrototype(), and fastVariable().

Here is the caller graph for this function:

◆ toLower()

INLINE std::string gum::toLower ( std::string str)

Returns the lowercase version of str.

Returns
Returns the lowercase version of str.

Definition at line 58 of file utils_string_inl.h.

58 {
59 std::transform(str.begin(), str.end(), str.begin(), ::tolower);
60 return str;
61 }

Referenced by gum::AggregatorDecomposition< GUM_SCALAR >::addAggregator_(), and gum::prm::PRMAggregate< GUM_SCALAR >::str2enum().

Here is the caller graph for this function:

◆ trim()

INLINE void gum::trim ( std::string & s)

trim from both ends (in place)

Parameters
sA string

Definition at line 80 of file utils_string_inl.h.

80 {
81 ltrim(s);
82 rtrim(s);
83 }
void ltrim(std::string &s)
trim from start (in place)
void rtrim(std::string &s)
trim from end (in place)

References ltrim(), and rtrim().

Referenced by fastVariable(), and trim_copy().

Here is the call graph for this function:
Here is the caller graph for this function:

◆ trim_copy()

INLINE std::string gum::trim_copy ( const std::string & s)

trim from both ends (copying)

Parameters
sA string
Returns
the new string trimmed from start

Definition at line 102 of file utils_string_inl.h.

102 {
103 std::string res{s};
104 trim(res);
105 return res;
106 }
void trim(std::string &s)
trim from both ends (in place)

References trim().

Here is the call graph for this function: