Medusa  1.1
Coordinate Free Mehless Method implementation
Utilities

Various utilities related to memory management, random, strings, numerics, spatial search, etc ... More...

Classes

class  mm::Grid< T, dimension, IndexType, IndexArrayT >
 Class representing a simple n-dimensional grid structure, which supports indexing and storing values. More...
 
class  mm::KDGrid< vec_t >
 Search structure over given d-dimensional box with given cell size. More...
 
class  mm::KDTree< vec_t >
 Class representing a static k-d tree data structure. More...
 
class  mm::KDTreeMutable< vec_t >
 A k-d tree data structure that supports dynamic insertions and lazy-removal. More...
 
struct  mm::kdtree_internal::PointCloud< vec_t >
 Helper class for KDTree with appropriate accessors containing a set of points. More...
 
class  mm::deep_copy_unique_ptr< T >
 Unique pointer with polymorphic deep copy semantics. More...
 
class  mm::Stopwatch
 A simple stopwatch class: time sections of code that execute repeatedly and get average execution time. More...
 
class  mm::Timer
 Simple timer class: add checkpoints throughout the code and measure execution time between them. More...
 
struct  mm::Pi< T >
 Value of Pi in type T. Usage: More...
 

Functions

std::string mm::mem2str (std::size_t bytes)
 Simple function to help format memory amounts for printing. More...
 
template<typename container_t >
std::size_t mm::mem_used (const container_t &v)
 Returns number of bytes the container uses in memory. More...
 
template<typename T >
int mm::iceil (T x)
 Ceils a floating point to an integer. More...
 
template<typename T >
int mm::ifloor (T x)
 Floors a floating point to an integer. More...
 
template<unsigned int exponent>
double mm::ipow (double base)
 Compile time integer power, returns base raised to power exponent. More...
 
template<>
double mm::ipow< 0 > (double)
 Compile time integer power (base case 0) More...
 
template<typename T >
mm::ipow (T b, int e)
 Compute non-negative integer power b^e. More...
 
template<typename T >
mm::ipowneg (T b, int e)
 Compute possibly negative integer power b^e. More...
 
template<typename T >
constexpr int mm::signum (T x)
 Signum function: determines a sign of a number x. More...
 
template<int dim>
bool mm::incrementCounter (Vec< int, dim > &counter, const Vec< int, dim > &limit)
 Increments a multi-dimensional counter with given limits. More...
 
template<int dim>
bool mm::incrementCounter (Vec< int, dim > &counter, const Vec< int, dim > &low, const Vec< int, dim > &high)
 Increments a multi-dimensional counter with given upper and lower limits. More...
 
template<int dim>
bool mm::incrementCyclicCounter (Vec< int, dim > &counter, const Vec< int, dim > &low, const Vec< int, dim > &high, const Vec< int, dim > &size)
 Increments a multi-dimensional counter with given upper and lower limits and global upper size, looping around to 0 if needed. More...
 
template<class scalar_t , int dim>
Range< Vec< scalar_t, dim > > mm::linspace (const Vec< scalar_t, dim > &beg, const Vec< scalar_t, dim > &end, const Vec< int, dim > &counts, const Vec< bool, dim > include_boundary=true)
 Multidimensional clone of Matlab's linspace function. More...
 
template<class scalar_t , int dim>
Range< Vec< scalar_t, dim > > mm::linspace (const Vec< scalar_t, dim > &beg, const Vec< scalar_t, dim > &end, const Vec< int, dim > &counts, bool include_boundary)
 Overload for bool argument of include_boundary. More...
 
template<typename scalar_t >
Range< scalar_tmm::linspace (scalar_t beg, scalar_t end, int count, bool include_boundary=true)
 Overload for 1 dimension. More...
 
template<typename function_t , typename input_t , typename output_t , bool verbose = false>
input_t mm::bisection (const function_t &f, input_t lo, input_t hi, output_t target=0.0, input_t tolerance=1e-4, int max_iter=40)
 Solves f(x) = target using bisection. More...
 
template<class T , class U >
std::ostream & std::operator<< (std::ostream &xx, const std::pair< T, U > &par)
 Output pairs as (1, 2). More...
 
template<class T , size_t N>
std::ostream & std::operator<< (std::ostream &xx, const std::array< T, N > &arr)
 Output arrays as [1, 2, 3]. More...
 
template<class T , class A >
std::ostream & std::operator<< (std::ostream &xx, const std::vector< T, A > &arr)
 Output vectors as [1, 2, 3]. More...
 
template<class T , class A >
std::ostream & std::operator<< (std::ostream &xx, const std::vector< std::vector< T, A >> &arr)
 Output nested vectors as [[1, 2]; [3, 4]]. More...
 
template<class... Args>
std::ostream & std::operator<< (std::ostream &os, const std::tuple< Args... > &t)
 Print a tuple as (1, 4.5, abc). More...
 
unsigned int mm::get_seed ()
 Return a random seed. More...
 
template<typename T >
mm::random_choice (const Range< T > &elements, const Range< double > &weights={}, bool normed=false)
 Randomly returns one of the specified elements with distribution according to given weights. More...
 
template<typename T , typename URNG >
mm::random_choice (const Range< T > &elements, const Range< double > &weights, bool normed, URNG &generator)
 Overload for custom generator. More...
 
std::vector< std::string > mm::split (const std::string &s, const std::string &delim)
 Splits string by delim, returning a vector of tokens (including empty). More...
 
std::string mm::join (const std::vector< std::string > &parts, const std::string &joiner)
 Joins a vector of strings back together. More...
 
template<typename container_t >
container_t & mm::sort (container_t &v)
 Sorts a container inplace. More...
 
template<typename container_t , typename predicate_t >
container_t & mm::sort (container_t &v, const predicate_t &pred)
 Sorts a container inplace according to ordering defined by pred. More...
 
template<typename container_t >
container_t mm::sorted (container_t v)
 Returns a sorted copy of container. More...
 
template<typename container_t , typename predicate_t >
container_t mm::sorted (container_t v, const predicate_t &pred)
 Returns a sorted copy of container ordered according to pred. More...
 
template<typename container_t , typename T >
container_t mm::pad (container_t container, T value)
 Pads a ragged array with given value. More...
 

Detailed Description

Various utilities related to memory management, random, strings, numerics, spatial search, etc ...

This section includes many print operators. It is out philosophy that any object should be quickly printable, which is why we included print operators for many common C++ types as well as for most custom types.

Spatial search structures such as k-d trees and k-d grids are also in this section.

Function Documentation

◆ bisection()

template<typename function_t , typename input_t , typename output_t , bool verbose = false>
input_t mm::bisection ( const function_t &  f,
input_t  lo,
input_t  hi,
output_t  target = 0.0,
input_t  tolerance = 1e-4,
int  max_iter = 40 
)

Solves f(x) = target using bisection.

Template Parameters
function_tFunction type, like std::function or lambda, that returns output_type.
input_tFloating point data type that support arithmetic operations.
output_tFloating point data type, such that mm::signum(output_t) can be called.
verboseReports approximation every iteration.
Parameters
fFunction mapping input_t -> output_t, for which to solve f(x) = target.
loLower bound of the interval, containing the solution.
hiUpper bound of the interval, containing the solution.
targetTarget value, default 0.
toleranceDesired accuracy of the solution, default 1e-4.
max_iterMaximal number of iterations.
Returns
The solution x, such that f(x) is approximately equal to target.
Examples
test/utils/numutils_test.cpp.

Definition at line 279 of file numutils.hpp.

◆ get_seed()

unsigned int mm::get_seed ( )
inline

Return a random seed.

The seed is truly random if available, otherwise it is the current system time.

Examples
test/utils/randutils_test.cpp.

Definition at line 25 of file randutils.hpp.

◆ iceil()

template<typename T >
int mm::iceil ( x)

Ceils a floating point to an integer.

Warning
This function might overflow if x is too large or return undefined results if x is not a finite number.
Examples
test/end2end/poisson_explicit.cpp, and test/utils/numutils_test.cpp.

Definition at line 27 of file numutils.hpp.

◆ ifloor()

template<typename T >
int mm::ifloor ( x)

Floors a floating point to an integer.

Warning
This function might overflow if x is too large or return undefined results if x is not a finite number.
Examples
test/utils/numutils_test.cpp.

Definition at line 36 of file numutils.hpp.

◆ incrementCounter() [1/2]

template<int dim>
bool mm::incrementCounter ( Vec< int, dim > &  counter,
const Vec< int, dim > &  limit 
)

Increments a multi-dimensional counter with given limits.

Parameters
counterA valid counter state.
limitLimit for each dimension of a counter.
Returns
true if an increment was performed and false otherwise. Repeated application of this function to counter with initial state 0 0 0 and limits 1 2 3 yields a sequence:
0 0 0 -> true
0 0 1 -> true
0 0 2 -> true
0 1 0 -> true
0 1 1 -> true
0 1 2 -> true
0 1 2 -> false
This is made so that it can be used nicely with a do {} while () loop, similarly to std::next_permutation.
Vec<int, 3> limit = {1, 2, 3};
Vec<int, 3> cnt; cnt.setZero();
std::vector<Vec<int, 3>> result;
do {
result.push_back(cnt);
} while (incrementCounter(cnt, limit));
Examples
test/utils/numutils_test.cpp.

Definition at line 120 of file numutils.hpp.

◆ incrementCounter() [2/2]

template<int dim>
bool mm::incrementCounter ( Vec< int, dim > &  counter,
const Vec< int, dim > &  low,
const Vec< int, dim > &  high 
)

Increments a multi-dimensional counter with given upper and lower limits.

Parameters
counterA valid counter state, which is modified.
lowLower limit for each dimension of a counter.
highUpper limit for each dimension of a counter. It must hold that low <= high in each component.
Returns
true if an increment was performed and false otherwise.
See also
incrementCounter

Definition at line 143 of file numutils.hpp.

◆ incrementCyclicCounter()

template<int dim>
bool mm::incrementCyclicCounter ( Vec< int, dim > &  counter,
const Vec< int, dim > &  low,
const Vec< int, dim > &  high,
const Vec< int, dim > &  size 
)

Increments a multi-dimensional counter with given upper and lower limits and global upper size, looping around to 0 if needed.

It need not hold that low <= high in each component.

Parameters
counterA valid counter state, which is modified.
lowLower limit for each dimension of a counter.
highUpper limit for each dimension of a counter.
sizeGlobal upper limit.
Returns
true if an increment was performed and false otherwise. Repeated application of this function to counter with limits 1 0 2 and 0 2 1 with size limit 3 3 3, starting from lower limit yields a sequence:
1 0 2 -> true
1 0 0 -> true
1 1 2 -> true
1 1 0 -> true
2 0 2 -> true
2 0 0 -> true
2 1 2 -> true
2 1 0 -> true
2 1 0 -> false
This is useful for cyclic iteration over multidimensional arrays.
Vec<int, 3> low = {1, 0, 2};
Vec<int, 3> high = {0, 2, 1};
Vec<int, 3> size = {3, 3, 3};
Vec<int, 3> cnt = low;
std::vector<Vec<int, 3>> result;
do {
result.push_back(cnt);
} while (incrementCyclicCounter(cnt, low, high, size));
See also
incrementCounter
Examples
test/utils/numutils_test.cpp.

Definition at line 182 of file numutils.hpp.

◆ ipow() [1/2]

template<unsigned int exponent>
double mm::ipow ( double  base)
inline

Compile time integer power, returns base raised to power exponent.

Examples
test/utils/numutils_test.cpp.

Definition at line 40 of file numutils.hpp.

◆ ipow() [2/2]

template<typename T >
T mm::ipow ( b,
int  e 
)
inline

Compute non-negative integer power b^e.

This function is usually faster than std::pow for e < 50 and matches the std::pow performance at approximately e = 100. For compile time constant e this function use ipow.

Definition at line 56 of file numutils.hpp.

◆ ipow< 0 >()

template<>
double mm::ipow< 0 > ( double  )
inline

Compile time integer power (base case 0)

Examples
test/utils/numutils_test.cpp.

Definition at line 46 of file numutils.hpp.

◆ ipowneg()

template<typename T >
T mm::ipowneg ( b,
int  e 
)
inline

Compute possibly negative integer power b^e.

This function is usually faster than std::pow for e < 50 and matches the std::pow performance at approximately e = 100.

Definition at line 72 of file numutils.hpp.

◆ join()

std::string mm::join ( const std::vector< std::string > &  parts,
const std::string &  joiner 
)

Joins a vector of strings back together.

Parameters
partsVector of strings.
joinerString to glue the parts with.
Examples
test/utils/stdtypesutils_test.cpp.

◆ linspace() [1/3]

template<class scalar_t , int dim>
Range<Vec<scalar_t, dim> > mm::linspace ( const Vec< scalar_t, dim > &  beg,
const Vec< scalar_t, dim > &  end,
const Vec< int, dim > &  counts,
bool  include_boundary 
)

Overload for bool argument of include_boundary.

Definition at line 238 of file numutils.hpp.

◆ linspace() [2/3]

template<class scalar_t , int dim>
Range<Vec<scalar_t, dim> > mm::linspace ( const Vec< scalar_t, dim > &  beg,
const Vec< scalar_t, dim > &  end,
const Vec< int, dim > &  counts,
const Vec< bool, dim include_boundary = true 
)

Multidimensional clone of Matlab's linspace function.

Uniformly discretizes cuboid given with beg and end points. Similar to numpy's linspace and Matlab's meshgrid.

Parameters
begBeginning of a cuboid.
endEnding of a cuboid.
countsHow many discretization points to use in each dimension.
include_boundaryFlag whether to include boundary of a cuboid in a given dimension.
Returns
Uniform discretization points of a domain with counts[i] points in dimension i. Instead of returning a n-dim matrix it returns it as a Range instead.
Examples
test/approximations/Monomials_test.cpp, and test/utils/numutils_test.cpp.

Definition at line 210 of file numutils.hpp.

◆ linspace() [3/3]

template<typename scalar_t >
Range<scalar_t> mm::linspace ( scalar_t  beg,
scalar_t  end,
int  count,
bool  include_boundary = true 
)

Overload for 1 dimension.

Definition at line 245 of file numutils.hpp.

◆ mem2str()

std::string mm::mem2str ( std::size_t  bytes)

Simple function to help format memory amounts for printing.

Takes in number of bytes and returns a human readable representation.

Examples
test/utils/memutils_test.cpp.

Definition at line 10 of file memutils.cpp.

◆ mem_used()

template<typename container_t >
std::size_t mm::mem_used ( const container_t &  v)

Returns number of bytes the container uses in memory.

The container must support size(). This does not count the memory that may be allocated by objects stored in the container. Also STL containers like vector may actually have more memory allocated than their size.

Definition at line 83 of file memutils.hpp.

◆ operator<<() [1/5]

template<class... Args>
std::ostream& std::operator<< ( std::ostream &  os,
const std::tuple< Args... > &  t 
)

Print a tuple as (1, 4.5, abc).

Definition at line 89 of file print.hpp.

◆ operator<<() [2/5]

template<class T , size_t N>
std::ostream& std::operator<< ( std::ostream &  xx,
const std::array< T, N > &  arr 
)

Output arrays as [1, 2, 3].

Definition at line 26 of file print.hpp.

◆ operator<<() [3/5]

template<class T , class U >
std::ostream& std::operator<< ( std::ostream &  xx,
const std::pair< T, U > &  par 
)

Output pairs as (1, 2).

Definition at line 20 of file print.hpp.

◆ operator<<() [4/5]

template<class T , class A >
std::ostream& std::operator<< ( std::ostream &  xx,
const std::vector< std::vector< T, A >> &  arr 
)

Output nested vectors as [[1, 2]; [3, 4]].

Definition at line 51 of file print.hpp.

◆ operator<<() [5/5]

template<class T , class A >
std::ostream& std::operator<< ( std::ostream &  xx,
const std::vector< T, A > &  arr 
)

Output vectors as [1, 2, 3].

Definition at line 38 of file print.hpp.

◆ pad()

template<typename container_t , typename T >
container_t mm::pad ( container_t  container,
value 
)

Pads a ragged array with given value.

Example:

pad({{1, 2}, {}, {9, 4, 2}}, -1); // return {{1, 2, -1}, {-1, -1, -1}, {9, 4, 2}}
Examples
test/utils/stdtypesutils_test.cpp.

Definition at line 78 of file stdtypesutils.hpp.

◆ random_choice() [1/2]

template<typename T , typename URNG >
T mm::random_choice ( const Range< T > &  elements,
const Range< double > &  weights,
bool  normed,
URNG &  generator 
)

Overload for custom generator.

See also
random_choice
Examples
test/utils/randutils_test.cpp.

Definition at line 59 of file randutils.hpp.

◆ random_choice() [2/2]

template<typename T >
T mm::random_choice ( const Range< T > &  elements,
const Range< double > &  weights = {},
bool  normed = false 
)

Randomly returns one of the specified elements with distribution according to given weights.

A std::mt19937 generator is created and seeded randomly with call to get_seed().

Parameters
elementsA pool of elements to choose from.
weightsWeights of the elements. If this argument is omitted all elements are assigned the same weights.
normedBoolean indicating that the weights are already normed and that additional computation is not necessary.
Exceptions
Assertionmight fail if thw weights are claimed to be normalized but are not.
See also
get_seed

Definition at line 51 of file randutils.hpp.

◆ signum()

template<typename T >
constexpr int mm::signum ( x)
inlineconstexpr

Signum function: determines a sign of a number x.

Parameters
xA number under inspection.
Returns
0 if x == 0, -1 if x is negative and +1 if x is positive

Definition at line 94 of file numutils.hpp.

◆ sort() [1/2]

◆ sort() [2/2]

template<typename container_t , typename predicate_t >
container_t& mm::sort ( container_t &  v,
const predicate_t &  pred 
)

Sorts a container inplace according to ordering defined by pred.

Definition at line 50 of file stdtypesutils.hpp.

◆ sorted() [1/2]

template<typename container_t >
container_t mm::sorted ( container_t  v)

Returns a sorted copy of container.

Examples
test/utils/stdtypesutils_test.cpp.

Definition at line 57 of file stdtypesutils.hpp.

◆ sorted() [2/2]

template<typename container_t , typename predicate_t >
container_t mm::sorted ( container_t  v,
const predicate_t &  pred 
)

Returns a sorted copy of container ordered according to pred.

Definition at line 64 of file stdtypesutils.hpp.

◆ split()

std::vector< std::string > mm::split ( const std::string &  s,
const std::string &  delim 
)

Splits string by delim, returning a vector of tokens (including empty).

split("a,b,c,", ","); // returns {"a", "b", "c", ""}
Examples
test/utils/stdtypesutils_test.cpp.

Definition at line 10 of file stdtypesutils.cpp.

mm::incrementCyclicCounter
bool incrementCyclicCounter(Vec< int, dim > &counter, const Vec< int, dim > &low, const Vec< int, dim > &high, const Vec< int, dim > &size)
Increments a multi-dimensional counter with given upper and lower limits and global upper size,...
Definition: numutils.hpp:182
mm::incrementCounter
bool incrementCounter(Vec< int, dim > &counter, const Vec< int, dim > &limit)
Increments a multi-dimensional counter with given limits.
Definition: numutils.hpp:120
mm::pad
container_t pad(container_t container, T value)
Pads a ragged array with given value.
Definition: stdtypesutils.hpp:78
mm::split
std::vector< std::string > split(const std::string &s, const std::string &delim)
Splits string by delim, returning a vector of tokens (including empty).
Definition: stdtypesutils.cpp:10