Other Tools

Timing Functions

A collection of tools to help measure timing of code.

Note

This file is part of Empirical, https://github.com/devosoft/Empirical

Copyright

Copyright (C) Michigan State University, MIT Software license; see doc/LICENSE.md

Date

2020.

Note

Status: BETA

Defines

EMP_FUNCTION_TIMER(TEST_FUN)

A simple macro to time how long it takes for a function to complete.

EMP_VOID_FUNCTION_TIMER(TEST_FUN)

A simple macro to time how long it takes for a function to complete.

namespace emp

If we are in emscripten, make sure to include the header.

Functions

double TimeFun(std::function<void()> test_fun)

A function timer that takes a functor an identifies how long it takes to complete when run.

Branch and Bound Solution States

Used as part of a branching solver to keep track of the current state.

Note

This file is part of Empirical, https://github.com/devosoft/Empirical

Copyright

Copyright (C) Michigan State University, MIT Software license; see doc/LICENSE.md

Date

2016-2021.

Note

Status: BETA

namespace emp

If we are in emscripten, make sure to include the header.

class SolveState
#include <SolveState.hpp>

Often in a branch-and-bound algorithm, we need to identify the sub-set of items that maximizes (or minimizes) an optimization metric. SolveState keeps track of the current state for which items have been locked in as “included” in the current branks, which have been “excluded”, and which are still “unknown” (still to be decided upon.) All tracking is performed with BitVectors for high efficiency.

Public Functions

SolveState(size_t state_size = 0)
SolveState(const SolveState &in)
~SolveState()
SolveState &operator=(const SolveState &in)

Set this SolveState to be identical to another.

size_t GetSize() const

How many items are being considered in the current SolveState?

bool IsIn(size_t id) const

Test if a particular item is going to be included for sure in the current solve state. (If it has been excluded -OR- is yet to be decided upon, false will be returned)

bool IsUnk(size_t id) const

Test if a particular item is yet to be decided upon in the current solve state. (If it has been excluded -OR- is included for sure, false will be returned)

bool IsOut(size_t id) const

Test if a particular item is going to be excluded for sure in the current solve state. (If it has been included -OR- is yet to be decided upon, false will be returned)

bool IsFinal() const

Test if all items have been decided upon (none are still in the “unknown” state)

size_t CountIn() const

How many items have been included for sure?

size_t CountUnk() const

How many items have yet to be decided upon (are “unknown”)

size_t CountOut() const

How many items have been excluded for sure.

const BitVector &GetInVector() const

Get the BitVector associated with which items have been included for sure.

const BitVector &GetUnkVector() const

Get the BitVector associated with which items have yet to be decided upon.

BitVector GetOutVector() const

Get the BitVector associated with which iterm have been excluded for sure.

int GetNextUnk(size_t prev_unk) const

Get the ID of the next unknown item.

void Include(size_t id)

Mark a specific item as to be included.

void Exclude(size_t id)

Mark a specific item as to be excluded.

void ForceExclude(size_t id)

Change our mind about a potentially included node (Be careful since many algorithms don’t requite this type of changes to be made.)

void IncludeSet(const BitVector &inc_set)

Include ALL of the items specified in the provided BitVector.

void ExcludeSet(const BitVector &inc_set)

Exclude ALL of the items specified in the provided BitVector.

Private Members

BitVector in_items

Items included for sure.

BitVector unk_items

Items yet to be decided on.

String Utilities

Simple functions to manipulate strings.

Note

This file is part of Empirical, https://github.com/devosoft/Empirical

Copyright

Copyright (C) Michigan State University, MIT Software license; see doc/LICENSE.md

Date

2016-2021.

Note

Status: RELEASE

namespace emp

If we are in emscripten, make sure to include the header.

Typedefs

using string_vec_t = emp::vector<std::string>

Functions

const std::string &empty_string()

Return a const reference to an empty string. This function is useful to implement other functions that need to return a const reference for efficiency, but also need a null response.

size_t count(const std::string &str, char c)

Count the number of times a specific character appears in a string (a clean shortcut to std::count)

std::string to_escaped_string(char value)

Convert a single chararcter to one that uses a proper escape sequence (in a string) if needed.

std::string to_escaped_string(const std::string &value)

Convert a full string to one that uses proper escape sequences, as needed.

std::string to_web_safe_string(const std::string &value)

Take a string and replace reserved HTML characters with character entities.

template<bool encode_space = false>
std::string url_encode(const std::string &value)

Returns url encoding of value. See https://en.wikipedia.org/wiki/Percent-encoding

template<bool decode_plus = false>
std::string url_decode(const std::string &str)

Returns url decoding of string. See https://en.wikipedia.org/wiki/Percent-encoding

template<typename T>
std::enable_if<!emp::IsIterable<T>::value, std::string>::type to_literal(const T &value)

Take a value and convert it to a C++-style literal.

std::string to_literal(char value)

Take a char and convert it to a C++-style literal.

std::string to_literal(const std::string &value)

Take a string or iterable and convert it to a C++-style literal.

char is_literal_char(const std::string &value)

Test if an input string is properly formated as a literal character.

char from_literal_char(const std::string &value)

Convert a literal character representation to an actual string. (i.e., ‘A’, ‘;’, or ‘

’)

char is_literal_string(const std::string &value)

Test if an input string is properly formated as a literal string.

std::string repeat(const std::string &value, const size_t n)

Concatenate n copies of a string.

std::string from_literal_string(const std::string &value)

Convert a literal string representation to an actual string.

std::string to_upper(std::string value)

Convert a string to all uppercase.

std::string to_lower(std::string value)

Convert a string to all lowercase.

std::string to_titlecase(std::string value)

Make first letter of each word upper case.

std::string to_roman_numeral(int val, const std::string &prefix = "")

Convert an integer to a roman numeral string.

bool is_whitespace(char test_char)

Determine if a character is whitespace.

bool is_upper_letter(char test_char)

Determine if a character is an uppercase letter.

bool is_lower_letter(char test_char)

Determine if a character is a lowercase letter.

bool is_letter(char test_char)

Determine if a character is a letter of any kind.

bool is_digit(char test_char)

Determine if a character is a digit.

bool is_alphanumeric(char test_char)

Determine if a character is a letter or digit.

bool is_idchar(char test_char)

Determine if a character is a letter, digit, or underscore.

bool is_one_of(char test_char, const std::string &char_set)

Determine if a character is in a set of characters (represented as a string)

bool is_composed_of(const std::string &test_str, const std::string &char_set)

Determine if a string is composed only of a set of characters (represented as a string)

bool has_whitespace(const std::string &test_str)

Determine if there is whitespace anywhere in a string.

bool has_upper_letter(const std::string &test_str)

Determine if there are any uppercase letters in a string.

bool has_lower_letter(const std::string &test_str)

Determine if there are any lowercase letters in a string.

bool has_letter(const std::string &test_str)

Determine if there are any letters in a string.

bool has_digit(const std::string &test_str)

Determine if there are any digits in a string.

bool is_digits(const std::string &test_str)

Determine if there are only digits in a string.

bool has_alphanumeric(const std::string &test_str)

Determine if there are any letters or digits anywhere in a string.

bool is_alphanumeric(const std::string &test_str)

Determine if there are any letters or digits anywhere in a string.

bool has_idchar(const std::string &test_str)

Determine if there are any letters, digit, or underscores anywhere in a string.

bool has_one_of(const std::string &test_str, const std::string &char_set)

Determine if a specified set of characters appears anywhere in a string.

bool is_valid(char)

If no functions are provided to is_valid(), always return false as base case.

template<typename ...FUNS>
bool is_valid(char test_char, std::function<bool(char)> fun1, FUNS... funs, )

Determine if a character passes any of the test functions provided.

template<typename ...FUNS>
bool is_valid(const std::string &test_str, FUNS... funs)

For a string to be valid, each character must pass at least one provided function.

std::string string_pop_fixed(std::string &in_string, std::size_t end_pos, size_t delim_size = 0)

Pop a segment from the beginning of a string as another string, shortening original.

std::string string_get_range(const std::string &in_string, std::size_t start_pos, std::size_t end_pos)

Get a segment from the beginning of a string as another string, leaving original untouched.

std::string string_pop(std::string &in_string, const char delim = ' ')

Remove a prefix of the input string (up to a specified delimeter) and return it. If the delimeter is not found, return the entire input string and clear it.

std::string string_get(const std::string &in_string, const char delim = ' ', size_t start_pos = 0)

Return a prefix of the input string (up to a specified delimeter), but do not modify it. If the delimeter is not found, return the entire input string.

std::string string_pop(std::string &in_string, const std::string &delim_set)

Remove a prefix of the input string (up to any of a specified set of delimeters) and return it. If the delimeter is not found, return the entire input string and clear it.

std::string string_get(const std::string &in_string, const std::string &delim_set, size_t start_pos = 0)

Return a prefix of the input string (up to any of a specified set of delimeters), but do not modify it. If the delimeter is not found, return the entire input string.

std::string string_pop_word(std::string &in_string)

Remove a prefix of a string, up to the first whitespace, and return it.

std::string string_get_word(const std::string &in_string, size_t start_pos = 0)

Return a prefix of a string, up to the first whitespace (do not modify the original string)

bool has_prefix(const std::string &in_string, const std::string &prefix)

Test if a string has a given prefix.

std::string string_pop_line(std::string &in_string)

Remove a prefix of a string, up to the first newline, and return it.

std::string string_get_line(const std::string &in_string, size_t start_pos = 0)

Return a prefix of a string, up to the first newline (do not modify the original string)

std::string left_justify(std::string &in_string)

Remove all whitespace at the beginning of a string. Return the whitespace removed.

void right_justify(std::string &in_string)

Remove all whitespace at the end of a string.

void justify(std::string &in_string)

Remove all whitespace at both the beginning and the end of a string.

void remove_chars(std::string &in_string, std::string chars)

Remove instances of characters from file.

void compress_whitespace(std::string &in_string)

Every time one or more whitespace characters appear replace them with a single space.

void remove_whitespace(std::string &in_string)

Remove all whitespace from anywhere within a string.

void remove_punctuation(std::string &in_string)

Remove all characters from a string except letters, numbers, and whitespace.

std::string slugify(const std::string &in_string)

Make a string safe(r)

std::string_view view_string(const std::string_view &str)

Provide a string_view on a given string.

std::string_view view_string(const std::string_view &str, size_t start)

Provide a string_view on a string from a given starting point.

std::string_view view_string(const std::string_view &str, size_t start, size_t npos)

Provide a string_view on a string from a starting point with a given size.

std::string_view view_string_front(const std::string_view &str, size_t npos)

Provide a string_view on a string from the beginning to a given size.

std::string_view view_string_back(const std::string_view &str, size_t npos)

Provide a string_view on a string from a starting point with a given size.

std::string_view view_string_range(const std::string_view &str, size_t start, size_t end)

Provide a string_view on a string from a starting point to an ending point.

std::string_view view_string_to(const std::string_view &in_string, const char delim, size_t start_pos = 0)

Return a view of the prefix of the input string up to a specified delimeter. If the delimeter is not found, return the entire input string.

void slice(const std::string_view &in_string, emp::vector<std::string> &out_set, const char delim = '\n', const size_t max_split = std::numeric_limits<size_t>::max())

Cut up a string based on the provided delimiter; fill them in to the provided vector.

Parameters
  • in_string: operand

  • out_set: destination

  • delim: delimiter to split on

  • max_split: defines the maximum number of splits

emp::vector<std::string> slice(const std::string_view &in_string, const char delim = '\n', const size_t max_split = std::numeric_limits<size_t>::max())

Slice a string without passing in result vector (may be less efficient).

Parameters
  • in_string: operand

  • delim: delimiter to split on

  • max_split: defines the maximum number of splits

void view_slices(const std::string_view &in_string, emp::vector<std::string_view> &out_set, char delim = '\n')

Create a set of string_views based on the provided delimiter; fill them in to the provided vector.

emp::vector<std::string_view> view_slices(const std::string_view &in_string, char delim = '\n')

Slice a string without passing in result vector (may be less efficient).

template<typename ...Ts>
std::string to_string(const Ts&... values)

This function does its very best to convert anything it gets to a string. Takes any number of arguments and returns a single string containing all of them concatenated. Any objects that can go through a stringstream, have a ToString() memember function, or are defined to be passed into emp::ToString(x) will work correctly.

template<typename T, size_t N>
std::string ToString(const emp::array<T, N> &container)

Setup emp::ToString to work on arrays.

template<typename T, typename ...Ts>
std::string ToString(const emp::vector<T, Ts...> &container)

Setup emp::ToString to work on vectors.

template<typename T>
T from_string(const std::string &str)

This function tries to convert a string into any type you’re looking for… You just need to specify the out type as the template argument.

template<typename ...Ts>
void from_string(const std::string &str, Ts&... args)

The from_string() function can also take multiple args instead of a return.

template<typename T>
emp::vector<T> from_strings(const emp::vector<std::string> &string_v)

The from_strings() function takes a vector of strings and convets them into a vector of the appropriate type.

template<typename T>
T from_string(std::string_view str)

This function tries to convert a string_view into any other type… You must need to specify the out type as the template argument.

template<typename T>
std::string join(const emp::vector<T> &v, std::string join_str)

This function returns the values in a vector as a string separated by a given delimeter.

Return

string of vector values

Parameters
  • v: a vector

  • join_str: delimeter

std::string to_english_list(const string_vec_t &strings)

Convert a vector of strings to an English list, such as “one, two, three, and four.”.

string_vec_t transform_strings(const string_vec_t &in_strings, std::function<std::string(const std::string&)> fun)

Transform all strings in a vector.

string_vec_t quote_strings(const string_vec_t &in_strings, const std::string quote = "'")

Put all strings provided in quotes (Like ‘this’), pre- and post-fixing another string if provided.

string_vec_t quote_strings(const string_vec_t &in_strings, const std::string open_quote, const std::string close_quote)

Pre-pend and post-pend specified sequences to all strings provided.

std::string to_quoted_list(const string_vec_t &in_strings, const std::string quote = "'")

Take a vector of strings, put them in quotes, and then transform it into an English list.

constexpr char ANSI_ESC()
std::string ANSI_Reset()
std::string ANSI_Bold()
std::string ANSI_Faint()
std::string ANSI_Italic()
std::string ANSI_Underline()
std::string ANSI_SlowBlink()
std::string ANSI_Blink()
std::string ANSI_Reverse()
std::string ANSI_Strike()
std::string ANSI_NoBold()
std::string ANSI_NoItalic()
std::string ANSI_NoUnderline()
std::string ANSI_NoBlink()
std::string ANSI_NoReverse()
std::string ANSI_Black()
std::string ANSI_Red()
std::string ANSI_Green()
std::string ANSI_Yellow()
std::string ANSI_Blue()
std::string ANSI_Magenta()
std::string ANSI_Cyan()
std::string ANSI_White()
std::string ANSI_DefaultColor()
std::string ANSI_BlackBG()
std::string ANSI_RedBG()
std::string ANSI_GreenBG()
std::string ANSI_YellowBG()
std::string ANSI_BlueBG()
std::string ANSI_MagentaBG()
std::string ANSI_CyanBG()
std::string ANSI_WhiteBG()
std::string ANSI_DefaultBGColor()
std::string ANSI_BrightBlack()
std::string ANSI_BrightRed()
std::string ANSI_BrightGreen()
std::string ANSI_BrightYellow()
std::string ANSI_BrightBlue()
std::string ANSI_BrightMagenta()
std::string ANSI_BrightCyan()
std::string ANSI_BrightWhite()
std::string ANSI_BrightBlackBG()
std::string ANSI_BrightRedBG()
std::string ANSI_BrightGreenBG()
std::string ANSI_BrightYellowBG()
std::string ANSI_BrightBlueBG()
std::string ANSI_BrightMagentaBG()
std::string ANSI_BrightCyanBG()
std::string ANSI_BrightWhiteBG()
std::string to_ansi_bold(const std::string &_in)

Make a string appear bold when printed to the command line.

std::string to_ansi_italic(const std::string &_in)

Make a string appear italics when printed to the command line.

std::string to_ansi_underline(const std::string &_in)

Make a string appear underline when printed to the command line.

std::string to_ansi_blink(const std::string &_in)

Make a string appear blink when printed to the command line.

std::string to_ansi_reverse(const std::string &_in)

Make a string appear reverse when printed to the command line.

template<typename ...Args>
std::string format_string(const std::string &format, Args... args)

Apply sprintf-like formatting to a string. See https://en.cppreference.com/w/cpp/io/c/fprintf. Adapted from https://stackoverflow.com/a/26221725.

Type Tracker

Track class types abstractly to dynamically call correct function overloads.

TypeTracker is a templated class that must be declared with all of the types that can possibly be tracked. For example:

emp::TypeTracker<int, std::string, double> tt;
Note

This file is part of Empirical, https://github.com/devosoft/Empirical

Copyright

Copyright (C) Michigan State University, MIT Software license; see doc/LICENSE.md

Date

2016-2018

Note

Status: BETA

…would create a TypeTracker that can manage the three types listed and convert back.

namespace emp

If we are in emscripten, make sure to include the header.

struct TrackedInfo_Base
#include <TypeTracker.hpp>

The proxy base class of any type to be tracked.

Subclassed by emp::TrackedInfo_Value< REAL_T, ID >

Public Functions

size_t GetTypeID() const noexcept = 0
~TrackedInfo_Base()
emp::Ptr<TrackedInfo_Base> Clone() const = 0
template<typename REAL_T, size_t ID>
struct TrackedInfo_Value : public emp::TrackedInfo_Base
#include <TypeTracker.hpp>

TrackedInfo_Value store both the real type and an ID for it (to be identified from the base class for each conversion back.)

Public Types

using real_t = REAL_T
using this_t = TrackedInfo_Value<REAL_T, ID>

Public Functions

TrackedInfo_Value(const REAL_T &in)
TrackedInfo_Value(REAL_T &&in)
TrackedInfo_Value(const TrackedInfo_Value&) = default
TrackedInfo_Value(TrackedInfo_Value&&) = default
TrackedInfo_Value &operator=(const TrackedInfo_Value&) = default
TrackedInfo_Value &operator=(TrackedInfo_Value&&) = default
size_t GetTypeID() const noexcept override
emp::Ptr<TrackedInfo_Base> Clone() const override

Build a copy of this TrackedInfo_Value; recipient is in charge of deletion.

Public Members

REAL_T value
struct TrackedVar
#include <TypeTracker.hpp>

The actual TrackedVar object that manages a Ptr to the value.

Public Functions

TrackedVar(emp::Ptr<TrackedInfo_Base> _ptr)
TrackedVar(const TrackedVar &_in)

Copy constructor; use judiciously since it copies the contents!

TrackedVar(TrackedVar &&_in)

Move constructor takes control of the pointer.

~TrackedVar()

Cleanup ptr on destruct.

TrackedVar &operator=(const TrackedVar &_in)

Move assignment hands over control of the pointer.

TrackedVar &operator=(TrackedVar &&_in)

Move assignment hands over control of the pointer.

size_t GetTypeID() const noexcept

Public Members

emp::Ptr<TrackedInfo_Base> ptr
template<typename ...TYPES>
class TypeTracker
#include <TypeTracker.hpp>

Dynamic functions that are indexed by parameter types; calls lookup the correct function to forward arguments into.

Public Types

using this_t = TypeTracker<TYPES...>
using wrap_t = TrackedInfo_Value<REAL_T, get_type_index<REAL_T, TYPES...>()>
using var_decoy = TrackedVar

var_decoy converts any variable into a TrackedVar (used to have correct number of vars)

Public Functions

TypeTracker() = default
TypeTracker(const TypeTracker&) = default
TypeTracker(TypeTracker&&) = default
TypeTracker &operator=(const TypeTracker&) = default
TypeTracker &operator=(TypeTracker&&) = default
~TypeTracker()
template<typename ...Ts>
this_t &AddFunction(std::function<void(Ts...)> fun)

Add a new std::function that this TypeTracker should call if the appropriate types are passed in.

template<typename ...Ts>
this_t &AddFunction(void (*fun)(Ts...))

Add a new function pointer that this TypeTracker should call if the appropriate types are passed in.

template<typename LAMBDA_T>
this_t &AddFunction(const LAMBDA_T &fun)

Add a new lambda function that this TypeTracker should call if the appropriate types are passed in.

template<typename ...Ts>
void RunFunction(Ts&&... args)

Run the appropriate function based on the argument types received.

template<typename ...Ts>
void operator()(Ts&&... args)

Call TypeTracker as a function (refers call to RunFunction)

Public Static Functions

constexpr size_t GetNumTypes()

How many types are we working with?

constexpr size_t GetNumCombos(size_t vals = 2)

How many combinations of V types are there?

constexpr size_t GetCumCombos(size_t vals = 2)

How many combinations are the of the given number of types OR FEWER?

template<typename T>
constexpr size_t GetID()

Each type should have a unique ID.

template<typename T1, typename T2, typename ...Ts>
constexpr size_t GetID()

Each set of types should have an ID unique within that number of types.

template<typename ...Ts>
constexpr size_t GetComboID()

A ComboID should be unique across all size combinations.

size_t GetTrackedID(const TrackedVar &tt)

A Tracked ID is simply the unique ID of the type being tracked.

template<typename ...Ts>
size_t GetTrackedID(const TrackedVar &tt1, const TrackedVar &tt2, const Ts&... ARGS)

Or set of types being tracked…

template<typename ...Ts>
constexpr size_t GetTrackedComboID(const Ts&... ARGS)

A tracked COMBO ID, is an ID for this combination of types, unique among all possible type combinations. Consistent with GetComboID with the same underlying types.

template<typename REAL_T>
TrackedVar Convert(const REAL_T &val)

Convert an input value into a TrackedInfo_Value maintaining the value (universal version)

template<typename TEST_T>
bool IsType(TrackedVar &tt)

Test if the tracked type is TEST_T.

template<typename REAL_T>
REAL_T ToType(TrackedVar &tt)

Convert the tracked type back to REAL_T. Assert that this is type safe!

template<typename OUT_T>
OUT_T Cast(TrackedVar &tt)

Cast the tracked type to OUT_T. Try to do so even if NOT original type!

Protected Attributes

std::unordered_map<size_t, Ptr<emp::GenericFunction>> fun_map

fun_map is a hash table that maps a set of inputs to the appropriate function.