Empirical – A library of tools for scientific software development¶
Authors: | Charles Ofria, Emily Dolson, Alex Lalejini, Jacob Fenton |
---|---|
GitHub: | https://github.com/devosoft/Empirical |
Empirical is a library of tools for scientific software development with an emphasis on being able to build web interfaces using Mozilla’s Emscripten compiler. The project goal is to improve the accessibility and reproducibility of the computational research.
Emprical is a C++ project though it uses Python for development infrastructure.
The developer documentation is for contributing to the Emscripten project and the user documentation is for those wanting to incorporate the Emscripten library into their own projects.
Contents:
General Purpose Debugging Tools¶
Empirical vectors and arrays¶
Empirical contains of intelligent versions of STL vectors and arrays that will warn you if you make common errors, but otherwise behave identically to the STL version. Most importantly, they will detect attempts to index to out-of-bounds locations and throw an error. These features are critical for writing code that will be compiled to Javascript with Emscripten, because Valgrind doesn’t run on Javascript. They also save a lot of debugging time when writing native C++ code.
“But wait,” you might say, “surely all of these additional checks slow down your code!” This is true when you compile in debug mode (the default). However, when you compile with the -DNDEBUG flag, these objects are directly replaced with their STL equivalent, removing any slowdown. That way, you can get all the debugging benefits while you’re writing your program, but all the speed benefits when you’re actually using it.
emp::vector Example¶
#include "Empirical/source/base/vector.h"
emp::vector<int> vec({1,2,3});
// You can treat this just like an std::vector<int>
emp::array Example¶
#include "Empirical/source/base/array.h"
emp::array<int, 3> array({1,2,3});
// You can treat this just like an std::array<int, 3>
Empirical asserts¶
These asserts function similarly to normal asserts, with a few important additional features:
- If compiled with Emscripten they will provide pop-up alerts when run in a web browser.
- emp_assert can take additional arguments. If the assert is triggered, those extra arguments will be evaluated and printed.
- if NDEBUG -or- EMP_NDEBUG is defined, the expression in emp_assert() is not evaluated.
- if EMP_TDEBUG is defined, emp_assert() goes into test mode and records failures, but does not abort. (useful for unit tests of asserts)
Example:
#include "Empirical/source/base/assert.h"
int a = 6;
emp_assert(a==5, a);
When compiled in debug mode (i.e. without the -DNDEBUG flag), this will trigger an assertion error and print the value of a.
emp_assert API (base/assert.h)¶
-
emp_assert
(...)¶ Require a specified condition to be true. If it is false, immediately halt execution. Note: If NDEBUG is defined, emp_assert() will not do anything.
-
emp_emscripten_assert
(...)¶ Require a specified condition to be true if this program was compiled to Javascript with Emscripten. Note: If NDEBUG is defined, emp_emscripten_assert() will not do anything.
Empirical pointers¶
Ptr objects behave as normal pointers under most conditions. However, if a program is compiled with EMP_TRACK_MEM set, then these pointers perform extra tests to ensure that they point to valid memory and that memory is freed before pointers are released.
If you trip an assert, you can re-do the run a track a specific pointer by defining EMP_ABORT_PTR_NEW or EMP_ABORT_PTR_DELETE to the ID of the pointer in question. This will allow you to track the pointer more easily in a debugger.
Example:
#include "Empirical/source/base/Ptr.h"
emp::Ptr<int> int_ptr;
int_ptr.New(123456); // Store the value 123456 in int_ptr.
std::cout << "*int_ptr = " << *int_ptr << std::endl;
int_ptr.Delete();
Data Collection and Recording Tools¶
Empirical includes a variety of tools for gathering and recording data. The core of these tools is the DataNode class. DataNodes are containers that you can pass as much data as you like into. When DataNodes are built, they can be given various modifiers (specified as template arguments) which control how much information they will collect about the data they are passed. For instance, the data::Current modifier gives the DataNode the power to remember the last value it was passed, whereas the data::Stats modifier keeps track of a variety of statisticcs about the distribution of data that the node has been passed. Except where otherwise noted, modifiers can be combined freely. Some also have dependencies on simpler modifiers. On the whole, DataNodes are designed to be as light-weight as possible while still keeping track of the desired information.
DataNodes that accept the same type of data and have the same modifiers can be grouped together using a DataManager.
The DataInterface class provides a general interface for interacting with DataNodes of any type. This is useful in cases where you have a collection of different types of DataNodes and want to operate on them without casting.
The DataFile class provides an interface for recording data at regular intervals. This data can come from DataNodes, the return of a specified function, or the contents of a specified variable. DataFiles are useful for collecting data over the course of a computational experiment.
Data Tools API¶
DataNodes¶
DataNode objects track a specific type of data over the course of a run.
Collection: New data can be pushed or pulled. Add(VAL… v) pushes data to a node AddDatum(VAL v) pushes just one datum, but can be used as an action for a signal.
- 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
Process: What should happen on Reset() ?
- Trigger an action to process the prior update’s data stored.
- Clear all data.
- Send data to a stream (or stats automatically have a stream that, if non-null data is sent to?)
-
template <typename VAL_TYPE, emp::data... MODS>
template<>
classDataNodeModule
<VAL_TYPE, data::Current, MODS...> : public emp::DataNodeModule<VAL_TYPE, MODS...>¶ - #include <DataNode.h>
== data::Current == This module lets you track the current (i.e. most recently added) value
Public Functions
-
DataNodeModule
()¶
-
const VAL_TYPE &
GetCurrent
() const¶ Return the current (most recently added) value.
Protected Types
-
template<>
usingparent_t
= DataNodeModule<VAL_TYPE, MODS...>¶
-
template<>
usingbase_t
= DataNodeModule<VAL_TYPE>¶
Protected Attributes
-
VAL_TYPE
cur_val
¶ Most recent value passed to this node.
-
-
template <typename VAL_TYPE, emp::data... MODS>
template<>
classDataNodeModule
<VAL_TYPE, data::Info, MODS...> : public emp::DataNodeModule<VAL_TYPE, MODS...>¶ - #include <DataNode.h>
== data::Info == This module adds information such as a name, description, and keyword for this node.
Public Functions
-
DataNodeModule
()¶
Protected Types
-
template<>
usingparent_t
= DataNodeModule<VAL_TYPE, MODS...>¶
-
-
template <typename VAL_TYPE, emp::data... MODS>
template<>
classDataNodeModule
<VAL_TYPE, data::Log, MODS...> : public emp::DataNodeModule<VAL_TYPE, MODS...>¶ - #include <DataNode.h>
== data::Log == This module lets you log all of the values that have been added since the last re-set
Public Functions
-
DataNodeModule
()
-
void
PrintDebug
(std::ostream &os = std::cout) Print debug information (useful for figuring out which modifiers you included)
-
-
template <typename VAL_TYPE, emp::data... MODS>
template<>
classDataNodeModule
<VAL_TYPE, data::Archive, MODS...> : public emp::DataNodeModule<VAL_TYPE, MODS...>¶ - #include <DataNode.h>
== data::Archive == This module keeps track of historical values in addition to those added since the last re-set. Every time Reset() is called, all values that have been added since the previous time Reset() are stored in a vector in the archive.
Public Functions
-
DataNodeModule
()
-
const auto &
GetArchive
() const¶ Get all data ever added to this DataNode. Returns a vector of vectors; each vector contains all data from a single time point (interval between resets)
-
const emp::vector<VAL_TYPE> &
GetData
(size_t update) const¶ Get a vector of all data that was added during the.
- Parameters
update
: ‘th interval between resets.
-
const emp::vector<VAL_TYPE> &
GetData
() const¶ Get a vector of all data that has been added since the last reset.
-
size_t
GetResetCount
() const¶ Get the number of time intervals recorded in this DataNode. Note that this is one more than the number of times it has been reset
-
void
Reset
()¶ Reset this DataNode, starting a new grouping of values in the archive. Resetting is useful for tracking data from different time points, such as per update or generation.
-
void
PrintDebug
(std::ostream &os = std::cout) Print debug information (useful for figuring out which modifiers you included)
-
-
template <typename VAL_TYPE, emp::data... MODS>
template<>
classDataNodeModule
<VAL_TYPE, data::Range, MODS...> : public emp::DataNodeModule<VAL_TYPE, MODS...>¶ - #include <DataNode.h>
== data::Range == This module allows this DataNode to store information (min, max, mean, count, and total) about the distribution of the values that have been added since the last call to Reset().
Public Functions
-
DataNodeModule
()
-
void
AddDatum
(const VAL_TYPE &val) Add.
- Parameters
val
: to this DataNode
-
void
Reset
() Reset DataNode, setting the running calucluations of total, min, mean, and max to 0.
-
void
PrintDebug
(std::ostream &os = std::cout) Print debug information (useful for figuring out which modifiers you included)
-
-
template <typename VAL_TYPE, emp::data... MODS>
template<>
classDataNodeModule
<VAL_TYPE, data::FullRange, MODS...> : public emp::DataNodeModule<VAL_TYPE, MODS...>¶ - #include <DataNode.h>
== data::FullRange == This module makes the DataNode store a history of distributional information measured by data::Range beteen calls to Reset(). Series of historical values are stored in vectors (except mean, which is calculated from total and count).
Public Functions
-
DataNodeModule
()
-
double
GetTotal
(size_t update) const¶ Get the sum of all values added to this DataNode during the.
- Parameters
update
: specified.
-
double
GetMean
(size_t update) const¶ Get the mean of all values added to this DataNode during the.
- Parameters
update
: specified.
-
double
GetMin
(size_t update) const¶ Get the minimum of all values added to this DataNode during the.
- Parameters
update
: specified.
-
double
GetMax
(size_t update) const¶ Get the maximum of all values added to this DataNode during the.
- Parameters
update
: specified.
-
size_t
GetResetCount
() const¶ Get the number of time intervals recorded in this DataNode. Note that this is one more than the number of times it has been reset
-
void
Reset
() Store the current range statistics in the archive and reset for a new interval.
-
void
PrintDebug
(std::ostream &os = std::cout) Print debug information (useful for figuring out which modifiers you included)
-
-
template <typename VAL_TYPE, emp::data... MODS>
template<>
classDataNodeModule
<VAL_TYPE, data::Stats, MODS...> : public emp::DataNodeModule<VAL_TYPE, MODS...>¶ - #include <DataNode.h>
== data::Stats == Note: These statistics are calculated with the assumption that the data this node has recieved is the entire population of measurements we’re interested in, not a sample.
Note 2: Kurtosis is calculated using Snedecor and Cochran (1967)’s formula. A perfect normal distribution has a kurtosis of 0.
Public Functions
-
DataNodeModule
()
-
double
GetVariance
() const¶ Get the variance (squared deviation from the mean) of values added since the last reset.
-
double
GetStandardDeviation
() const¶ Get the standard deviation of values added since the last reset.
-
double
GetSkew
() const¶ Get the skewness of values added since the last reset. This measurement tells you about the shape of the distribution. For a unimodal distribution, negative skew means that the distribution has a longer/thicker tail to the left. Positive skew means that ths distribution has a longer/thicker tail to the right.
-
double
GetKurtosis
() const¶ Get the kurtosis of the values added since the last reset. This is another measurement that describes the shape of the distribution. High kurtosis means that there is more data in the tails of the distribution (i.e. the tails are “heavier”), whereas low kurtosis means that there is less data in the tails. We use Snedecor and Cochran (1967)’s formula to calculate kurtosis. Under this formula, a normal distribution has kurtosis of 0.
-
void
AddDatum
(const VAL_TYPE &val) Add.
- Parameters
val
: to this DataNode
-
void
Reset
() Reset this node (resets current stats to 0)
-
void
PrintDebug
(std::ostream &os = std::cout) Print debug information (useful for figuring out which modifiers you included)
-
-
template <typename VAL_TYPE, emp::data... MODS>
template<>
classDataNodeModule
<VAL_TYPE, data::Histogram, MODS...> : public emp::DataNodeModule<VAL_TYPE, MODS...>¶ - #include <DataNode.h>
== data::Histogram == Make the DataNode track a histogram of values observed since the last reset.
Public Functions
-
DataNodeModule
()
-
VAL_TYPE
GetHistMin
() const¶ Returns the minimum value this histogram is capable of containing (i.e. the minimum value for the first bin)
-
VAL_TYPE
GetHistMax
() const¶ Returns the maximum value this histogram is capable of containing (i.e. the maximum value for the last bin)
-
size_t
GetHistCount
(size_t bin_id) const¶ Return the count of items in the.
- Parameters
bin_id
: ‘th bin of the histogram
-
double
GetHistWidth
(size_t bin_id) const¶ Return the width of the.
- Parameters
bin_id
: ‘th bin of the histogram
-
const emp::vector<size_t> &
GetHistCounts
() const¶ Return a vector containing the count of items in each bin of the histogram.
-
emp::vector<double>
GetBinMins
() const¶ Return a vector containing the lowest value allowed in each bin.
-
void
SetupBins
(VAL_TYPE _min, VAL_TYPE _max, size_t num_bins)¶ Sets up the ranges of values that go in each bin of the histogram.
- Parameters
_min
: - the lowest value allowed in the histogram_max
: - the largest value allowed in the histogramnum_bins
: - The number of bins the histogram should have. The distance between min and max will be easily divided among this many bins.
-
void
AddDatum
(const VAL_TYPE &val) Add.
- Parameters
val
: to the DataNode
-
void
Reset
() Reset the DataNode (empties the historgram)
-
void
PrintDebug
(std::ostream &os = std::cout) Print debug information (useful for figuring out which modifiers you included)
-
-
template <typename VAL_TYPE, emp::data... MODS>
template<>
classDataNodeModule
<VAL_TYPE, data::Pull, MODS...> : public emp::DataNodeModule<VAL_TYPE, MODS...>¶ - #include <DataNode.h>
== data::Pull == This module makes it possible to give the DataNode a function that it can call to calculate new values or sets of values that it will then track. These functions are called every time the PullData method is called on this node, and the values they return are measured as specified by the other modules in this node.
Protected Types
-
template<>
usingparent_t
= DataNodeModule<VAL_TYPE, MODS...>¶
-
template<>
usingbase_t
= DataNodeModule<VAL_TYPE>¶
Protected Functions
-
void
PullData_impl
()¶
-
template<>
-
namespace
emp
¶ If we are in emscripten, make sure to include the header.
This file contains extra analysis tools to use with systematics managers that have non-null DATA_TYPES.
- 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
- 2018
This file contains functions for adding additional data files to Worlds.
- 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
- 2018
Typedefs
-
using
emp::ModPack = typedef emp::IntPack<(int) MODS...>
A shortcut for converting DataNode mod ID’s to IntPacks.
-
using
emp::DataMonitor = typedef DataNode<T, data::Current, data::Info, data::Range, data::Stats, MODS...>
A node that stores data about the most recent value it recieved, as well as the distribution (min, max, count, total, and mean) of values it has recieved since the last reset. It also allows you to give it a name, description, and keyword.
-
using
emp::DataLog = typedef DataNode<T, data::Current, data::Info, data::Log, MODS...>
A node that stores data about the most recent value it recieved, as well as all values it has recieved since the last reset. It also allows you to give it a name, description, and keyword.
-
using
emp::DataArchive = typedef DataNode<T, data::Info, data::Archive, data::FullRange, MODS...>
A node that stores all data it recieves in an archive (vector of vectors). The inner vectors are groups of data that were recieved between resets. This node also keeps a record of the min, max, count, and total of each vector, so you don’t have to recalculate it later. Additionally, it allows you to give it a name, description, and keyword.
Enums
-
enum
data
¶ A set of modifiers are available do describe DataNode.
Values:
-
Current
¶ Track most recent value.
-
Info
¶ Include information (name, keyword, description) for each instance.
-
Log
¶ Track all values since last Reset()
-
Archive
¶ Track Log + ALL values over time (with purge options)
-
Range
¶ Track min, max, mean, total.
-
Histogram
¶ Keep a full histogram.
-
Pull
¶ Enable data collection on request.
Various signals are possible:
-
SignalReset
¶ Include a signal that triggers BEFORE Reset() to process data.
-
SignalData
¶ Include a signal when new data is added (as a group)
-
SignalDatum
¶ Include a signal when each datum is added.
-
SignalRange
¶ Include a signal for data in a range.
-
SignalLimits
¶ Include a signal for data OUTSIDE a range.
-
UNKNOWN
¶ Unknown modifier; will trigger error.
-
-
template <emp::data MOD>
structDataModInfo
¶ - #include <DataNode.h>
Extra info about data modules that we need to know before actually building this DataNode. (for now, just REQUISITES for each module.)
Public Types
-
template<>
usingreqs
= ModPack<>¶
-
template<>
-
template <>
template<>
structDataModInfo
<data::Archive> - #include <DataNode.h>
Public Types
-
template<>
usingreqs
= ModPack<data::Log>
-
template<>
-
template <>
template<>
structDataModInfo
<data::FullRange> - #include <DataNode.h>
Public Types
-
template<>
usingreqs
= ModPack<data::Range>
-
template<>
-
template <>
template<>
structDataModInfo
<data::Stats> - #include <DataNode.h>
Public Types
-
template<>
usingreqs
= ModPack<data::Range>
-
template<>
-
template <emp::data CUR_MOD, emp::data... MODS>
template<>
structDataModuleRequisiteAdd
<CUR_MOD, MODS...>¶ - #include <DataNode.h>
Public Types
-
template<>
usingnext_type
= typename DataModuleRequisiteAdd<MODS...>::type¶
-
template<>
usingthis_req
= typename DataModInfo<CUR_MOD>::reqs¶
-
using
emp::DataModuleRequisiteAdd< CUR_MOD, MODS... >::type = typename next_type::template append<this_req>
-
template<>
-
template <>
template<>
structDataModuleRequisiteAdd
<>¶ - #include <DataNode.h>
Public Types
-
template<>
usingtype
= IntPack<>¶
-
template<>
-
template <typename VAL_TYPE, emp::data... MODS>
classDataNode
: public emp::DataNode_Interface<VAL_TYPE, FormatDataMods<MODS...>::sorted>¶ - #include <DataNode.h>
Public Functions
-
void
Add
()¶
-
template <typename... Ts>
voidAdd
(const VAL_TYPE &val, const Ts&... extras)¶ Methods to provide new data.
-
void
PullData
()¶ Method to retrieve new data.
-
void
Reset
()¶ Methods to reset data.
-
void
PrintCurrent
(std::ostream &os = std::cout) const¶ Methods to Print the templated values that a DataNode can produce.
Private Types
-
template<>
usingparent_t
= DataNode_Interface<VAL_TYPE, typename FormatDataMods<MODS...>::sorted>¶
-
void
-
template <typename VAL_TYPE, int... IMODS>
template<>
classDataNode_Interface
<VAL_TYPE, IntPack<IMODS...>> : public emp::DataNodeModule<VAL_TYPE, (emp::data) IMODS...>¶ - #include <DataNode.h>
Outermost interface to all DataNode modules.
Private Types
-
template<>
usingparent_t
= DataNodeModule<VAL_TYPE, (emp::data) IMODS...>¶
-
template<>
-
template <typename VAL_TYPE, emp::data... MODS>
classDataNodeModule
¶ - #include <DataNode.h>
Generic form of DataNodeModule (should never be used; trigger error!)
Public Functions
-
DataNodeModule
()
-
-
template <typename VAL_TYPE>
template<>
classDataNodeModule
<VAL_TYPE>¶ - #include <DataNode.h>
Base form of DataNodeModule (available in ALL data nodes.)
Public Types
-
template<>
usingvalue_t
= VAL_TYPE¶
Public Functions
-
DataNodeModule
()
-
size_t
GetCount
() const¶ Return the number of values that have been added to this node since the last reset.
-
size_t
GetResetCount
() const If reset count not tracked, always return 0. If any modifier causes history to be saved, it will override this function and indicate how much history is stored.
-
double
GetTotal
() const
-
double
GetMean
() const
-
double
GetMin
() const
-
double
GetMax
() const
-
double
GetVariance
() const¶
-
double
GetStandardDeviation
() const¶
-
double
GetSkew
() const¶
-
double
GetKurtosis
() const¶
-
void
AddDatum
(const VAL_TYPE &val)
-
void
Reset
()
-
void
PrintDebug
(std::ostream &os = std::cout) Print debug information (useful for figuring out which modifiers you included)
Protected Functions
-
void
PullData_impl
()¶
-
template<>
-
template <typename VAL_TYPE, emp::data... MODS>
template<>
classDataNodeModule
<VAL_TYPE, data::Archive, MODS...> : public emp::DataNodeModule<VAL_TYPE, MODS...> - #include <DataNode.h>
== data::Archive == This module keeps track of historical values in addition to those added since the last re-set. Every time Reset() is called, all values that have been added since the previous time Reset() are stored in a vector in the archive.
Public Functions
-
DataNodeModule
()
-
const auto &
GetArchive
() const¶ Get all data ever added to this DataNode. Returns a vector of vectors; each vector contains all data from a single time point (interval between resets)
-
const emp::vector<VAL_TYPE> &
GetData
(size_t update) const¶ Get a vector of all data that was added during the.
- Parameters
update
: ‘th interval between resets.
-
const emp::vector<VAL_TYPE> &
GetData
() const Get a vector of all data that has been added since the last reset.
-
size_t
GetResetCount
() const Get the number of time intervals recorded in this DataNode. Note that this is one more than the number of times it has been reset
-
void
Reset
() Reset this DataNode, starting a new grouping of values in the archive. Resetting is useful for tracking data from different time points, such as per update or generation.
-
void
PrintDebug
(std::ostream &os = std::cout) Print debug information (useful for figuring out which modifiers you included)
Protected Types
-
template<>
usingthis_t
= DataNodeModule<VAL_TYPE, data::Archive, MODS...>
-
template<>
usingparent_t
= DataNodeModule<VAL_TYPE, MODS...>
-
template<>
usingbase_t
= DataNodeModule<VAL_TYPE>
-
-
template <typename VAL_TYPE, emp::data... MODS>
template<>
classDataNodeModule
<VAL_TYPE, data::Current, MODS...> : public emp::DataNodeModule<VAL_TYPE, MODS...> - #include <DataNode.h>
== data::Current == This module lets you track the current (i.e. most recently added) value
Public Functions
-
DataNodeModule
()
-
const VAL_TYPE &
GetCurrent
() const¶ Return the current (most recently added) value.
-
void
AddDatum
(const VAL_TYPE &val) Add.
- Parameters
val
: to this DataNode
-
void
PrintDebug
(std::ostream &os = std::cout) Print debug information (useful for figuring out which modifiers you included)
Protected Types
-
template<>
usingthis_t
= DataNodeModule<VAL_TYPE, data::Current, MODS...>
-
template<>
usingparent_t
= DataNodeModule<VAL_TYPE, MODS...>
-
template<>
usingbase_t
= DataNodeModule<VAL_TYPE>
Protected Attributes
-
VAL_TYPE
cur_val
¶ Most recent value passed to this node.
-
-
template <typename VAL_TYPE, emp::data... MODS>
template<>
classDataNodeModule
<VAL_TYPE, data::FullRange, MODS...> : public emp::DataNodeModule<VAL_TYPE, MODS...> - #include <DataNode.h>
== data::FullRange == This module makes the DataNode store a history of distributional information measured by data::Range beteen calls to Reset(). Series of historical values are stored in vectors (except mean, which is calculated from total and count).
Public Functions
-
DataNodeModule
()
-
double
GetTotal
() const Get the sum of all values added to this DataNode since the last reset.
-
double
GetMean
() const Get the mean of all values added to this DataNode since the last reset.
-
double
GetMin
() const Get the minimum of all values added to this DataNode since the last reset.
-
double
GetMax
() const Get the maximum of all values added to this DataNode since the last reset.
-
double
GetTotal
(size_t update) const¶ Get the sum of all values added to this DataNode during the.
- Parameters
update
: specified.
-
double
GetMean
(size_t update) const¶ Get the mean of all values added to this DataNode during the.
- Parameters
update
: specified.
-
double
GetMin
(size_t update) const¶ Get the minimum of all values added to this DataNode during the.
- Parameters
update
: specified.
-
double
GetMax
(size_t update) const¶ Get the maximum of all values added to this DataNode during the.
- Parameters
update
: specified.
-
size_t
GetResetCount
() const Get the number of time intervals recorded in this DataNode. Note that this is one more than the number of times it has been reset
-
void
Reset
() Store the current range statistics in the archive and reset for a new interval.
-
void
PrintDebug
(std::ostream &os = std::cout) Print debug information (useful for figuring out which modifiers you included)
Protected Types
-
template<>
usingthis_t
= DataNodeModule<VAL_TYPE, data::FullRange, MODS...>
-
template<>
usingparent_t
= DataNodeModule<VAL_TYPE, MODS...>
-
template<>
usingbase_t
= DataNodeModule<VAL_TYPE>
-
-
template <typename VAL_TYPE, emp::data... MODS>
template<>
classDataNodeModule
<VAL_TYPE, data::Histogram, MODS...> : public emp::DataNodeModule<VAL_TYPE, MODS...> - #include <DataNode.h>
== data::Histogram == Make the DataNode track a histogram of values observed since the last reset.
Public Functions
-
DataNodeModule
()
-
VAL_TYPE
GetHistMin
() const¶ Returns the minimum value this histogram is capable of containing (i.e. the minimum value for the first bin)
-
VAL_TYPE
GetHistMax
() const¶ Returns the maximum value this histogram is capable of containing (i.e. the maximum value for the last bin)
-
size_t
GetHistCount
(size_t bin_id) const¶ Return the count of items in the.
- Parameters
bin_id
: ‘th bin of the histogram
-
double
GetHistWidth
(size_t bin_id) const¶ Return the width of the.
- Parameters
bin_id
: ‘th bin of the histogram
-
const emp::vector<size_t> &
GetHistCounts
() const¶ Return a vector containing the count of items in each bin of the histogram.
-
emp::vector<double>
GetBinMins
() const¶ Return a vector containing the lowest value allowed in each bin.
-
void
SetupBins
(VAL_TYPE _min, VAL_TYPE _max, size_t num_bins)¶ Sets up the ranges of values that go in each bin of the histogram.
- Parameters
_min
: - the lowest value allowed in the histogram_max
: - the largest value allowed in the histogramnum_bins
: - The number of bins the histogram should have. The distance between min and max will be easily divided among this many bins.
-
void
AddDatum
(const VAL_TYPE &val) Add.
- Parameters
val
: to the DataNode
-
void
Reset
() Reset the DataNode (empties the historgram)
-
void
PrintDebug
(std::ostream &os = std::cout) Print debug information (useful for figuring out which modifiers you included)
Protected Types
-
template<>
usingthis_t
= DataNodeModule<VAL_TYPE, data::Histogram, MODS...>
-
template<>
usingparent_t
= DataNodeModule<VAL_TYPE, MODS...>
-
template<>
usingbase_t
= DataNodeModule<VAL_TYPE>
-
-
template <typename VAL_TYPE, emp::data... MODS>
template<>
classDataNodeModule
<VAL_TYPE, data::Info, MODS...> : public emp::DataNodeModule<VAL_TYPE, MODS...> - #include <DataNode.h>
== data::Info == This module adds information such as a name, description, and keyword for this node.
Public Functions
-
DataNodeModule
()
-
void
SetInfo
(const std::string &_n, const std::string &_d = "", const std::string &_k = "") Set this DataNode’s name to.
- Parameters
_ndescription
: to_dand
: keyword to_k
:
-
void
PrintDebug
(std::ostream &os = std::cout) Print debug information (useful for figuring out which modifiers you included)
Protected Types
-
template<>
usingparent_t
= DataNodeModule<VAL_TYPE, MODS...>
-
-
template <typename VAL_TYPE, emp::data... MODS>
template<>
classDataNodeModule
<VAL_TYPE, data::Log, MODS...> : public emp::DataNodeModule<VAL_TYPE, MODS...> - #include <DataNode.h>
== data::Log == This module lets you log all of the values that have been added since the last re-set
Public Functions
-
DataNodeModule
()
-
const emp::vector<VAL_TYPE> &
GetData
() const Get a vector of all data added since the last reset.
-
void
AddDatum
(const VAL_TYPE &val) Add.
- Parameters
val
: to this DataNode
-
void
Reset
() Reset this DataNode (clear the current log of data)
-
void
PrintDebug
(std::ostream &os = std::cout) Print debug information (useful for figuring out which modifiers you included)
Protected Types
-
template<>
usingthis_t
= DataNodeModule<VAL_TYPE, data::Log, MODS...>
-
template<>
usingparent_t
= DataNodeModule<VAL_TYPE, MODS...>
-
template<>
usingbase_t
= DataNodeModule<VAL_TYPE>
-
-
template <typename VAL_TYPE, emp::data... MODS>
template<>
classDataNodeModule
<VAL_TYPE, data::Pull, MODS...> : public emp::DataNodeModule<VAL_TYPE, MODS...> - #include <DataNode.h>
== data::Pull == This module makes it possible to give the DataNode a function that it can call to calculate new values or sets of values that it will then track. These functions are called every time the PullData method is called on this node, and the values they return are measured as specified by the other modules in this node.
Public Functions
-
DataNodeModule
()
-
void
AddPull
(const std::function<VAL_TYPE()> &fun)
-
void
PrintDebug
(std::ostream &os = std::cout)
Protected Types
-
template<>
usingthis_t
= DataNodeModule<VAL_TYPE, data::Pull, MODS...>
-
template<>
usingparent_t
= DataNodeModule<VAL_TYPE, MODS...>
-
template<>
usingbase_t
= DataNodeModule<VAL_TYPE>
Protected Functions
-
void
PullData_impl
()
-
-
template <typename VAL_TYPE, emp::data... MODS>
template<>
classDataNodeModule
<VAL_TYPE, data::Range, MODS...> : public emp::DataNodeModule<VAL_TYPE, MODS...> - #include <DataNode.h>
== data::Range == This module allows this DataNode to store information (min, max, mean, count, and total) about the distribution of the values that have been added since the last call to Reset().
Public Functions
-
DataNodeModule
()
-
double
GetTotal
() const Get the sum of all values added to this DataNode since the last reset.
-
double
GetMean
() const Get the mean of all values added to this DataNode since the last reset.
-
double
GetMin
() const Get the min of all values added to this DataNode since the last reset.
-
double
GetMax
() const Get the max of all values added to this DataNode since the last reset.
-
void
AddDatum
(const VAL_TYPE &val) Add.
- Parameters
val
: to this DataNode
-
void
Reset
() Reset DataNode, setting the running calucluations of total, min, mean, and max to 0.
-
void
PrintDebug
(std::ostream &os = std::cout) Print debug information (useful for figuring out which modifiers you included)
Protected Types
-
template<>
usingthis_t
= DataNodeModule<VAL_TYPE, data::Range, MODS...>
-
template<>
usingparent_t
= DataNodeModule<VAL_TYPE, MODS...>
-
template<>
usingbase_t
= DataNodeModule<VAL_TYPE>
-
-
template <typename VAL_TYPE, emp::data... MODS>
template<>
classDataNodeModule
<VAL_TYPE, data::Stats, MODS...> : public emp::DataNodeModule<VAL_TYPE, MODS...> - #include <DataNode.h>
== data::Stats == Note: These statistics are calculated with the assumption that the data this node has recieved is the entire population of measurements we’re interested in, not a sample.
Note 2: Kurtosis is calculated using Snedecor and Cochran (1967)’s formula. A perfect normal distribution has a kurtosis of 0.
Public Functions
-
DataNodeModule
()
-
double
GetVariance
() const Get the variance (squared deviation from the mean) of values added since the last reset.
-
double
GetStandardDeviation
() const Get the standard deviation of values added since the last reset.
-
double
GetSkew
() const Get the skewness of values added since the last reset. This measurement tells you about the shape of the distribution. For a unimodal distribution, negative skew means that the distribution has a longer/thicker tail to the left. Positive skew means that ths distribution has a longer/thicker tail to the right.
-
double
GetKurtosis
() const Get the kurtosis of the values added since the last reset. This is another measurement that describes the shape of the distribution. High kurtosis means that there is more data in the tails of the distribution (i.e. the tails are “heavier”), whereas low kurtosis means that there is less data in the tails. We use Snedecor and Cochran (1967)’s formula to calculate kurtosis. Under this formula, a normal distribution has kurtosis of 0.
-
void
AddDatum
(const VAL_TYPE &val) Add.
- Parameters
val
: to this DataNode
-
void
Reset
() Reset this node (resets current stats to 0)
-
void
PrintDebug
(std::ostream &os = std::cout) Print debug information (useful for figuring out which modifiers you included)
Protected Types
-
template<>
usingthis_t
= DataNodeModule<VAL_TYPE, data::Stats, MODS...>
-
template<>
usingparent_t
= DataNodeModule<VAL_TYPE, MODS...>
-
template<>
usingbase_t
= DataNodeModule<VAL_TYPE>
-
-
template <emp::data... MODS>
structFormatDataMods
¶ - #include <DataNode.h>
A template that will determing requisites, sort, make unique the data mods provided. The final, sorted IntPack of the requisites plus originals is in ‘sorted’.
DataManagers¶
DataManager handles a set of DataNode objects with the same tracking settings.
- 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
- 2017-2018
-
namespace
emp
¶ If we are in emscripten, make sure to include the header.
This file contains extra analysis tools to use with systematics managers that have non-null DATA_TYPES.
- 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
- 2018
This file contains functions for adding additional data files to Worlds.
- 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
- 2018
-
template <typename VAL_TYPE, emp::data... MODS>
classDataManager
¶ - #include <DataManager.h>
DataManagers handle sets of DataNode objects that all have the same tracking settings.
Public Functions
-
DataManager
()¶
-
~DataManager
()¶
-
size_t
GetSize
() const¶ Returns the number of DataNodes in this DataManager.
-
auto &
GetNodes
() const¶ Returns the std::map mapping node names (strings) to DataNodes.
-
node_t &
New
(const std::string &name)¶ Creates and adds a new DataNode, with the name specified in.
- Parameters
name.
:
-
void
Delete
(const std::string &name)¶ Deletes the DataNode with the name
- Parameters
name.
: Throws an error if there is no node with that name in this manager.
-
const node_t &
Get
(const std::string &name) const¶ Returns a const reference to the node named
- Parameters
name.
: Throws an error if there is no node with that name in this manager
-
node_t &
Get
(const std::string &name)¶ Returns a reference to the node named
- Parameters
name.
: Throws an error if there is no node with that name in this manager
-
template <typename... Ts>
voidAddData
(const std::string &name, Ts... extra)¶ Adds data to a node in the DataManager.
Example:
- Parameters
name
: is the node to add the data to. All subsequent arguments are the data to add to that node, and should be of whatever type all of the nodes in this maanger expect.
DataManager<int, data::Current, data::Range> my_data_manager; my_data_manager.Add(“my_node_name”); my_data_manager.AddData(“my_node_name”, 1, 2, 3, 4, 5);
-
void
ResetAll
()¶ Resets all nodes in this manager. For nodes without the data::Archive attribute, this clears all of their data except current. For nodes with the data::Archive attribute, this creates a new vector to start storing data, retaining the old one in the archive.
Private Types
-
template<>
usingdata_t
= VAL_TYPE¶
-
DataInterfaces¶
DataInterface is a generic interface to a DataNode.
- 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
-
namespace
emp
If we are in emscripten, make sure to include the header.
This file contains extra analysis tools to use with systematics managers that have non-null DATA_TYPES.
- 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
- 2018
This file contains functions for adding additional data files to Worlds.
- 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
- 2018
Functions
-
template <typename VAL_TYPE, emp::data... EXTRA>
DataInterface *MakeDataInterface
()¶
-
class
DataInterface
¶ - #include <DataInterface.h>
A generic interface to a DataNode (so that you don’t need to know the node’s exact type)
Subclassed by emp::DataInterface_Impl< VAL_TYPE, EXTRA >
Public Functions
-
virtual
~DataInterface
()¶
-
virtual size_t
GetCount
() const = 0¶
-
virtual size_t
GetResetCount
() const = 0¶
-
virtual double
GetTotal
() const = 0¶
-
virtual double
GetMean
() const = 0¶
-
virtual double
GetMin
() const = 0¶
-
virtual double
GetMax
() const = 0¶
-
virtual double
GetVariance
() const = 0¶
-
virtual double
GetStandardDeviation
() const = 0¶
-
virtual double
GetSkew
() const = 0¶
-
virtual double
GetKurtosis
() const = 0¶
-
virtual void
PullData
() = 0¶
-
virtual void
Reset
() = 0¶
-
virtual void
GetName
() = 0¶
-
virtual void
GetDescription
() = 0¶
-
virtual void
GetKeyword
() = 0¶
-
virtual
-
template <typename VAL_TYPE, emp::data... EXTRA>
classDataInterface_Impl
: public emp::DataInterface¶ - #include <DataInterface.h>
Public Functions
-
DataInterface_Impl
()¶
-
DataInterface_Impl
(node_t *n)¶
-
DataInterface_Impl
(const DataInterface_Impl&)¶
-
DataInterface_Impl
(DataInterface_Impl&&)¶
-
~DataInterface_Impl
()¶
-
DataInterface_Impl &
operator=
(const DataInterface_Impl&)¶
-
DataInterface_Impl &
operator=
(DataInterface_Impl&&)¶
-
size_t
GetCount
() const¶ Returns the number values added to this node since the last reset.
-
size_t
GetResetCount
() const¶ Returns the number of times this node has been reset.
-
double
GetTotal
() const¶ Returns the sum of values added since the last reset. Requires that the data::Range or data::FullRange be added to the DataNode
-
double
GetMean
() const¶ Returns the mean of the values added since the last reset. Requires that the data::Range or data::FullRange be added to the DataNode
-
double
GetMin
() const¶ Returns the minimum of the values added since the last reset. Requires that the data::Range or data::FullRange be added to the DataNode
-
double
GetMax
() const¶ Returns the maximum of the values added since the last reset. Requires that the data::Range or data::FullRange be added to the DataNode
-
double
GetVariance
() const¶ Returns the variance of the values added since the last reset. Requires that the data::Stats or data::FullStats be added to the DataNode
-
double
GetStandardDeviation
() const¶ Returns the standard deviation of the values added since the last reset. Requires that the data::Stats or data::FullStats be added to the DataNode
-
double
GetSkew
() const¶ Returns the skewness of the values added since the last reset. Requires that the data::Stats or data::FullStats be added to the DataNode
-
double
GetKurtosis
() const¶ Returns the kurtosis of the values added since the last reset. Requires that the data::Stats or data::FullStats be added to the DataNode
-
void
PullData
()¶ Runs the Pull function for this DataNode and records the resulting values. Requires that the data::Pull module was added to this DataNode, and that a pull function was specified.
-
void
Reset
()¶ Reset this node. The exact effects of this depend on the modules that this node has, but in general it prepares the node to recieve a new set of data.
-
void
PrintDebug
(std::ostream &os = std::cout)¶ Print debug information about this node to
- Parameters
os.
: Useful for tracking which modifiers are included.
-
void
GetName
()¶ Returns this node’s name. Requires that the data::Info module was added to this DataNode, and that a name was set.
-
void
GetDescription
()¶ Returns this node’s description. Requires that the data::Info module was added to this DataNode, and that a description was set.
-
void
GetKeyword
()¶ Returns this node’s keyword. Requires that the data::Info module was added to this DataNode, and that a keyword was set.
-
DataFiles¶
DataFile objects use DataNode objects to dynamically fill out file contents.
- 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
-
namespace
emp
If we are in emscripten, make sure to include the header.
This file contains extra analysis tools to use with systematics managers that have non-null DATA_TYPES.
- 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
- 2018
This file contains functions for adding additional data files to Worlds.
- 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
- 2018
Functions
-
template <typename CONTAINER>
ContainerDataFile<CONTAINER>MakeContainerDataFile
(std::function<CONTAINER(void)> fun, const std::string &filename, const std::string &b = "", const std::string &s = ",", const std::string &e = "n", )¶ Convenience function for building a container data file.
- Parameters
fun
: is the function to call to update the container
-
template <typename CONTAINER>
classContainerDataFile
: public emp::DataFile¶ - #include <DataFile.h>
Sometimes you may want a data file where a set of functions is run on every item in a container every time you write to the file. ContainerDataFiles do that.
Note: CONTAINER type can be a pointer to a container and the datafile will handle derefeferencing it appropriately.
Public Functions
-
ContainerDataFile
(const std::string &filename, const std::string &b = "", const std::string &s = ",", const std::string &e = "n")¶
-
~ContainerDataFile
()¶
-
void
SetUpdateContainerFun
(const fun_update_container_t fun)¶ Tell this file what function to run to update the contents of the container that data is being calculated on.
-
void
PrintHeaderKeys
()¶ Print a header containing the name of each column.
-
void
PrintHeaderComment
(const std::string &cstart = "# ")¶ Print a header containing comments describing all of the columns.
-
const container_t
GetCurrentRows
() const¶
-
void
OutputLine
(const data_t d)¶
-
void
Update
()¶ Run all of the functions and print the results as a new line in the file.
-
void
Update
(size_t update)¶ Update the file with an additional set of lines.
-
size_t
Add
(const std::function<void(std::ostream&, data_t)> &fun, const std::string &key, const std::string &desc, )¶ If a function takes an ostream, pass in the correct one. Generic function for adding a column to the DataFile. In practice, you probably want to call one of the more specific ones.
-
template <typename T>
size_tAddContainerFun
(const std::function<T(const data_t)> &fun, const std::string &key = "", const std::string &desc = "", )¶ Add a function that returns a value to be printed to the file.
-
const std::string &
GetLineBegin
() const¶ Returns the string that is printed at the beginning of each line.
-
const std::string &
GetSpacer
() const¶ Returns the string that is printed between elements on each line (i.e. the delimeter).
-
void
SetTiming
(time_fun_t fun)¶ Provide a timing function with a bool(size_t update) signature. The timing function is called with the update, and returns a bool to indicate if files should print this update.
-
void
SetTimingOnce
(size_t print_time)¶ Setup this file to print only once, at the specified update. Note that this timing function can be replaced at any time, even after being triggered.
-
void
SetTimingRepeat
(size_t step)¶ Setup this file to print every ‘step’ updates.
-
void
SetTimingRange
(size_t first, size_t step, size_t last)¶ Setup this file to print only in a specified time range, and a given frequency (step).
-
void
SetSpacer
(const std::string &_in)¶ Print.
- Parameters
_in
: between elements (i.e. make_in
: the delimeter).
-
void
SetupLine
(const std::string &b, const std::string &s, const std::string &e)¶ Set line begin character (.
- Parameters
b)column
: delimeter (s)and
: line end character (e)
:
-
size_t
Add
(const std::function<void(std::ostream&)> &fun, const std::string &key, const std::string &desc, )¶ If a function takes an ostream, pass in the correct one. Generic function for adding a column to the DataFile. In practice, you probably want to call one of the more specific ones.
-
template <typename T>
size_tAddFun
(const std::function<T()> &funconst std::string &key = "", const std::string &desc = "", )¶ Add a function that returns a value to be printed to the file.
-
template <typename T>
size_tAddVar
(const T &var, const std::string &key = "", const std::string &desc = "")¶ Add a function that always prints the current value of.
- Parameters
var.
:
-
template <typename VAL_TYPE, emp::data... MODS>
size_tAddCurrent
(DataNode<VAL_TYPE, MODS...> &node, const std::string &key = "", const std::string &desc = "", const bool &reset = false, const bool &pull = false)¶ Add a function that always pulls the current value from the DataNode
- Parameters
node.
: Requires thatnode
: have the data::Current modifier. Ifreset
: is set true, we will call Reset on that DataNode after pulling the current value from the node
-
template <typename VAL_TYPE, emp::data... MODS>
size_tAddMean
(DataNode<VAL_TYPE, MODS...> &node, const std::string &key = "", const std::string &desc = "", const bool &reset = false, const bool &pull = false)¶ Add a function that always pulls the mean value from the DataNode
- Parameters
node.
: Requires thatnode
: have the data::Range or data::FullRange modifier. Ifreset
: is set true, we will call Reset on that DataNode after pulling the current value from the node
-
template <typename VAL_TYPE, emp::data... MODS>
size_tAddTotal
(DataNode<VAL_TYPE, MODS...> &node, const std::string &key = "", const std::string &desc = "", const bool &reset = false, const bool &pull = false)¶ Add a function that always pulls the total value from the DataNode
- Parameters
node.
: Requires thatnode
: have the data::Range or data::FullRange modifier. Ifreset
: is set true, we will call Reset on that DataNode after pulling the current value from the node
-
template <typename VAL_TYPE, emp::data... MODS>
size_tAddMin
(DataNode<VAL_TYPE, MODS...> &node, const std::string &key = "", const std::string &desc = "", const bool &reset = false, const bool &pull = false)¶ Add a function that always pulls the minimum value from the DataNode
- Parameters
node.
: Requires thatnode
: have the data::Range or data::FullRange modifier. Ifreset
: is set true, we will call Reset on that DataNode after pulling the current value from the node
-
template <typename VAL_TYPE, emp::data... MODS>
size_tAddMax
(DataNode<VAL_TYPE, MODS...> &node, const std::string &key = "", const std::string &desc = "", const bool &reset = false, const bool &pull = false)¶ Add a function that always pulls the maximum value from the DataNode
- Parameters
node.
: Requires thatnode
: have the data::Range or data::FullRange modifier. Ifreset
: is set true, we will call Reset on that DataNode after pulling the current value from the node
-
template <typename VAL_TYPE, emp::data... MODS>
size_tAddVariance
(DataNode<VAL_TYPE, MODS...> &node, const std::string &key = "", const std::string &desc = "", const bool &reset = false, const bool &pull = false)¶ Add a function that always pulls the variance from the DataNode
- Parameters
node
: Requires thatnode
: have the data::Stats or data::FullStats modifier.
-
template <typename VAL_TYPE, emp::data... MODS>
size_tAddStandardDeviation
(DataNode<VAL_TYPE, MODS...> &node, const std::string &key = "", const std::string &desc = "", const bool &reset = false, const bool &pull = false)¶ Add a function that always pulls the standard deviation from the DataNode
- Parameters
node
: Requires thatnode
: have the data::Stats or data::FullStats modifier.
-
template <typename VAL_TYPE, emp::data... MODS>
size_tAddSkew
(DataNode<VAL_TYPE, MODS...> &node, const std::string &key = "", const std::string &desc = "", const bool &reset = false, const bool &pull = false)¶ Add a function that always pulls the skewness from the DataNode
- Parameters
node
: Requires thatnode
: have the data::Stats or data::FullStats modifier.
-
template <typename VAL_TYPE, emp::data... MODS>
size_tAddKurtosis
(DataNode<VAL_TYPE, MODS...> &node, const std::string &key = "", const std::string &desc = "", const bool &reset = false, const bool &pull = false)¶ Add a function that always pulls the kurtosis from the DataNode
- Parameters
node
: Requires thatnode
: have the data::Stats or data::FullStats modifier.
-
template <typename VAL_TYPE, emp::data... MODS>
voidAddStats
(DataNode<VAL_TYPE, MODS...> &node, const std::string &key = "", const std::string &desc = "", const bool &reset = false, const bool &pull = false)¶ Add multiple functions that pull common stats measurements (mean, variance, min, and max) from the DataNode
- Parameters
node.
: Requires thatnode
: have the data::Stats or data::FullStats modifier.key
: anddesc
: will have the name of the stat appended to the beginning. Note: excludes standard deviation, because it is easily calculated from variance
-
template <typename VAL_TYPE, emp::data... MODS>
voidAddAllStats
(DataNode<VAL_TYPE, MODS...> &node, const std::string &key = "", const std::string &desc = "", const bool &reset = false, const bool &pull = false)¶ Add multiple functions that pull all stats measurements (mean, variance, min, max, skew, and kurtosis) from the DataNode
- Parameters
node
: Requires thatnode
: have the data::Stats or data::FullStats modifier.key
: anddesc
: will have the name of the stat appended to the beginning. Note: excludes standard deviation, because it is easily calculated from variance
-
template <typename VAL_TYPE, emp::data... MODS>
size_tAddHistBin
(DataNode<VAL_TYPE, MODS...> &node, size_t bin_id, const std::string &key = "", const std::string &desc = "", const bool &reset = false, const bool &pull = false)¶ Add a function that always pulls the count of the
- Parameters
bin_id
: ‘th bin of the histogram fromnode.
: Requires thatnode
: have the data::Histogram modifier and at least bins. Ifreset
: is set true, we will call Reset on that DataNode after pulling the current value from the node
-
template <typename VAL_TYPE, emp::data... MODS>
size_tAddInferiority
(DataNode<VAL_TYPE, MODS...> &node, const std::string &key = "", const std::string &desc = "", const bool &reset = false, const bool &pull = false)¶ Add a function that always pulls the inferiority (mean divided by max) from the DataNode
- Parameters
node.
: Requires thatnode
: have the data::Range or data::FullRange modifier. Ifreset
: is set true, we will call Reset on that DataNode after pulling the current value from the node
Protected Types
-
template<>
usingraw_container_t
= typename remove_ptr_type<container_t>::type¶
-
template<>
usingdata_t
= typename raw_container_t::value_type¶
-
template<>
usingfun_update_container_t
= std::function<container_t(void)>¶
Protected Attributes
-
fun_update_container_t
update_container_fun
¶
-
container_t
current_rows
¶
-
FunctionSet<container_fun_t>
container_funs
¶
-
time_fun_t
timing_fun
¶ Function to determine updates to print on (default: all)
-
-
class
DataFile
¶ - #include <DataFile.h>
Keep track of everything associated with periodically printing data to a file. Maintain a set of functions for calculating the desired measurements at each point in time that they are required. It also handles the formating of the file.
Subclassed by emp::ContainerDataFile< CONTAINER >
Public Functions
-
DataFile
(const std::string &in_filename, const std::string &b = "", const std::string &s = ",", const std::string &e = "n")¶
-
DataFile
(std::ostream &in_os, const std::string &b = "", const std::string &s = ",", const std::string &e = "n")¶
-
virtual
~DataFile
()¶
-
const std::string &
GetLineBegin
() const¶ Returns the string that is printed at the beginning of each line.
-
const std::string &
GetSpacer
() const¶ Returns the string that is printed between elements on each line (i.e. the delimeter).
-
void
SetTiming
(time_fun_t fun)¶ Provide a timing function with a bool(size_t update) signature. The timing function is called with the update, and returns a bool to indicate if files should print this update.
-
void
SetTimingOnce
(size_t print_time)¶ Setup this file to print only once, at the specified update. Note that this timing function can be replaced at any time, even after being triggered.
-
void
SetTimingRepeat
(size_t step)¶ Setup this file to print every ‘step’ updates.
-
void
SetTimingRange
(size_t first, size_t step, size_t last)¶ Setup this file to print only in a specified time range, and a given frequency (step).
-
void
SetSpacer
(const std::string &_in)¶ Print.
- Parameters
_in
: between elements (i.e. make_in
: the delimeter).
-
void
SetupLine
(const std::string &b, const std::string &s, const std::string &e)¶ Set line begin character (.
- Parameters
b)column
: delimeter (s)and
: line end character (e)
:
-
virtual void
PrintHeaderKeys
()¶ Print a header containing the name of each column.
-
virtual void
PrintHeaderComment
(const std::string &cstart = "# ")¶ Print a header containing comments describing all of the columns.
-
virtual void
Update
()¶ Run all of the functions and print the results as a new line in the file.
-
void
Update
(size_t update)¶ If Update is called with an update number, call the full version of update only if the update value passes the timing function (that is, the timing function returns true).
-
size_t
Add
(const std::function<void(std::ostream&)> &fun, const std::string &key, const std::string &desc, ) If a function takes an ostream, pass in the correct one. Generic function for adding a column to the DataFile. In practice, you probably want to call one of the more specific ones.
-
template <typename T>
size_tAddFun
(const std::function<T()> &funconst std::string &key = "", const std::string &desc = "", ) Add a function that returns a value to be printed to the file.
-
template <typename T>
size_tAddVar
(const T &var, const std::string &key = "", const std::string &desc = "")¶ Add a function that always prints the current value of.
- Parameters
var.
:
-
template <typename VAL_TYPE, emp::data... MODS>
size_tAddCurrent
(DataNode<VAL_TYPE, MODS...> &node, const std::string &key = "", const std::string &desc = "", const bool &reset = false, const bool &pull = false)¶ Add a function that always pulls the current value from the DataNode
- Parameters
node.
: Requires thatnode
: have the data::Current modifier. Ifreset
: is set true, we will call Reset on that DataNode after pulling the current value from the node
-
template <typename VAL_TYPE, emp::data... MODS>
size_tAddMean
(DataNode<VAL_TYPE, MODS...> &node, const std::string &key = "", const std::string &desc = "", const bool &reset = false, const bool &pull = false)¶ Add a function that always pulls the mean value from the DataNode
- Parameters
node.
: Requires thatnode
: have the data::Range or data::FullRange modifier. Ifreset
: is set true, we will call Reset on that DataNode after pulling the current value from the node
-
template <typename VAL_TYPE, emp::data... MODS>
size_tAddTotal
(DataNode<VAL_TYPE, MODS...> &node, const std::string &key = "", const std::string &desc = "", const bool &reset = false, const bool &pull = false)¶ Add a function that always pulls the total value from the DataNode
- Parameters
node.
: Requires thatnode
: have the data::Range or data::FullRange modifier. Ifreset
: is set true, we will call Reset on that DataNode after pulling the current value from the node
-
template <typename VAL_TYPE, emp::data... MODS>
size_tAddMin
(DataNode<VAL_TYPE, MODS...> &node, const std::string &key = "", const std::string &desc = "", const bool &reset = false, const bool &pull = false)¶ Add a function that always pulls the minimum value from the DataNode
- Parameters
node.
: Requires thatnode
: have the data::Range or data::FullRange modifier. Ifreset
: is set true, we will call Reset on that DataNode after pulling the current value from the node
-
template <typename VAL_TYPE, emp::data... MODS>
size_tAddMax
(DataNode<VAL_TYPE, MODS...> &node, const std::string &key = "", const std::string &desc = "", const bool &reset = false, const bool &pull = false)¶ Add a function that always pulls the maximum value from the DataNode
- Parameters
node.
: Requires thatnode
: have the data::Range or data::FullRange modifier. Ifreset
: is set true, we will call Reset on that DataNode after pulling the current value from the node
-
template <typename VAL_TYPE, emp::data... MODS>
size_tAddVariance
(DataNode<VAL_TYPE, MODS...> &node, const std::string &key = "", const std::string &desc = "", const bool &reset = false, const bool &pull = false)¶ Add a function that always pulls the variance from the DataNode
- Parameters
node
: Requires thatnode
: have the data::Stats or data::FullStats modifier.
-
template <typename VAL_TYPE, emp::data... MODS>
size_tAddStandardDeviation
(DataNode<VAL_TYPE, MODS...> &node, const std::string &key = "", const std::string &desc = "", const bool &reset = false, const bool &pull = false)¶ Add a function that always pulls the standard deviation from the DataNode
- Parameters
node
: Requires thatnode
: have the data::Stats or data::FullStats modifier.
-
template <typename VAL_TYPE, emp::data... MODS>
size_tAddSkew
(DataNode<VAL_TYPE, MODS...> &node, const std::string &key = "", const std::string &desc = "", const bool &reset = false, const bool &pull = false)¶ Add a function that always pulls the skewness from the DataNode
- Parameters
node
: Requires thatnode
: have the data::Stats or data::FullStats modifier.
-
template <typename VAL_TYPE, emp::data... MODS>
size_tAddKurtosis
(DataNode<VAL_TYPE, MODS...> &node, const std::string &key = "", const std::string &desc = "", const bool &reset = false, const bool &pull = false)¶ Add a function that always pulls the kurtosis from the DataNode
- Parameters
node
: Requires thatnode
: have the data::Stats or data::FullStats modifier.
-
template <typename VAL_TYPE, emp::data... MODS>
voidAddStats
(DataNode<VAL_TYPE, MODS...> &node, const std::string &key = "", const std::string &desc = "", const bool &reset = false, const bool &pull = false)¶ Add multiple functions that pull common stats measurements (mean, variance, min, and max) from the DataNode
- Parameters
node.
: Requires thatnode
: have the data::Stats or data::FullStats modifier.key
: anddesc
: will have the name of the stat appended to the beginning. Note: excludes standard deviation, because it is easily calculated from variance
-
template <typename VAL_TYPE, emp::data... MODS>
voidAddAllStats
(DataNode<VAL_TYPE, MODS...> &node, const std::string &key = "", const std::string &desc = "", const bool &reset = false, const bool &pull = false)¶ Add multiple functions that pull all stats measurements (mean, variance, min, max, skew, and kurtosis) from the DataNode
- Parameters
node
: Requires thatnode
: have the data::Stats or data::FullStats modifier.key
: anddesc
: will have the name of the stat appended to the beginning. Note: excludes standard deviation, because it is easily calculated from variance
-
template <typename VAL_TYPE, emp::data... MODS>
size_tAddHistBin
(DataNode<VAL_TYPE, MODS...> &node, size_t bin_id, const std::string &key = "", const std::string &desc = "", const bool &reset = false, const bool &pull = false)¶ Add a function that always pulls the count of the
- Parameters
bin_id
: ‘th bin of the histogram fromnode.
: Requires thatnode
: have the data::Histogram modifier and at least bins. Ifreset
: is set true, we will call Reset on that DataNode after pulling the current value from the node
-
template <typename VAL_TYPE, emp::data... MODS>
size_tAddInferiority
(DataNode<VAL_TYPE, MODS...> &node, const std::string &key = "", const std::string &desc = "", const bool &reset = false, const bool &pull = false)¶ Add a function that always pulls the inferiority (mean divided by max) from the DataNode
- Parameters
node.
: Requires thatnode
: have the data::Range or data::FullRange modifier. Ifreset
: is set true, we will call Reset on that DataNode after pulling the current value from the node
Protected Attributes
-
time_fun_t
timing_fun
¶ Function to determine updates to print on (default: all)
-
-
namespace
internal
¶ -
template <typename container_t>
structupdate_impl
¶ - #include <DataFile.h>
Public Functions
-
void
Update
(ContainerDataFile<container_t> *df)¶
-
void
-
template <typename container_t>
template<>
structupdate_impl
<container_t *>¶ - #include <DataFile.h>
Public Functions
-
void
Update
(ContainerDataFile<container_t *> *df)¶
-
void
-
template <typename container_t>
template<>
structupdate_impl
<Ptr<container_t>>¶ - #include <DataFile.h>
Public Functions
-
void
Update
(ContainerDataFile<Ptr<container_t>> *df)¶
-
void
-
template <typename container_t>
Web Tools (for use with Emscripten)¶
D3 Data Visualization Tools¶
Using Empirical’s D3.js Wrapper¶
If you’re writing scientific code that runs on the web, you’ll probably want to visualize the results (either as your program runs or after it’s done). To make this as easy as possible, Empirical includes a C++ wrapper for d3.js, a wildly popular and powerful Javascript data visualization library. Using the wrapper, you can create visualizations directly from C++.
At a base level, the wrapper provides C++ equivalents for all objects, methods, and functions in d3.js. So, if you’re used to using d3, using the wrapper should be very similar. However, d3.js is a library that you use to build visualizations rather than a library of pre-built visualizations (a fact that has lead to the proliferation of many very similar libraries built on top of d3 that provide pre-built graphs). Where possible, we have tried to provide short-cut functions and pre-built graph objects in an effort to help those new to Javascript visualization get started fast. This is an ongoing process and we’re always open to suggestions!
A Minimal Example¶
D3 visualizations run in web browsers. That means that to use this wrapper, you need to compile your C++ code to Javascript, using Emscripten. To see the visualization, you need to have an html file that loads your Javascript. Then you need to open that html file in a web browser. Optionally, you might also have a CSS file that contains rules for how elements of your web page should look.
This example assumes the following file structure:

Here are the basics of what you need in order to get up and running. The easiest way to make a visualization is to use one of the pre-built visualizations. Later we’ll get into writing your own. Either way, you’ll need:
C++ File¶
The C++ file that you’ll compile to Javascript. For this example, we’ll use the Empirical web module to build the whole web page:
// Always include web_init.h when you're doing web stuff -
// it makes sure everything gets initialized right
#include "../Empirical/web/web_init.h"
// We're using a document object to arrange everything
// we're drawing.
#include "../Empirical/web/Document.h"
//Contains pre-built visualizations
#include "../Empirical/web/d3/visualizations.h"
// The document object is in charge of all of the Javascript
// and html that goes in the <div> element in the html. It
// gets created before main so that it stays in scope
// when main ends
emp::web::Document doc("my_visualization");
// The visualization object needs to be declared globally for
// the same reason. For this example, we'll use a
// LineageVisualization, which is a type of D3 visualization
// object. It takes two argumenets: the width and the height
// of the visualization.
emp::web::LineageVisualization lineage_viz(6000, 5000);
int main {
// Add visualization to the document
doc << lineage_viz;
// Load pre-existing data file, example.json,
// into the visualization
lineage_viz.LoadDataFromFile("example.json");
}
Now we need to compile it:
emcc my_program.cc -o my_program.js \ #.js extension tells Emscripten to compile to Javascript
--js-library ../Empirical/web/library_emp.js \ #Include the Empirical Javascript library
--js-library ../Empirical/web/d3/library_d3.js \ #Include Javascript library for D3 wrapper
-s EXPORTED_FUNCTIONS="['_main', '_empCppCallback']" \ #Tells Emscripten what to export from C++
-s ASSERTIONS=2 \ #Emscripten needs to know this
-s DEMANGLE_SUPPORT=1 \ #Make names of variables in Javascript more readable
-s TOTAL_MEMORY=67108864 \ #The exact number doesn't matter, but default is too small
-s NO_EXIT_RUNTIME=1 \ #Make the page keep working after main() is done running
-O3 -DNDEBUG #Turn on optimizations and turn off debugging (improves speed - only do this
#once you're done debugging)
HTML File¶
To tell the browser what to do with your Javascript, you need an html file:
<!-- This is an html comment -->
<!DOCTYPE html>
<html>
<!-- The head is for stuff that needs to get set up first,
like metadata and styles -->
<head>
<title> My D3/Empirical visualization! </title>
<!-- Optional - load a stylesheet -->
<link rel="stylesheet" type="text/css" href="style_sheet.css" />
</head>
<!-- Everything else goes in the body -->
<body>
<!-- Include necessary javascript libraries
(jquery, d3, and a d3 tooltip library) -->
<script src="Empirical/web/jquery-1.11.2.min.js"></script>
<script src="Empirical/web/d3/d3.min.js" charset="utf-8"></script>
<script src="Empirical/web/d3/d3-tip.js" charset="utf-8"></script>
<!-- Include the Javascript file you
compiled your C++ code to -->
<script src="my_program.js"></script>
<!-- We told the emp::document that it was in charge of
something called "my_visualization," so we need to create
that element -->
<div id="my_visualization"></div>
</body>
</html>
CSS File¶
Optionally, a CSS file can be used to make elements look the way you want them to. Here’s one that includes the necessary styles to make tooltips work (the html file above assumes it’s called style_sheet.css, and is in the same directory as the html file):
.d3-tip {
line-height: 1;
font-weight: bold;
padding: 12px;
background: rgba(255, 255, 255, 0.8);
color: #000;
border-radius: 2px;
}
/* Creates a small triangle extender for the tooltip */
.d3-tip:after {
box-sizing: border-box;
display: inline;
font-size: 10px;
width: 100%;
line-height: 1;
color: rgba(255, 255, 255, 0.8);
content: "\25BC";
position: absolute;
text-align: center;
}
/* Style northward tooltips differently */
.d3-tip.n:after {
margin: -1px 0 0 0;
top: 100%;
left: 0;
}
Running your visualization¶
Now to open up the page in a browser! Some browsers will let you open the page up directly, but some will complain about the fact that you’re trying to access a file on your computer (example.json) with Javascript. The easiest way around this is with the Python simpleHTTPServer library. If you’re using Python 2.x, run the following command from the directory containing your html file:
python -m SimpleHTTPServer

If you’re running Python 3.x, use this command instead:
python -m http.server

You can now open a browser to the server (http://localhost:8000, replacing 8000 with whatever number was after “port” in the output from the command). You should see a list of file names in the directory your terminal was open to when you ran the HTTP Server command (unless you happen to have a file named index.html, in which case you’ll see the contents of that file). Assuming you ran this command from the “example” directory in the directory structure shown above, you should see “my_html.html” (or whatever you called your html file) on the list. Click on it.
Ta-da! There’s your visualization.
It’s convenient to have a visualization of data you’ve already generated, but the real power of D3 visualization objects is that they can update in real time while your code runs. Here’s an example C++ file that does that:
Example here
So that’s how you use out-of-the-box D3 visualizations in Empirical. Sometimes, though, you want to do something new and exciting. Which brings us to the next section…
Writing Your Own Visualization¶
To build your own visualization, you need to understand a bit about how D3 works. Which means you need to understand a bit about how Javascript and HTML work. I know, I know, the reason you’re doing this all in C++ is that you want to avoid that, but I promise it’s worth it if you want to make interactive visualizations that run on the web.
When your browser loads a website, it takes the html for that page and turns it into a tree:

This tree is called the Document Object Model (DOM) and every set of tags (things in angle brackets, like <head></head>) in the html is an element in it. Elements that are nested inside other elements are represented as children of those elements in the tree. For instance, the tree pictured above is representing the following html:
<!DOCTYPE html>
<html>
<head>
</head>
<body>
<div></div>
<div></div>
</body>
</html>
Javascript manipulates the DOM. It adds elements, it removes elements, it moves them around, and it changes information about them. D3’s primary innovation is that it binds data to DOM elements and lets you manipulate them based on that data. So, for instance, you can add a bunch of circle elements representing all of your data points. With the D3 C++ wrapper, you’re doing the same thing, but from C++.
Let’s take a tour of the main components of D3:
Selections¶
Selections are a way to work with groups of DOM elements. For instance, let’s say we have this html file:
<!DOCTYPE html>
<html>
<head>
<title> My D3/Empirical visualization! </title>
</head>
<body>
<!-- Include necessary javascript libraries
(jquery, and d3) -->
<script src="Empirical/web/jquery-1.11.2.min.js">
</script>
<script src="Empirical/web/d3/d3.min.js" charset="utf-8">
</script>
<!-- Include the Javascript file you compiled your
C++ code to -->
<script src="my_program.js"></script>
<div id="my_visualization">
<svg id = "graph">
<circle cx="10" cy="10" r="5">
<circle cx="20" cy="20" r="5">
</svg>
</div>
</body>
</html>
Notice that we’ve added two types of elements: an SVG canvas and two circles. SVG stands for Scalable Vector Graphics, which is the type of graphics the D3 works with (the other type of graphics in Javascript are canvas graphics). In SVG graphics, every shape is its own element, nested inside an SVG canvas element, so each shape can be manipulated independently. Here we have two circle elements on our SVG canvas. We’ve set three attributes for the circles: the x coordinate of their center points (cx), the y coordinate of their center points (cy), and their radii (r).
If we want to operate on the circles, we can create a selection object that contains them:
//s is a container that contains both circle elements in the DOM
D3::Selection s = D3::SelectAll("circle");
We can then do things to all of the circles, like turn them purple:
// Set the "fill" style of everything in the s selection
// to "purple". "fill" is the color of the inside of a shape
// We'll talk more about modifying shapes a bit later
s.SetStyle("fill", "purple");
What if there are other circles outside the graph area that we don’t want to affect? We can select an element with a specific id using the “#”, and then take a sub-selection by calling the SelectAll method on it:
// Select will create a selection containing the first matching
// element, whereas SelectAll creates a selection containing
// all matching elements
D3::Selection svg = D3::Select("#graph");
D3::Selection graph_circles = svg.SelectAll("circle");
Advanced note: You can also make selections based on classes with D3::Select(.classname).
Binding Data¶
In D3, you bind data to selections. Usually, you are binding that data because you to visualize it with SVG elements. So, usually the selection that we’re binding data to is a selection of some type of SVG element on an SVG canvas. Something like this:
// Here we're using D3 to add the svg canvas to the document.
// We could also have Selected a pre-existing svg canvas that
// we put in the html, as we did in previous examples.
D3::Selection svg = D3::Select("body").Append("svg");
D3::Selection data_points = svg.SelectAll("circle");
Wait, what? Why did we select all of the circles on the SVG canvas when we know for a fact that there aren’t any, because we just created it? It turns out that D3 pays attention to the type of elements a selection contains. It knows that this is an empty selection for circles. So now we can bind our data to this selection and D3 will understand that each point should correspond to a circle. That means it can tell which data points don’t have corresponding circles (in this case all of them). These data points make up the “enter selection,” which we can access with the selection.enter() method. Most commonly, we use the enter selection to append elements for every data point. Here’s what that all looks like together:
// Create example data
emp::vector<int> data = {1,2,3,4,5};
// Bind the data to the selection. We'll explain why this
// variable is named update in moment
D3::Selection update = data_points.Data(data);
// Get the enter selection (data without a DOM element)
D3::Selection enter = update.Enter();
// Give each data point in the enter selection a circle
// (as a shortcut, we could also have just used
// EnterAppend("circle") on the previous line)
enter.Append("circle");
Our circles won’t show up if we don’t give them cx, cy, and r attributes. Let’s set them to be equal to each element’s corresponding data value. We can do this by passing SetAttr() a function as its second object. Since passing functions around it much more common in Javascript than in C++, we’ll talk a bit more about the ins and outs a bit later. For now, you just need to know that SetAttr() accepts a function that takes the data bound to the element and returns the value you want to set an attribute to. Technically, Javascript is going to pass it three arguements, so you should write your C++ function to accept three parameters, or your compiler will probably throw a tantrum:
// For now, we're going to use the simplest calllback function
// possible: one that returns exactly the data value that it
// was given.
std::function<int(int, int, int)> return_d = \
[](int d, int i, int j){return d;};
// Set cx (the x coordinate of the circle's center), cy (the y
// coordinate of the circle's center), and r (the radius) to
// all be the return of the return_d function
// (i.e. the bound data)
enter.SetAttr("cx", return_d)
.SetAttr("cy", return_d)
.SetAttr("r", return_d);
Now we have 5 circles, with the numbers from 1-5 bound to them as data (one number per circle).
What if we get more data?
// Change data
data = {1, 2, 3, 4, 5, 6, 7};
// Select all of the circles and bind the new data
update = svg.SelectAll("circle").Data(data);
// This time the enter selection only contains two data points:
// 6 and 7
enter = update.Enter();
// Add new circles for the new data and set
// attributes appropriately
enter.Append("circle")
.SetAttr("cx", return_d)
.SetAttr("cy", return_d)
.SetAttr("r", return_d);
Now we have 7 circles. We added circles for the ones that didn’t already have circles.
What happens if our dataset shrinks? We can use the selection.Exit() method. This returns the “exit selection”. In the same way the enter selection contains all of the data points without circles, the exit selection contains all of the circles without data points. Usually we want to remove them:
// Change data
data = {1,2,3,4};
// Select all of the circles and bind the new data
update = svg.SelectAll("circle").Data(data);
// The enter selection would be empty, but the exit
// selection has three things in it: 5, 6, and 7
exit = update.Exit();
// Remove everything in the exit selection from the DOM
// (as a shortcut, we could have just used ExitRemove()
// on the previous line)
exit.Remove();
Now we’re down to four circles.
What happens if our data is replaced with four completely different numbers? The enter and exit selections will be empty (every data point has a circle and every circle has a data point), but the circles’ attributes won’t correspond to the right data anymore. Now it’s finally time to use that “update” variable we keep making. That variable has been holding what’s called the “update selection.” The update selection is directly returned by the selection.data() method, and it contains all of the data points associated with circles that already existed before the data was bound. We can use it to re-set the circles’ attributes, based on the new data:
// Change data
data = {10, 11, 12, 13};
// Select all of the circles and bind the new data
update = svg.SelectAll("circle").Data(data);
// Reset the attributes of the update selection
update.SetAttr("cx", return_d)
.SetAttr("cy", return_d)
.SetAttr("r", return_d);
Congratulations! You’ve now used d3’s popular enter-update-exit pattern. For a more thorough discussion, see [this article](https://bost.ocks.org/mike/join/) by the creator of d3.js.
There’s one other thing you should know about binding data. Thus far, we’ve been matching data with DOM elements sequentially (the first data point in the array gets paired with the first circle in the selection, and so on). But sometimes you’d like to keep the same circle corresponding to the same data point (this is especially important if you’re applying transitions). To acheive this, you can pass selection.Data() a “key” function that takes a piece of data (and optionally a position in the array/selection) and returns a string. Data points are then matched with DOM elements based on whether the string returned by running the function on the data point matches the string returned by running the function on the data bound to the element.
// Change data (re-arrange three elements and replace the fourth)
data = {13, 12, 11, 8}
// Select all of the circles and bind the new data with a key
// function. The key function supplied here is a lambda
// function that, like the return_d function
// we already wrote, just returns the value of the bound data
// The update selection contains circles for 11, 12, and 13,
// still associated with the correct data (so we don't need
// to reset the attributes)
update = svg.SelectAll("circle")
.Data(data, [](int d, int i){return d};);
// The enter selection contains 8
// EnterAppend just combines Enter() and Append()
// In Javascript, it's common to chain methods, as is
// done below. Most Selection methods in the D3 wrapper
// return the selection, so that we can chain methods here too
// The code below does exactly the same thing we did to the
// other enter selections
update.EnterAppend("circle")
.SetAttr("cx", return_d)
.SetAttr("cy", return_d)
.SetAttr("r", return_d);
// The exit selection contains 10
update.ExitRemove();
Changing Elements’ Traits¶
There are three types of traits that a DOM element might have: attributes, styles, and properties. For the most part, attributes are fundamental pieces of information about the element, styles deal with the element’s appearance (they are all things you could set with CSS), and properties are rare and specific to certain types of elements. The distinction mostly only matters because it determines which functions you call to set and get the values of a trait. Here are some examples of commonly used traits in each category:
Attributes (use SetAttr()):
- id - an element’s unique identifier
- width - in pixels, by default
- height - in pixels, by default
- x - the location of an element on the x axis (in pixels)
- y - the location of an element on the y axis (in pixels)
- cx - the location of a circle’s center on the x axis (in pixels)
- cy - the location of a circle’s center on the y axis (in pixels)
- r - a circle’s radius (in pixels)
- transform - a string indicating how to position the element. The Move and Rotate methods of selections are a convenient shortcut for this.
Styles (use SetStyle()):
- fill - the color an SVG shape is filled with
- stroke - the color of a line (either the border of an SVG shape or a path object)
- stroke-width - the length of a path or SVG shape border
Properties (use SetProperty()):
- checked - a property indicating whether or not a checkbox is checked
All of these functions take two arguemnts: a string indicating the name of the trait being changed and the value to change it to. This vale can be a constant, such as a number, string, or color (depending on the trait). They also accept functions (simple example above, explained in more detail below) that allow you to set the trait based off of each element’s bound data. Javascript will pass these functions three parameters: the value bound as data, the index of the element in the selection, and a third element that we don’t currently have a good way to translate to C++ (use an int as a placeholder in your function definition so C++ doesn’t throw a tantrum).
Transitions¶
One of the most powerful parts of D3 is the ease with which it allows you to animate your data. This is accomplished with transitions. The most common way to make a transition is to call the selection.MakeTransition() method on a selection containing all of the elements you want to animate (note: in Javascript, the method is just selection.transition(), because Javascript is less finicky about name collisions). You can then use the attr() and style() methods on the transition, just as you would on a selection, and the change will be animated. Note that the wrapper also allows you to set properties, html, and classes on a transition, but D3 doesn’t know how to animate changes in these, so they will just happen at the end of the transition. Other operations, such as appending new elements, are not allowed on transitions, because there isn’t a clear way to animate them.
For instance, here’s an example of animating a circle moving across the screen and gradually changing color from black (default) to blue:
// Add an svg canvas to the body and set its width to 100 pixels
D3::Selection svg = D3::Select("body").Append("svg")
.SetAttr("width", 100);
// Put a circle on the canvas
D3::Selection circle = svg.Append("circle");
// The circle will only show up if we give it x and y coordinates
// for it's center, and a radius Since we're going to move it
// from the left side of the screen to the right, we'll start it
// centered at 0, the left edge (it will be half of the canvas)
circle.SetAttr("cx", 0).SetAttr("cy", 5).SetAttr("r", 5)
// Make a transition from the circle selection
D3::Transition circle_anim = circle.MakeTransition();
// By changing the "cx" attribute via the transition, we cause
// the change to be animated, so we see the circle moving across
// the screen. Similarly, we see the circle fade from black
// to blue.
circle_anim.SetAttr("cx", 100).SetStyle("fill", "blue");
Some functions in Empirical’s D3 wrapper that accept selections will also select transitions, allowing you to choose to have their effects be animated, rather than occuring instantaneously (which can look choppy in many visualizations).
Scales and Axes¶
Usually your data is not in units that you can directly draw on the screen. For instance, if you want to plot a variable on the Y axis that has values from -1 to 1, you’ll need a way to convert from these very small values to values representing where the elements of your visualization should appear on the SVG canvas (in pixels). This is what scales do. Like a number of other objects in D3, scales are actually functions. They accept a value in the domain (the range of values your data can have) and return a value in the range (the range of coordinates on your screen that you want data to show up in).
For example, lets say we have data ranging from 0 to 1 and we want to convert it to coordinates on our screen from 0 to 100. We can make a scale to do it:
// Make a scale. We'll use a LinearScale, but you could also use
// an IdentityScale, LogScale, or PowScale
D3::LinearScale y_scale = D3::LinearScale();
// Set domain (possible input values)
y_scale.SetDomain(0, 1);
// Set range (possible output values)
y_scale.SetRange(0, 100);
// Convert value from domain to range
// This will be 100
double result = y_scale.ApplyScale(1);
// This will be 0
result = y_scale.ApplyScale(0);
// This will be 50
result = y_scale.ApplyScale(.5);
// Example data
emp::vector<int> data = {.1, .2, .3, .4, .5};
// Add SVG canvas to body, set its height to 100 (so our data
// fits)
D3::Selection svg = D3::Select("body")
.Append("svg")
.SetAttr("height", 100);
// make empty selection for circles,
// bind data to selection, and append circles for data
svg.SelectAll("circle")
.Data(data)
.Append("circle");
// Set y coordinate of circle centers based on y_scale
// Input to this function is the bound data, the index
// of the circles in the selection, and a placeholder
// value. Here, we use a lambda function, as it is a
// convenient way to put the y_scale in the proper scope.
circles.SetAttr("cy", [&y_scale](int d, int i, int j){
return y_scale.ApplyScale(d);
});
// Set cx and r so circles show up
circles.SetAttr("cx", 5).SetAttr("r", 3);
Great - we’ve used a scale to plot our data. But how are we supposed to know what the original data values were, now? With an axis object! Axes are a way of creating a visual representation of a scale:
// Make an axis object, templated off of
// the type of scale we're depicting
// We pass the constructor a string to tell it
// how to label the axis.
D3::Axis<D3::LinearScale> ax = D3::Axis<D3::LinearScale>("yvar");
// Set the axis to use our y scale
ax.SetScale(y_scale);
// This is a y axis, so we probably want it oriented
// vertically with the numbers and label on the left
ax.SetOrientation("left");
// Draw the axis onto our SVG object
ax.Draw(svg);
If you’re drawing both x and y axes, you may want to try using DrawAxes(), which attempts to make a smart guess about where to place them.
You’re not limited to working with numbers when you use scales. If you provide strings with color names (or hex representations), the scale will return an appropriately interpolated color. You can even provide an array of more than two numerical values to domain, and an array containing an equal number of colors to range, and D3 will interpolate appropriately. If you don’t want a continuous range of colors, try a categorical scale. The Category10Scale will assign colors to up to 10 different categorical values. The Category20Scale can handle 20.
Passing Functions as Arguments¶
In Javascript, it’s very common to pass functions as arguments to other functions in order to customize their behavior. This comes, in part, from the fact that a lot of Javascript code is exectured asynchronously. Since the goal of most Javscript is to run a web page, Javascript needs to respond to events such as user interactions (clicking, scrolling, etc.). It also needs to avoid delaying everything on the page just because there’s a picture it’s trying to load from a server that’s down. As a result, functions that require waiting for something to happen often accept a “callback function” as an argument. This function will get run when the function it was passed to is done. This way of programming can take some getting used to for people who are more used to more linear programming languages, but it’s hard to avoid when writing web code.
D3.js makes heavy use of functions-as-arguments. Most commonly, this happens when you’re trying to set attributes of graphical elements based on the data that is bound to them (as demonstrated in the section on binding data); you pass a function that takes a piece of data as an argument and returns the attribute value.
In Empirical, there are a number of ways to pass functions as arguments into d3 methods:
- Write the callback function as a regular C++ function, a C++ lambda function, or a std::function object and pass it into the d3 method.
int times_two(int d, int i, int j) {return d*2;};
int main() {
// Create an empty selection for circles on an svg canvas
// (assumes svg is already created). Bind data [1,2,3]
// to selection, and add a circle for each data point
D3::Selection s = Select("svg")
.SelectAll("circle")
.Data(emp::vector({1,2,3}))
.EnterAppend("circle");
// We can use either of the following two lines to set
// the circles' radii to be equal to two times their
// data point (1, 2, or 3). Here we use a normal C++
// function (could also be a std::function object)
s.SetAttr("r", times_two);
// Javascript will pass this function three things: the
// data (d) bound to an element (an int, in this case),
// an int (i) indicating the position of the element in
// the selection, and a third item that you
// don't need to worry about yet, but that requires an
// int parameter (j) as a placeholder
s.SetAttr("r", [](int d, int i, int j){return d * 2;});
- Pass the d3 method a string containing the name of a function that exists in Javascript (either one that has been created by empirical, one that you defined globally on the current webpage, or a d3 built-in function).
// For instance, if we wanted to sort our selection from
// the previous example, we could use d3's built-in
// "ascending" function:
s.sort("ascending");
- If you’re going to be repeatedly using a C++ function as a callback, you may improve the efficiency of your code by combining the two previous approaches, using Empirical’s JSWrap function.
// Creates a function in Javascript called "times_two"
// that calls times_two
emp::JSWrap(times_two, "times_two");
// Call the Javascript version of times_two
s.SetAttr("r", "times_two");
- Advanced users may also wish to write functions directly in Javascript, which is possible using Emscripten’s macros.
// Put the function in global scope by adding it
// to the current window
EM_ASM({window["times_two"] = function(d, i, j){return d*2;};});
// Call the Javascript version of times_two
s.SetAttr("r", "times_two");
All of these examples have assumed that the data points you’ve bound to your selection are ints. But most real-world data points are more complex than that (e.g. they may contain values for multiple variables). Javascript handles such data nicely by using JSON objects. You can write functions in C++ that accept JSON data from Javascript, but you have to tell C++ what data it should be expecting. An Empirical feature called introspective tuple structs provide a convenient way to do that, which JSWrap understands.
struct JSONData {
EMP_BUILD_INTROSPECTIVE_TUPLE( int, x,
int, y,
std::string, name
)
};
int get_x(JSONData d, int i, int j) {return d.x();};
// Assume s is a selection with a dataset already bound to it,
// and that that dataset contains JSON objects with the
// attributes described in the JSONData struct (x, y, and name).
// Set the "cx" attribute of the circle (the x position of the
// circle on your screen, in pixels) to the return of calling
// get_x on the data bound to each circle (i.e. the x value
// stored in the data point bound to a given circle)
s.SetAttr("cx", get_x);
Under the Hood (for the curious, developers, and people trying to do weird stuff)¶
For the most part, Empirical’s d3 wrapper isn’t that complicated under the hood. All C++ objects in the d3 module have a unique integer id. Most of them don’t actually store much more information. Instead, they serve as an interface to an object stored in Javascript. All Javascript objects that are being represented in C++ are stored in a Javascript array called js.objects. An object’s id is actually the index of the corresponding Javascript object in the js.objects array. Methods of that object reach into Javascript and call the corresponding method on the appropriate object. Some higher-level functions may call more than one d3 function.
The other piece of complexity that is hidden from the user is the translation between JSON objects in Javascript and objects created with EMP_BUILD_INTROSPECTIVE_TUPLE. This is all handled by JSWrap, which identifies objects created with EMP_BUILD_INTROSPECTIVE_TUPLE by looking for a member called n_fields. n_fields is created by EMP_BUILD_INTROSPECTIVE_TUPLE and indicates how many fields an object has. All conversion from C++ functions to javascript functions is handled by JSWrap (if you pass a function directly to a d3 method, JSWrap is called behind the scenes). This is why it is potentially more efficient to wrap functions once and pass the Javascript name as a string than to keep passing them as C++ functions and re-wrapping them every time. Rigorous tests on how much of a slow-down this introduces have not been conducted.
Things to watch out for:
- D3 object creation order - be careful of the order your constructors for d3 objects get called in. It’s hard to make this happen, but if you’re constructing objects in the constructors for other objects, it’s possible for the ids to get mixed up.
- Errors in Javascript usually won’t show up on compilation - you need to actually run the code.
- Main is a function that gets run like any other. When main finishes running, its local variables will go out of scope. This means that everything needed for an ongoing animation needs to live in global scope.
- Javascript is designed to work asynchronously in a lot of contexts (especially when loading outside resources or updating the graphics on the screen). This can change the way you need to structure your code.
D3 Wrapper API¶
Basic D3 Objects¶
-
namespace
D3
¶ Functions
-
int
NextD3ID
()¶
-
class
D3_Base
¶ - #include <d3_init.h>
A base object that all D3 objects inherit from. Handles storing the object in Javascript You probably don’t want to instantiate this directly
Subclassed by D3::Axis< D3::LinearScale >, D3::Axis< X_SCALE_TYPE >, D3::Axis< Y_SCALE_TYPE >, D3::Axis< SCALE_TYPE >, D3::Category10Scale, D3::Category20bScale, D3::Category20cScale, D3::Category20Scale, D3::Dataset, D3::FormatFunction, D3::Histogram, D3::JSFunction, D3::JSObject, D3::Layout, D3::Scale, D3::SelectionOrTransition< DERIVED >, D3::SvgShapeGenerator, D3::ToolTip, D3::SelectionOrTransition< Selection >, D3::SelectionOrTransition< Transition >
Protected Functions
-
D3_Base
()¶ Default constructor - adds placeholder to js.objects array in Javascript.
-
D3_Base
(int id)¶ Construct an object pointing to a pre-determined location in js.objects. Warning: This trusts that you know what you’re doing in choosing an id.
-
~D3_Base
()¶
Protected Attributes
-
int
id
¶
-
-
class
FormatFunction
: public D3::D3_Base¶ - #include <d3_init.h>
A callable string d3.format() string formatting function.
Protected Attributes
-
int
id
¶
-
int
-
class
JSFunction
: public D3::D3_Base¶ - #include <d3_init.h>
Wrapper for creating functions in javascript and calling them there.
Public Functions
-
JSFunction
()¶
-
void
operator()
()¶ Only works if function has no arguments or returns.
-
int
GetID
() const
-
void
Log
() const
Protected Attributes
-
int
id
-
-
class
JSObject
: public D3::D3_Base¶ - #include <d3_init.h>
Catch-all object for storing references to things created in JS.
Protected Attributes
-
int
id
-
int
-
class
ToolTip
: public D3::D3_Base¶ - #include <d3_init.h>
Create a tooltup using the d3.tip Javascript library.
Public Functions
-
ToolTip
()¶ Default constructor - displays whatever data is bound on mouseover.
-
ToolTip
(std::string func)¶ Cosntructor that allows you to specify a function that returns the html for the tooltip. As input, this function should take 3 parameters: the bound data, the index of this item in the selection (int), and a placeholder (int).
Example:
`D3::FormatFunction rounded = D3::FormatFunction(“.2f”);
std::function<double, int, int)> tooltip_display = [this](double d, int i, int k) {return “Data: ” + to_string(rounded(d));}
D3::ToolTip tip = D3::ToolTip(tooltip_display);
D3::Selection example_selection = D3::SelectAll(“circle”);
example_selection.SetupToolTip(tip);’
Mousing over a circle in the example selection will display “Data: ” followed by the value of d, rounded to two decimal points.
-
int
GetID
() const
-
void
Log
() const
Protected Attributes
-
int
id
-
-
int
Selections and Transitions¶
-
namespace
D3
¶ Functions
-
Selection
Select
(std::string selector)¶ Create a selection containing the first DOM element matching [selector] (convenience function to match D3 syntax - you can also just use the constructor)
-
Selection
SelectAll
(std::string selector)¶ Create a selection containing all DOM elements matching [selector] (convenience function to match D3 syntax - you can also just use the constructor)
-
class
Selection
: public D3::SelectionOrTransition<Selection>¶ - #include <selection.h>
Selections are the primary way that d3 allows you to operate on DOM elements (i.e. objects on your webpage). A selection is effectively an array of DOM elements that you can act on at the same time and bind a collection of data to.
For a deep dive into how selections work in d3, see this article.
Setters
There are three main types of values you might want to change about a selection: attributes (use
SetAttr
), styles (useSetStyle
), and properties (useSetProperty
). The distinction between these types is rooted in how they are represented in web languages (Javascript, CSS, and HTML) and would ideally be abstracted in this wrapper but can’t be.Additional traits you can set include text and html.
Advanced note: In D3.js, the same functions are used to set and get values (depending on whether an argument is passed). Because C++ needs to have clearly defined return types we need separate getters for each return type.
-
Selection &
SetAttr
(std::string name, std::string value)¶ Assigns [value] to the selection’s [name] attribute. Value can be any primitive type, a string, a function object, or a lambda. If a string is passed, it can be a normal string, or the name of a function in d3, emp (such as one created with JSWrap), or the local window. If it is a function name, that function will be run, receiving bound data, if any, as input
-
Selection &
SetStyle
(std::string name, std::string value, bool priority = false)¶ Sets the selection’s [name] style to [value]. This is the same idea as SetAttr, except for CSS styles. Value can be any primitive type, a string, a function object, or a lambda. If a string is passed, it can be a normal string, or the name of a function in d3, emp (such as one created with JSWrap), or the local window. If it is a function name, that function will be run, receiving bound data, if any, as input
There is a third optional argument, a boolean indicating whether you want to give this setting priority.
-
Selection &
SetText
(std::string text)¶ Sets this selection’s text to the specified string, or the string returned by running the specified function on the element’s bound data
-
Selection &
SetProperty
(std::string name, std::string value)¶ Sets special properties of DOM elements (e.g. “checked” for checkboxes) Value can be a number, function, string, or string naming a Javascript function See the d3 documentation for more information.
Advanced note: This is implemented differently for selection vs transitions. As such, calling it on a SelectionOrTransition object directly is not supported.
-
Selection &
SetHtml
(std::string value)¶ Sets this selection’s inner html to the specified string, or the string returned by running the specified function on the element’s bound data
Advanced note: This is implemented differently for selection vs transitions. As such, calling it on a SelectionOrTransition object directly is not supported.
-
Selection &
SetClassed
(std::string classname, bool value)¶ Change whether or not element in this selection have the [classname] class. Example: Add the data-point class with selection.SetClassed(“data-point”, true); Advanced note: This is implemented differently for selection vs transitions. As such, calling it on a SelectionOrTransition object directly is not supported.
Getters
There are three main types of values you might want to access about a selection: attributes (use
GetAttr
), styles (useGetStyle
), and properties (useGetProperty
). The distinction between these types is rooted in how they are represented in web languages (Javascript, CSS, and HTML) and would ideally be abstracted in this wrapper but can’t be.Additional traits you can set include text and html.
Advanced note: In D3.js, the same functions are used to set and get values (depending on whether an argument is passed). Because C++ needs to have clearly defined return types (and because different macros are required to return different types from Javascript), we need separate getters for each return type.
-
std::string
GetAttrString
(std::string name) const¶ Get the value of this object’s [name] attribute when it’s a string.
-
int
GetAttrInt
(std::string name) const¶ Get the value of this object’s [name] attribute when it’s an int.
-
double
GetAttrDouble
(std::string name) const¶ Get the value of this object’s [name] attribute when it’s a double.
-
std::string
GetStyleString
(std::string name) const¶ Get the value of this object’s [name] style when it’s a string.
-
int
GetStyleInt
(std::string name) const¶ Get the value of this object’s [name] style when it’s an int.
-
double
GetStyleDouble
(std::string name) const¶ Get the value of this object’s [name] style when it’s a double.
-
std::string
GetHtml
()¶ Get this object’s html
Advanced note: This is implemented differently for selection vs transitions. As such, calling it on a SelectionOrTransition object directly is not supported.
-
std::string
GetPropertyString
(std::string name)¶ Get the value of this object’s [name] property when its a string
Advanced note: This is implemented differently for selection vs transitions. As such, calling it on a SelectionOrTransition object directly is not supported.
-
int
GetPropertyInt
(std::string name)¶ Get the value of this object’s [name] property when it’s an int
Advanced note: This is implemented differently for selection vs transitions. As such, calling it on a SelectionOrTransition object directly is not supported.
-
double
GetPropertyDouble
(std::string name)¶ Get the value of this object’s [name] property when it’s a double
Advanced note: This is implemented differently for selection vs transitions. As such, calling it on a SelectionOrTransition object directly is not supported.
-
bool
Empty
() const¶ Returns true if there are no elements in this selection (or all elements are null)
-
int
Size
() const¶ Returns number of elements in this selection.
Constructors
You may prefer to use the Select or SelectAll functions for improved code clarity/consistency with d3.js
-
Selection
()¶ Default constructor - constructs empty selection.
-
Selection
(int id)¶ Create Selection object with a specific id.
Advanced note: This is useful when creating a Selection object to point to a selection
-
Selection
(std::string selector, bool all = false)¶ This is the Selection constructor you usually want to use. It takes a string saying what to select and a bool saying whether to select all elements matching that string [true] or just the first [false]
-
~Selection
()¶ Destructor.
Binding Data
This group of functions allows you to bind data to the current selection and deal with new data you have just bound (the enter selection) and data that was previously bound to to the selection but is not present in the set of data that was most recently bound (the exit selection)
The process of binding data to a selection is called a “join” in d3-speak. For more in-depth explanation, see this article.
-
Selection
Data
(Dataset &values, std::string key = "")¶ Bind data to selection. Accepts any contiguous container (such as an array or vector) or a D3::Dataset object (which stores the data Javascript). Optionally also accepts a key function to run on each element to determine which elements are equivalent (if no key is provided, elements are expected to be in the same order each time you bind data to this selection). This function can either be a string with the name of a function in Javascript, or it can be a C++ function pointer, std::function object, or lambda.
-
Dataset
GetData
() const¶
-
Selection
EnterAppend
(std::string type)¶ This function appends the specified type of nodes to this selection’s enter selection, which merges the enter selection with the update selection.
Selection must have an enter selection (i.e. have just had data bound to it).
-
Selection
EnterInsert
(std::string name, std::string before = NULL)¶ Insert elements of type [name] into current enter selection
For more information, see the D3 documention on insert
-
Selection
Enter
()¶ Sometimes you want to perform multiple operations on the enter selection. If so, you can use the Enter() method to get the enter selection, rather than using one of the convenience functions like EnterAppend().
Returns a selection object pointing at this selection’s enter selection.
-
void
ExitRemove
()¶ Selection must have an exit selection (i.e. have just had data bound to it).
Pretty much the only thing you ever want to do with the exit() selection is remove all of the nodes in it. This function does just that.
-
Selection
Exit
()¶ Usually the only thing you want to do with the exit selection is remove its contents, in which case you should use the ExitRemove method. However, advanced users may want to operate on the exit selection, which is why this method is provided.
Returns a selection object pointing at this selection’s exit selection.
Public Functions
-
Selection
Append
(std::string name)¶ Append DOM element(s) of the type specified by [name] to this selection.
-
Selection
Insert
(std::string name, std::string before = NULL)¶ Insert DOM element of type “name” into the current selection before the element selected by the element specified by the [before] string
For more information, see the D3 documention on insert
-
Transition
MakeTransition
(std::string name = "")¶ Create a transition from the current selection. If a [name] is specified the transition will be given that name
-
Transition
MakeTransition
(Transition &t)¶
-
Selection &
Interrupt
(std::string name = "")¶ Interrupt the transition with the name [name] on the current selection.
-
Selection &
Move
(int x, int y)¶ Move the elements in this selection by [x] in the x direction and [y] in the y direction. Note for advanced users: this method is just a shortcut for setting the “transform” attribute to “translate(x, y)”, because doing that is a pain in C++ (even more so than in Javascript)
-
Selection &
Rotate
(int degrees)¶ Rotate the elements in this selection by [degrees]. Note for advanced users: this method is just a shortcut for setting the “transform” attribute to “rotate(degrees)”, because doing that is a pain in C++ (even more so than in Javascript)
-
Selection &
Order
()¶ Change the order of elements in the document to match their order in this selection.
-
Selection &
On
(std::string type, std::string listener = "null", bool capture = false)¶ Listen for an event of type [type] and call [listener] when it happens [listener] can be a string containing the name of a Javascript function, or a C++ function
The third paramter for the listener function is the id of a selection containing the relevant DOM object.
To remove an event listener, call On with that type and “null” as the listener (default)
Advanced note: the optional capture flag invokes Javascript’s useCapture option
-
Selection &
Sort
(std::string comparator = "ascending")¶ Sort the selection by the given comparator function. The function can be a C++ function or a stirng indicating a function in the d3 namespace, the emp namespace (as results from JSWrapping C++ functions), or the window namespace. These three options are checked sequentially in that order, so a C++ function with the same name as d3 built-in will not override the built-in. Similarly, a function declared directly in the window will be overriden by a JSWrapped function with the same name.
-
Selection
Select
(std::string selector) const¶ Create a new selection/transition containing the first element matching the [selector] string that are within this current selection/transition
-
Selection
SelectAll
(std::string selector) const¶ Create a new selection/transition containing all elements matching the [selector] string that are within this current selection/transition
-
Selection &
Call
(std::string function)¶ Call the given function once on the entire selection/transition. [function] can either be a C++ function or a string with the name of a Javascript function in the d3, emp, or current window namespace. To get around the problem of passing selections into C++, this function assumes that the function you are passing expects a single argument: an int, representing the id of the selection to be operated on (which you can then convert to a selection object with
D3::Selection(i)
).
-
Selection
Filter
(std::string selector) const¶ Returns a new selection/transition, representing the current selection/transition filtered by [selector]. [selector] can be a C++ function that returns a bool, a string representing a function in either the d3, emp, or window namespaces that returns a bool, or a string containing a selector to filter by.
For more information see the D3 documentation
-
Selection &
Each
(std::string function)¶ Call the given function on each element of the selection/transition. [function] can either be a C++ function or a string with the name of a Javascript function in the d3, emp, or current window namespace.
-
void
Remove
()¶ Remove the elements in this selection/transition from the document For transitions, this happens at the end of the transition.
-
Selection &
-
template <typename DERIVED>
classSelectionOrTransition
: public D3::D3_Base¶ - #include <selection.h>
You probably never want to instantiate this class. Its sole purpose is to hold code for methods that are common to selections and transitions.
Developer note: It’s also handy if you want to allow a function to accept either a selection or transition. This is a good idea any time you are only using methods that are applicable to either, and the person calling the function may want to animate its results.
Setters
There are three main types of values you might want to change about a selection: attributes (use
SetAttr
), styles (useSetStyle
), and properties (useSetProperty
). The distinction between these types is rooted in how they are represented in web languages (Javascript, CSS, and HTML) and would ideally be abstracted in this wrapper but can’t be.Additional traits you can set include text and html.
Advanced note: In D3.js, the same functions are used to set and get values (depending on whether an argument is passed). Because C++ needs to have clearly defined return types we need separate getters for each return type.
-
DERIVED &
SetAttr
(std::string name, std::string value)¶ Assigns [value] to the selection’s [name] attribute. Value can be any primitive type, a string, a function object, or a lambda. If a string is passed, it can be a normal string, or the name of a function in d3, emp (such as one created with JSWrap), or the local window. If it is a function name, that function will be run, receiving bound data, if any, as input
-
DERIVED &
SetStyle
(std::string name, std::string value, bool priority = false)¶ Sets the selection’s [name] style to [value]. This is the same idea as SetAttr, except for CSS styles. Value can be any primitive type, a string, a function object, or a lambda. If a string is passed, it can be a normal string, or the name of a function in d3, emp (such as one created with JSWrap), or the local window. If it is a function name, that function will be run, receiving bound data, if any, as input
There is a third optional argument, a boolean indicating whether you want to give this setting priority.
-
DERIVED &
SetText
(std::string text)¶ Sets this selection’s text to the specified string, or the string returned by running the specified function on the element’s bound data
-
DERIVED &
SetProperty
(std::string name, std::string value)¶ Sets special properties of DOM elements (e.g. “checked” for checkboxes) Value can be a number, function, string, or string naming a Javascript function See the d3 documentation for more information.
Advanced note: This is implemented differently for selection vs transitions. As such, calling it on a SelectionOrTransition object directly is not supported.
-
DERIVED &
SetHtml
(std::string value)¶ Sets this selection’s inner html to the specified string, or the string returned by running the specified function on the element’s bound data
Advanced note: This is implemented differently for selection vs transitions. As such, calling it on a SelectionOrTransition object directly is not supported.
-
DERIVED &
SetClassed
(std::string classname, bool value)¶ Change whether or not element in this selection have the [classname] class. Example: Add the data-point class with selection.SetClassed(“data-point”, true); Advanced note: This is implemented differently for selection vs transitions. As such, calling it on a SelectionOrTransition object directly is not supported.
Getters
There are three main types of values you might want to access about a selection: attributes (use
GetAttr
), styles (useGetStyle
), and properties (useGetProperty
). The distinction between these types is rooted in how they are represented in web languages (Javascript, CSS, and HTML) and would ideally be abstracted in this wrapper but can’t be.Additional traits you can set include text and html.
Advanced note: In D3.js, the same functions are used to set and get values (depending on whether an argument is passed). Because C++ needs to have clearly defined return types (and because different macros are required to return different types from Javascript), we need separate getters for each return type.
-
std::string
GetAttrString
(std::string name) const¶ Get the value of this object’s [name] attribute when it’s a string.
-
int
GetAttrInt
(std::string name) const¶ Get the value of this object’s [name] attribute when it’s an int.
-
double
GetAttrDouble
(std::string name) const¶ Get the value of this object’s [name] attribute when it’s a double.
-
std::string
GetStyleString
(std::string name) const¶ Get the value of this object’s [name] style when it’s a string.
-
int
GetStyleInt
(std::string name) const¶ Get the value of this object’s [name] style when it’s an int.
-
double
GetStyleDouble
(std::string name) const¶ Get the value of this object’s [name] style when it’s a double.
-
std::string
GetHtml
()¶ Get this object’s html
Advanced note: This is implemented differently for selection vs transitions. As such, calling it on a SelectionOrTransition object directly is not supported.
-
std::string
GetPropertyString
(std::string name)¶ Get the value of this object’s [name] property when its a string
Advanced note: This is implemented differently for selection vs transitions. As such, calling it on a SelectionOrTransition object directly is not supported.
-
int
GetPropertyInt
(std::string name)¶ Get the value of this object’s [name] property when it’s an int
Advanced note: This is implemented differently for selection vs transitions. As such, calling it on a SelectionOrTransition object directly is not supported.
-
double
GetPropertyDouble
(std::string name)¶ Get the value of this object’s [name] property when it’s a double
Advanced note: This is implemented differently for selection vs transitions. As such, calling it on a SelectionOrTransition object directly is not supported.
-
bool
Empty
() const¶ Returns true if there are no elements in this selection (or all elements are null)
-
int
Size
() const¶ Returns number of elements in this selection.
Public Functions
-
SelectionOrTransition
()¶
-
SelectionOrTransition
(int id)¶
-
SelectionOrTransition
(const SelectionOrTransition<DERIVED> &s)¶
-
DERIVED
Select
(std::string selector) const¶ Create a new selection/transition containing the first element matching the [selector] string that are within this current selection/transition
-
DERIVED
SelectAll
(std::string selector) const¶ Create a new selection/transition containing all elements matching the [selector] string that are within this current selection/transition
-
DERIVED &
Call
(std::string function)¶ Call the given function once on the entire selection/transition. [function] can either be a C++ function or a string with the name of a Javascript function in the d3, emp, or current window namespace. To get around the problem of passing selections into C++, this function assumes that the function you are passing expects a single argument: an int, representing the id of the selection to be operated on (which you can then convert to a selection object with
D3::Selection(i)
).
-
DERIVED
Filter
(std::string selector) const¶ Returns a new selection/transition, representing the current selection/transition filtered by [selector]. [selector] can be a C++ function that returns a bool, a string representing a function in either the d3, emp, or window namespaces that returns a bool, or a string containing a selector to filter by.
For more information see the D3 documentation
-
DERIVED &
Each
(std::string function)¶ Call the given function on each element of the selection/transition. [function] can either be a C++ function or a string with the name of a Javascript function in the d3, emp, or current window namespace.
-
void
Remove
()¶ Remove the elements in this selection/transition from the document For transitions, this happens at the end of the transition.
-
DERIVED
Merge
(DERIVED &other)¶
-
DERIVED &
-
class
Transition
: public D3::SelectionOrTransition<Transition>¶ - #include <selection.h>
Transitions are similar to selections, but when you make a change to them (attr or style), it will be animated. For additional discussion of transitions in d3, see this article.
Setters
There are three main types of values you might want to change about a selection: attributes (use
SetAttr
), styles (useSetStyle
), and properties (useSetProperty
). The distinction between these types is rooted in how they are represented in web languages (Javascript, CSS, and HTML) and would ideally be abstracted in this wrapper but can’t be.Additional traits you can set include text and html.
Advanced note: In D3.js, the same functions are used to set and get values (depending on whether an argument is passed). Because C++ needs to have clearly defined return types we need separate getters for each return type.
-
Transition &
SetAttr
(std::string name, std::string value) Assigns [value] to the selection’s [name] attribute. Value can be any primitive type, a string, a function object, or a lambda. If a string is passed, it can be a normal string, or the name of a function in d3, emp (such as one created with JSWrap), or the local window. If it is a function name, that function will be run, receiving bound data, if any, as input
-
Transition &
SetStyle
(std::string name, std::string value, bool priority = false) Sets the selection’s [name] style to [value]. This is the same idea as SetAttr, except for CSS styles. Value can be any primitive type, a string, a function object, or a lambda. If a string is passed, it can be a normal string, or the name of a function in d3, emp (such as one created with JSWrap), or the local window. If it is a function name, that function will be run, receiving bound data, if any, as input
There is a third optional argument, a boolean indicating whether you want to give this setting priority.
-
Transition &
SetText
(std::string text) Sets this selection’s text to the specified string, or the string returned by running the specified function on the element’s bound data
-
Transition &
SetProperty
(std::string name, std::string value) Sets special properties of DOM elements (e.g. “checked” for checkboxes) Value can be a number, function, string, or string naming a Javascript function See the d3 documentation for more information.
Advanced note: This is implemented differently for selection vs transitions. As such, calling it on a SelectionOrTransition object directly is not supported.
-
Transition &
SetHtml
(std::string value) Sets this selection’s inner html to the specified string, or the string returned by running the specified function on the element’s bound data
Advanced note: This is implemented differently for selection vs transitions. As such, calling it on a SelectionOrTransition object directly is not supported.
-
Transition &
SetClassed
(std::string classname, bool value) Change whether or not element in this selection have the [classname] class. Example: Add the data-point class with selection.SetClassed(“data-point”, true); Advanced note: This is implemented differently for selection vs transitions. As such, calling it on a SelectionOrTransition object directly is not supported.
Getters
There are three main types of values you might want to access about a selection: attributes (use
GetAttr
), styles (useGetStyle
), and properties (useGetProperty
). The distinction between these types is rooted in how they are represented in web languages (Javascript, CSS, and HTML) and would ideally be abstracted in this wrapper but can’t be.Additional traits you can set include text and html.
Advanced note: In D3.js, the same functions are used to set and get values (depending on whether an argument is passed). Because C++ needs to have clearly defined return types (and because different macros are required to return different types from Javascript), we need separate getters for each return type.
-
std::string
GetAttrString
(std::string name) const Get the value of this object’s [name] attribute when it’s a string.
-
int
GetAttrInt
(std::string name) const Get the value of this object’s [name] attribute when it’s an int.
-
double
GetAttrDouble
(std::string name) const Get the value of this object’s [name] attribute when it’s a double.
-
std::string
GetStyleString
(std::string name) const Get the value of this object’s [name] style when it’s a string.
-
int
GetStyleInt
(std::string name) const Get the value of this object’s [name] style when it’s an int.
-
double
GetStyleDouble
(std::string name) const Get the value of this object’s [name] style when it’s a double.
-
std::string
GetText
() const Get this object’s text.
-
std::string
GetHtml
() Get this object’s html
Advanced note: This is implemented differently for selection vs transitions. As such, calling it on a SelectionOrTransition object directly is not supported.
-
std::string
GetPropertyString
(std::string name) Get the value of this object’s [name] property when its a string
Advanced note: This is implemented differently for selection vs transitions. As such, calling it on a SelectionOrTransition object directly is not supported.
-
int
GetPropertyInt
(std::string name) Get the value of this object’s [name] property when it’s an int
Advanced note: This is implemented differently for selection vs transitions. As such, calling it on a SelectionOrTransition object directly is not supported.
-
double
GetPropertyDouble
(std::string name) Get the value of this object’s [name] property when it’s a double
Advanced note: This is implemented differently for selection vs transitions. As such, calling it on a SelectionOrTransition object directly is not supported.
-
bool
Empty
() const Returns true if there are no elements in this selection (or all elements are null)
-
int
Size
() const Returns number of elements in this selection.
Constructors
Usually transitions are constructed from selections by calling the selection.MakeTransition() method. In rare cases you may want to construct a new transition, though.
-
Transition
()¶ Default constructor - construct empty transition.
-
Transition
(int id)¶ Advanced: Construct new transition pointing to the [id]th element in js.objects.
-
Transition
NewTransition
(std::string name = "") const¶ Create a transition from the current transition. If a [name] is specified the transition will be given that name
Note: In D3.js this method is just called transition(), but in C++ that would cause a collision with the constructor
Public Functions
-
Transition
Select
(std::string selector) const Create a new selection/transition containing the first element matching the [selector] string that are within this current selection/transition
-
Transition
SelectAll
(std::string selector) const Create a new selection/transition containing all elements matching the [selector] string that are within this current selection/transition
-
Transition &
Call
(std::string function) Call the given function once on the entire selection/transition. [function] can either be a C++ function or a string with the name of a Javascript function in the d3, emp, or current window namespace. To get around the problem of passing selections into C++, this function assumes that the function you are passing expects a single argument: an int, representing the id of the selection to be operated on (which you can then convert to a selection object with
D3::Selection(i)
).
-
Transition
Filter
(std::string selector) const Returns a new selection/transition, representing the current selection/transition filtered by [selector]. [selector] can be a C++ function that returns a bool, a string representing a function in either the d3, emp, or window namespaces that returns a bool, or a string containing a selector to filter by.
For more information see the D3 documentation
-
Transition &
Each
(std::string function) Call the given function on each element of the selection/transition. [function] can either be a C++ function or a string with the name of a Javascript function in the d3, emp, or current window namespace.
-
void
Remove
() Remove the elements in this selection/transition from the document For transitions, this happens at the end of the transition.
-
Transition
Merge
(Transition &other)¶
-
Transition &
-
Selection
Scales¶
Tools for scaling graph axes in D3.
- 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
-
namespace
D3
-
-
class
Category20cScale
: D3::D3_Base¶ - #include <scales.h>
Public Functions
-
Category20cScale
()¶
Protected Attributes
-
int
id
¶
-
-
class
IdentityScale
: public D3::Scale¶ - #include <scales.h>
Subclassed by D3::LinearScale
Public Functions
-
IdentityScale
()¶
-
IdentityScale
(bool derived)¶
-
template <typename T>
doubleInvert
(T y)¶
-
IdentityScale &
SetTicks
(int count)¶
-
IdentityScale &
SetTickFormat
(int count, std::string format)¶
-
template <typename T, size_t SIZE>
Scale &SetRange
(emp::array<T, SIZE> values)¶ Set the output values corresponding to values in the domain. Output for values in between will be interpolated with a function determined by the type of the scale. Array should contain same number of elements as the one used to set the domain.
-
template <typename T, size_t SIZE>
Scale &SetDomain
(emp::array<T, SIZE> values)¶ Set the input values corresponding to values in the range. Array should contain same number of elements as the one used to set the range.
-
double
ApplyScale
(double input)¶ Calculate the ouput for [input], based on the scale’s scaling function.
-
int
ApplyScale
(int input)¶
-
-
class
LinearScale
: public D3::IdentityScale¶ - #include <scales.h>
Subclassed by D3::LogScale, D3::PowScale, D3::TimeScale
Public Functions
-
LinearScale
()¶
-
LinearScale
(bool derived)¶
-
template <typename T, size_t SIZE>
LinearScale &SetRangeRound
(emp::array<T, SIZE> values)¶
-
LinearScale &
SetRangeRound
(double min, double max)¶
-
LinearScale &
SetInterpolate
(std::string factory)¶
-
LinearScale &
Clamp
(bool clamp)¶
-
LinearScale &
Nice
(int count = -1)¶
-
template <typename T>
doubleInvert
(T y)¶
-
IdentityScale &
SetTicks
(int count)¶
-
IdentityScale &
SetTickFormat
(int count, std::string format)¶
-
template <typename T, size_t SIZE>
Scale &SetRange
(emp::array<T, SIZE> values)¶ Set the output values corresponding to values in the domain. Output for values in between will be interpolated with a function determined by the type of the scale. Array should contain same number of elements as the one used to set the domain.
-
template <typename T, size_t SIZE>
Scale &SetDomain
(emp::array<T, SIZE> values)¶ Set the input values corresponding to values in the range. Array should contain same number of elements as the one used to set the range.
-
double
ApplyScale
(double input)¶ Calculate the ouput for [input], based on the scale’s scaling function.
-
int
ApplyScale
(int input)¶
-
-
class
LogScale
: public D3::LinearScale¶ - #include <scales.h>
Public Functions
-
LogScale
()¶
-
LogScale
(bool derived)¶
-
template <typename T, size_t SIZE>
LinearScale &SetRangeRound
(emp::array<T, SIZE> values)¶
-
LinearScale &
SetRangeRound
(double min, double max)¶
-
LinearScale &
SetInterpolate
(std::string factory)¶
-
LinearScale &
Clamp
(bool clamp)¶
-
LinearScale &
Nice
(int count = -1)¶
-
template <typename T>
doubleInvert
(T y)
-
IdentityScale &
SetTicks
(int count)
-
IdentityScale &
SetTickFormat
(int count, std::string format)
-
template <typename T, size_t SIZE>
Scale &SetRange
(emp::array<T, SIZE> values) Set the output values corresponding to values in the domain. Output for values in between will be interpolated with a function determined by the type of the scale. Array should contain same number of elements as the one used to set the domain.
-
Scale &
SetRange
(double min, double max)
-
template <typename T, size_t SIZE>
Scale &SetDomain
(emp::array<T, SIZE> values) Set the input values corresponding to values in the range. Array should contain same number of elements as the one used to set the range.
-
Scale &
SetDomain
(double min, double max)
-
Scale
Copy
() Make a copy of this scale.
-
double
ApplyScale
(double input) Calculate the ouput for [input], based on the scale’s scaling function.
-
int
ApplyScale
(int input)
-
-
class
OrdinalScale
: public D3::QuantizeScale¶ - #include <scales.h>
Public Functions
-
OrdinalScale
()¶
-
OrdinalScale
(bool derived)¶
-
template <typename T>
doubleInvertExtent
(T y)¶
-
template <typename T, size_t SIZE>
Scale &SetRange
(emp::array<T, SIZE> values) Set the output values corresponding to values in the domain. Output for values in between will be interpolated with a function determined by the type of the scale. Array should contain same number of elements as the one used to set the domain.
-
Scale &
SetRange
(double min, double max)
-
template <typename T, size_t SIZE>
Scale &SetDomain
(emp::array<T, SIZE> values) Set the input values corresponding to values in the range. Array should contain same number of elements as the one used to set the range.
-
Scale &
SetDomain
(double min, double max)
-
Scale
Copy
() Make a copy of this scale.
-
double
ApplyScale
(double input) Calculate the ouput for [input], based on the scale’s scaling function.
-
int
ApplyScale
(int input)
-
-
class
PowScale
: public D3::LinearScale¶ - #include <scales.h>
Public Functions
-
PowScale
()¶
-
PowScale
(bool derived)¶
-
template <typename T, size_t SIZE>
LinearScale &SetRangeRound
(emp::array<T, SIZE> values)
-
LinearScale &
SetRangeRound
(double min, double max)
-
LinearScale &
SetInterpolate
(std::string factory)
-
LinearScale &
Clamp
(bool clamp)
-
LinearScale &
Nice
(int count = -1)
-
template <typename T>
doubleInvert
(T y)
-
IdentityScale &
SetTicks
(int count)
-
IdentityScale &
SetTickFormat
(int count, std::string format)
-
template <typename T, size_t SIZE>
Scale &SetRange
(emp::array<T, SIZE> values) Set the output values corresponding to values in the domain. Output for values in between will be interpolated with a function determined by the type of the scale. Array should contain same number of elements as the one used to set the domain.
-
Scale &
SetRange
(double min, double max)
-
template <typename T, size_t SIZE>
Scale &SetDomain
(emp::array<T, SIZE> values) Set the input values corresponding to values in the range. Array should contain same number of elements as the one used to set the range.
-
Scale &
SetDomain
(double min, double max)
-
Scale
Copy
() Make a copy of this scale.
-
double
ApplyScale
(double input) Calculate the ouput for [input], based on the scale’s scaling function.
-
int
ApplyScale
(int input)
-
-
class
QuantileScale
: public D3::QuantizeScale¶ - #include <scales.h>
Public Functions
-
QuantileScale
()¶
-
QuantileScale
(bool derived)¶
-
template <typename T>
doubleInvertExtent
(T y)¶
-
template <typename T, size_t SIZE>
Scale &SetRange
(emp::array<T, SIZE> values) Set the output values corresponding to values in the domain. Output for values in between will be interpolated with a function determined by the type of the scale. Array should contain same number of elements as the one used to set the domain.
-
Scale &
SetRange
(double min, double max)
-
template <typename T, size_t SIZE>
Scale &SetDomain
(emp::array<T, SIZE> values) Set the input values corresponding to values in the range. Array should contain same number of elements as the one used to set the range.
-
Scale &
SetDomain
(double min, double max)
-
Scale
Copy
() Make a copy of this scale.
-
double
ApplyScale
(double input) Calculate the ouput for [input], based on the scale’s scaling function.
-
int
ApplyScale
(int input)
-
-
class
QuantizeScale
: public D3::Scale¶ - #include <scales.h>
Subclassed by D3::OrdinalScale, D3::QuantileScale, D3::ThresholdScale
Public Functions
-
QuantizeScale
()¶
-
QuantizeScale
(bool derived)¶
-
template <typename T>
doubleInvertExtent
(T y)
-
template <typename T, size_t SIZE>
Scale &SetRange
(emp::array<T, SIZE> values) Set the output values corresponding to values in the domain. Output for values in between will be interpolated with a function determined by the type of the scale. Array should contain same number of elements as the one used to set the domain.
-
Scale &
SetRange
(double min, double max)
-
template <typename T, size_t SIZE>
Scale &SetDomain
(emp::array<T, SIZE> values) Set the input values corresponding to values in the range. Array should contain same number of elements as the one used to set the range.
-
Scale &
SetDomain
(double min, double max)
-
Scale
Copy
() Make a copy of this scale.
-
double
ApplyScale
(double input) Calculate the ouput for [input], based on the scale’s scaling function.
-
int
ApplyScale
(int input)
-
-
class
Scale
: public D3::D3_Base¶ - #include <scales.h>
Scales in D3 are functions that take input values and map them to output based on a scaling function. They are often used to map data calues to x, y coordinates in pixels describing where on the screen elements should be placed. This is a base class to inherit from - should never be made stand-alone
Subclassed by D3::IdentityScale, D3::QuantizeScale
Public Functions
-
Scale
()¶
-
Scale
(bool derived)¶ Decoy constructor so we don’t construct extra base scales.
-
template <typename T, size_t SIZE>
Scale &SetRange
(emp::array<T, SIZE> values) Set the output values corresponding to values in the domain. Output for values in between will be interpolated with a function determined by the type of the scale. Array should contain same number of elements as the one used to set the domain.
-
Scale &
SetRange
(double min, double max)
-
template <typename T, size_t SIZE>
Scale &SetDomain
(emp::array<T, SIZE> values) Set the input values corresponding to values in the range. Array should contain same number of elements as the one used to set the range.
-
Scale &
SetDomain
(double min, double max)
-
Scale
Copy
() Make a copy of this scale.
-
double
ApplyScale
(double input) Calculate the ouput for [input], based on the scale’s scaling function.
-
int
ApplyScale
(int input)
Protected Functions
-
Scale
(int id)¶
-
-
class
ThresholdScale
: public D3::QuantizeScale¶ - #include <scales.h>
Public Functions
-
ThresholdScale
()¶
-
ThresholdScale
(bool derived)¶
-
template <typename T>
doubleInvertExtent
(T y)
-
template <typename T, size_t SIZE>
Scale &SetRange
(emp::array<T, SIZE> values) Set the output values corresponding to values in the domain. Output for values in between will be interpolated with a function determined by the type of the scale. Array should contain same number of elements as the one used to set the domain.
-
Scale &
SetRange
(double min, double max)
-
template <typename T, size_t SIZE>
Scale &SetDomain
(emp::array<T, SIZE> values) Set the input values corresponding to values in the range. Array should contain same number of elements as the one used to set the range.
-
Scale &
SetDomain
(double min, double max)
-
Scale
Copy
() Make a copy of this scale.
-
double
ApplyScale
(double input) Calculate the ouput for [input], based on the scale’s scaling function.
-
int
ApplyScale
(int input)
-
-
class
TimeScale
: public D3::LinearScale¶ - #include <scales.h>
Public Functions
-
TimeScale
()¶
-
TimeScale
(bool derived)¶
-
template <typename T, size_t SIZE>
LinearScale &SetRangeRound
(emp::array<T, SIZE> values)
-
LinearScale &
SetRangeRound
(double min, double max)
-
LinearScale &
SetInterpolate
(std::string factory)
-
LinearScale &
Clamp
(bool clamp)
-
LinearScale &
Nice
(int count = -1)
-
template <typename T>
doubleInvert
(T y)
-
IdentityScale &
SetTicks
(int count)
-
IdentityScale &
SetTickFormat
(int count, std::string format)
-
template <typename T, size_t SIZE>
Scale &SetRange
(emp::array<T, SIZE> values) Set the output values corresponding to values in the domain. Output for values in between will be interpolated with a function determined by the type of the scale. Array should contain same number of elements as the one used to set the domain.
-
Scale &
SetRange
(double min, double max)
-
template <typename T, size_t SIZE>
Scale &SetDomain
(emp::array<T, SIZE> values) Set the input values corresponding to values in the range. Array should contain same number of elements as the one used to set the range.
-
Scale &
SetDomain
(double min, double max)
-
Scale
Copy
() Make a copy of this scale.
-
double
ApplyScale
(double input) Calculate the ouput for [input], based on the scale’s scaling function.
-
int
ApplyScale
(int input)
-
-
class
Axes¶
Handle drawing of axes on D3 graphts.
- 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
- 2017-2018
-
namespace
D3
Functions
-
template <typename SCALE_X_TYPE = D3::LinearScale, typename SCALE_Y_TYPE = D3::LinearScale>
voidDrawAxes
(Axis<SCALE_X_TYPE> &x_axis, Axis<SCALE_Y_TYPE> &y_axis, Selection &selection)¶ Helper function to draw a standard set of x and y axes Takes the desired x axis, y axis, and the selection on which to draw them
-
template <typename SCALE_TYPE = LinearScale>
classAxis
: public D3::D3_Base¶ - #include <axis.h>
Axis objects are in charge of drawing graphical axes onto svg canvases. An axis depicts a scale, so every axis has a scale, and is templated off of the type of that scale.
Public Functions
-
Axis
(std::string type, std::string label = "")¶ Consruct an axis - this doesn’t draw anything yet, but sets up the necessary infrastructure to draw it when you call the Draw method. Optionally takes a label to label the axis with. This label will also be used to create an id for the axis, to make it easier to select it later. The id will be the same as [label], but with all whitespace removed and “_axis” appended to the end.
For example, if your label was “Per capita mortality”, you could select the axis with:
D3::Select("#Percapitamortality_axis");
.
-
Axis &
Draw
(Selection &selection)¶ Draw axis on [selection] (must contain a single SVG element) with intelligent default positioning
-
template <typename T>
Axis &ApplyAxis
(const SelectionOrTransition<T> &selection)¶
-
Axis &
SetScale
(SCALE_TYPE &scale)¶ An axis must have a scale. By default, a scale of SCALE_TYPE will be constructed, but usually you want an axis to depict a specific scale. This method points this object’s scale member variable at [scale].
-
SCALE_TYPE &
GetScale
()¶ Get a reference to this object’s scale.
-
Axis &
AdjustLabelOffset
(std::string offset)¶ Adjust the location of the label text relative to the axis (helpful if numbers are overlapping it). Can be negative. Use “em” (e.g. “2em”) to specify distance relative to font size.
-
Axis &
Move
(int x, int y)¶ Draw tries to make a good guess about where to place the axis, but sometimes you want to scoot it over. This method will move the axis to the x,y location specified.
-
Axis &
SetTickFormat
(std::string format)¶ Set the format for displaying numbers assoiated with ticks. [format] should be a format following the rules for d3.format()
-
template <typename T>
Axis &Rescale
(double new_min, double new_max, const D3::SelectionOrTransition<T> &svg)¶ Adjust scale and axis to accomodate the new range of data specified by [new_min], and [new_max]. [svg] is a Selection or Transition containing the current axis. If it’s a transition, then the rescaling will be animated.
Public Members
-
-
template <typename SCALE_X_TYPE = D3::LinearScale, typename SCALE_Y_TYPE = D3::LinearScale>
SVG Shapes and Paths¶
Tools to build common SVG shapes.
- 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
-
namespace
D3
-
class
ArcGenerator
: public D3::RadialAreaGenerator¶ - #include <svg_shapes.h>
Public Functions
-
ArcGenerator
()¶
-
void
SetCornerRadius
(float radius)¶
-
void
SetPadRadius
(float radius)¶
-
void
SetPadAngle
(float angle)¶
-
void
SetInnerRadius
(float radius)¶
-
void
SetOuterRadius
(float radius)¶
-
void
SetStartAngle
(float angle)¶
-
void
SetEndAngle
(float angle)¶
-
void
SetRadius
(float radius)¶
-
void
SetAngle
(float angle)¶
-
void
SetCurve
(std::string curve)¶ Set the method used to interpolate a curve between points in the line. For allowed options, see the d3 documntation
-
void
SetTension
(float tension)¶ If interpolation is “bundle”, “cardinal”, “cardinal-open”, or “cardinal-closed”, a tension parameter is used.
-
void
SetDefined
(std::string defined)¶ Set a function indicating where the line is defined (i.e. valid) Can be a C++ function or a string indicating a Javascript function
-
template <typename T, size_t SIZE>
std::stringGenerate
(emp::array<emp::array<T, 2>, SIZE> &data)¶ Generate the string describing the path associated with [data] Assumes [data] is an array of 2-element arrays describing (x,y) coordinates and makes the line that connects them
-
-
class
AreaGenerator
: public D3::LineGenerator¶ - #include <svg_shapes.h>
An area is defined by two lines, with the area in between shaded.
Public Functions
-
AreaGenerator
()¶
-
template <typename T>
voidSetX0
(T x)¶
-
template <typename T>
voidSetY0
(T y)¶
-
template <typename T>
voidSetX1
(T x)¶
-
template <typename T>
voidSetY1
(T y)¶
-
template <typename X_SCALE_TYPE>
voidAddXScale
(X_SCALE_TYPE &scale)¶ Often, when you’re drawing cartesion lines, you want to use a scale to transform numbers from range of your data to the range of pixels on your screen. Adding an X scale will cause the x-coordinates of all points on the line to be passed through that scale function. This stacks on top of whatever the current function for accessing x is (which means scales will also stack).
-
template <typename Y_SCALE_TYPE>
voidAddYScale
(Y_SCALE_TYPE &scale)¶ Often, when you’re drawing cartesion lines, you want to use a scale to transform numbers from range of your data to the range of pixels on your screen. Adding a Y scale will cause the y-coordinates of all points on the line to be passed through that scale function. This stacks on top of whatever the current function for accessing y is (which means scales will also stack).
-
void
SetX
(std::string x)¶ If the data that you are generating lines from is anything more complicated than a sequence of pairs of numbers, representing x and y (in that order), you need to tell the line generator how it should figure out what the x coordinate of a point in the line is. The parameter you pass to SetX should be instructions for doing so. It can either be a function (as a string indicating a Javascript function or as a literal C++ function) that accepts an element of the data sequence you are generating the line from, or it can be a constant, in which case the x coordinate of every point will be that constant.
Note: This function will re-set any scales that you’ve added to the X coordinate
As an example, the default function expects data like this (array of arrays): [[0,0], [1,1], [2,2]] And has (a Javascript equivalent of) this accessor: int x(emp::array<int, 2> d) {return d[0];}
If your data instead looked like this (array of Javascript objects with x and y values): [{x:0, y:0}, {x:1, y:1}, {x:2, y:2}] You might want to use an accessor like this: int x(JSONObject d) {return d.x();} Where JSONObject is a struct designed to hold necessary data from the Javascript object: struct JSONObject { EMP_BUILD_INTROSPECTIVE_TUPLE( int, x, int, y ) };
-
void
SetY
(std::string y)¶ If the data that you are generating lines from is anything more complicated than a sequence of pairs of numbers, representing x and y (in that order), you need to tell the line generator how it should figure out what the y coordinate of a point in the line is. The parameter you pass to SetY should be instructions for doing so. It can either be a function (as a string indicating a Javascript function or as a literal C++ function) that accepts an element of the data sequence you are generating the line from, or it can be a constant, in which case the y coordinate of every point will be that constant.
Note: This function will re-set any scales that you’ve added to the Y coordinate
As an example, the default function expects data like this (array of arrays): [[0,0], [1,1], [2,2]] And has (a Javascript equivalent of) this accessor: int x(emp::array<int, 2> d) {return d[1];}
If your data instead looked like this (array of Javascript objects with x and y values): [{x:0, y:0}, {x:1, y:1}, {x:2, y:2}] You might want to use an accessor like this: int x(JSONObject d) {return d.y();} Where JSONObject is a struct designed to hold necessary data from the Javascript object: struct JSONObject { EMP_BUILD_INTROSPECTIVE_TUPLE( int, x, int, y ) };
-
void
SetCurve
(std::string curve)¶ Set the method used to interpolate a curve between points in the line. For allowed options, see the d3 documntation
-
void
SetTension
(float tension)¶ If interpolation is “bundle”, “cardinal”, “cardinal-open”, or “cardinal-closed”, a tension parameter is used.
-
void
SetDefined
(std::string defined)¶ Set a function indicating where the line is defined (i.e. valid) Can be a C++ function or a string indicating a Javascript function
-
template <typename T, size_t SIZE>
std::stringGenerate
(emp::array<emp::array<T, 2>, SIZE> &data)¶ Generate the string describing the path associated with [data] Assumes [data] is an array of 2-element arrays describing (x,y) coordinates and makes the line that connects them
-
-
class
BaseLineGenerator
: public D3::SvgShapeGenerator¶ - #include <svg_shapes.h>
Base class for generating both cartesian and radial lines You don’t normally want to instantiate this - use LineGenerator or RadialLineGenerator instead.
Subclassed by D3::LineGenerator, D3::RadialLineGenerator
Public Functions
-
BaseLineGenerator
()¶
-
void
SetCurve
(std::string curve) Set the method used to interpolate a curve between points in the line. For allowed options, see the d3 documntation
-
void
SetTension
(float tension) If interpolation is “bundle”, “cardinal”, “cardinal-open”, or “cardinal-closed”, a tension parameter is used.
-
void
SetDefined
(std::string defined) Set a function indicating where the line is defined (i.e. valid) Can be a C++ function or a string indicating a Javascript function
-
template <typename T, size_t SIZE>
std::stringGenerate
(emp::array<emp::array<T, 2>, SIZE> &data) Generate the string describing the path associated with [data] Assumes [data] is an array of 2-element arrays describing (x,y) coordinates and makes the line that connects them
-
-
class
ChordGenerator
: public D3::RadialAreaGenerator¶ - #include <svg_shapes.h>
Public Functions
-
ChordGenerator
()¶
-
template <typename T>
voidSetSource
(T source)¶
-
template <typename T>
voidSetTarget
(T target)¶
-
void
SetInnerRadius
(float radius)¶
-
void
SetOuterRadius
(float radius)¶
-
void
SetStartAngle
(float angle)¶
-
void
SetEndAngle
(float angle)¶
-
void
SetRadius
(float radius)¶
-
void
SetAngle
(float angle)¶
-
void
SetCurve
(std::string curve) Set the method used to interpolate a curve between points in the line. For allowed options, see the d3 documntation
-
void
SetTension
(float tension) If interpolation is “bundle”, “cardinal”, “cardinal-open”, or “cardinal-closed”, a tension parameter is used.
-
void
SetDefined
(std::string defined) Set a function indicating where the line is defined (i.e. valid) Can be a C++ function or a string indicating a Javascript function
-
template <typename T, size_t SIZE>
std::stringGenerate
(emp::array<emp::array<T, 2>, SIZE> &data) Generate the string describing the path associated with [data] Assumes [data] is an array of 2-element arrays describing (x,y) coordinates and makes the line that connects them
-
-
class
LineGenerator
: public D3::BaseLineGenerator¶ - #include <svg_shapes.h>
Generator for regular old (cartesian) lines.
Subclassed by D3::AreaGenerator, D3::LinkGenerator
Public Functions
-
LineGenerator
()¶
-
template <typename X_SCALE_TYPE>
voidAddXScale
(X_SCALE_TYPE &scale)¶ Often, when you’re drawing cartesion lines, you want to use a scale to transform numbers from range of your data to the range of pixels on your screen. Adding an X scale will cause the x-coordinates of all points on the line to be passed through that scale function. This stacks on top of whatever the current function for accessing x is (which means scales will also stack).
-
template <typename Y_SCALE_TYPE>
voidAddYScale
(Y_SCALE_TYPE &scale)¶ Often, when you’re drawing cartesion lines, you want to use a scale to transform numbers from range of your data to the range of pixels on your screen. Adding a Y scale will cause the y-coordinates of all points on the line to be passed through that scale function. This stacks on top of whatever the current function for accessing y is (which means scales will also stack).
-
void
SetX
(std::string x)¶ If the data that you are generating lines from is anything more complicated than a sequence of pairs of numbers, representing x and y (in that order), you need to tell the line generator how it should figure out what the x coordinate of a point in the line is. The parameter you pass to SetX should be instructions for doing so. It can either be a function (as a string indicating a Javascript function or as a literal C++ function) that accepts an element of the data sequence you are generating the line from, or it can be a constant, in which case the x coordinate of every point will be that constant.
Note: This function will re-set any scales that you’ve added to the X coordinate
As an example, the default function expects data like this (array of arrays): [[0,0], [1,1], [2,2]] And has (a Javascript equivalent of) this accessor: int x(emp::array<int, 2> d) {return d[0];}
If your data instead looked like this (array of Javascript objects with x and y values): [{x:0, y:0}, {x:1, y:1}, {x:2, y:2}] You might want to use an accessor like this: int x(JSONObject d) {return d.x();} Where JSONObject is a struct designed to hold necessary data from the Javascript object: struct JSONObject { EMP_BUILD_INTROSPECTIVE_TUPLE( int, x, int, y ) };
-
void
SetY
(std::string y)¶ If the data that you are generating lines from is anything more complicated than a sequence of pairs of numbers, representing x and y (in that order), you need to tell the line generator how it should figure out what the y coordinate of a point in the line is. The parameter you pass to SetY should be instructions for doing so. It can either be a function (as a string indicating a Javascript function or as a literal C++ function) that accepts an element of the data sequence you are generating the line from, or it can be a constant, in which case the y coordinate of every point will be that constant.
Note: This function will re-set any scales that you’ve added to the Y coordinate
As an example, the default function expects data like this (array of arrays): [[0,0], [1,1], [2,2]] And has (a Javascript equivalent of) this accessor: int x(emp::array<int, 2> d) {return d[1];}
If your data instead looked like this (array of Javascript objects with x and y values): [{x:0, y:0}, {x:1, y:1}, {x:2, y:2}] You might want to use an accessor like this: int x(JSONObject d) {return d.y();} Where JSONObject is a struct designed to hold necessary data from the Javascript object: struct JSONObject { EMP_BUILD_INTROSPECTIVE_TUPLE( int, x, int, y ) };
-
void
SetCurve
(std::string curve) Set the method used to interpolate a curve between points in the line. For allowed options, see the d3 documntation
-
void
SetTension
(float tension) If interpolation is “bundle”, “cardinal”, “cardinal-open”, or “cardinal-closed”, a tension parameter is used.
-
void
SetDefined
(std::string defined) Set a function indicating where the line is defined (i.e. valid) Can be a C++ function or a string indicating a Javascript function
-
template <typename T, size_t SIZE>
std::stringGenerate
(emp::array<emp::array<T, 2>, SIZE> &data) Generate the string describing the path associated with [data] Assumes [data] is an array of 2-element arrays describing (x,y) coordinates and makes the line that connects them
-
-
class
LinkGenerator
: public D3::LineGenerator¶ - #include <svg_shapes.h>
Public Functions
-
template <typename X_SCALE_TYPE>
voidAddXScale
(X_SCALE_TYPE &scale) Often, when you’re drawing cartesion lines, you want to use a scale to transform numbers from range of your data to the range of pixels on your screen. Adding an X scale will cause the x-coordinates of all points on the line to be passed through that scale function. This stacks on top of whatever the current function for accessing x is (which means scales will also stack).
-
template <typename Y_SCALE_TYPE>
voidAddYScale
(Y_SCALE_TYPE &scale) Often, when you’re drawing cartesion lines, you want to use a scale to transform numbers from range of your data to the range of pixels on your screen. Adding a Y scale will cause the y-coordinates of all points on the line to be passed through that scale function. This stacks on top of whatever the current function for accessing y is (which means scales will also stack).
-
void
SetX
(std::string x) If the data that you are generating lines from is anything more complicated than a sequence of pairs of numbers, representing x and y (in that order), you need to tell the line generator how it should figure out what the x coordinate of a point in the line is. The parameter you pass to SetX should be instructions for doing so. It can either be a function (as a string indicating a Javascript function or as a literal C++ function) that accepts an element of the data sequence you are generating the line from, or it can be a constant, in which case the x coordinate of every point will be that constant.
Note: This function will re-set any scales that you’ve added to the X coordinate
As an example, the default function expects data like this (array of arrays): [[0,0], [1,1], [2,2]] And has (a Javascript equivalent of) this accessor: int x(emp::array<int, 2> d) {return d[0];}
If your data instead looked like this (array of Javascript objects with x and y values): [{x:0, y:0}, {x:1, y:1}, {x:2, y:2}] You might want to use an accessor like this: int x(JSONObject d) {return d.x();} Where JSONObject is a struct designed to hold necessary data from the Javascript object: struct JSONObject { EMP_BUILD_INTROSPECTIVE_TUPLE( int, x, int, y ) };
-
void
SetY
(std::string y) If the data that you are generating lines from is anything more complicated than a sequence of pairs of numbers, representing x and y (in that order), you need to tell the line generator how it should figure out what the y coordinate of a point in the line is. The parameter you pass to SetY should be instructions for doing so. It can either be a function (as a string indicating a Javascript function or as a literal C++ function) that accepts an element of the data sequence you are generating the line from, or it can be a constant, in which case the y coordinate of every point will be that constant.
Note: This function will re-set any scales that you’ve added to the Y coordinate
As an example, the default function expects data like this (array of arrays): [[0,0], [1,1], [2,2]] And has (a Javascript equivalent of) this accessor: int x(emp::array<int, 2> d) {return d[1];}
If your data instead looked like this (array of Javascript objects with x and y values): [{x:0, y:0}, {x:1, y:1}, {x:2, y:2}] You might want to use an accessor like this: int x(JSONObject d) {return d.y();} Where JSONObject is a struct designed to hold necessary data from the Javascript object: struct JSONObject { EMP_BUILD_INTROSPECTIVE_TUPLE( int, x, int, y ) };
-
void
SetCurve
(std::string curve) Set the method used to interpolate a curve between points in the line. For allowed options, see the d3 documntation
-
void
SetTension
(float tension) If interpolation is “bundle”, “cardinal”, “cardinal-open”, or “cardinal-closed”, a tension parameter is used.
-
void
SetDefined
(std::string defined) Set a function indicating where the line is defined (i.e. valid) Can be a C++ function or a string indicating a Javascript function
-
template <typename T, size_t SIZE>
std::stringGenerate
(emp::array<emp::array<T, 2>, SIZE> &data) Generate the string describing the path associated with [data] Assumes [data] is an array of 2-element arrays describing (x,y) coordinates and makes the line that connects them
-
template <typename X_SCALE_TYPE>
-
class
RadialAreaGenerator
: public D3::RadialLineGenerator¶ - #include <svg_shapes.h>
Subclassed by D3::ArcGenerator, D3::ChordGenerator
Public Functions
-
RadialAreaGenerator
()¶
-
void
SetInnerRadius
(float radius)
-
void
SetInnerRadius
(std::string radius)
-
void
SetOuterRadius
(float radius)
-
void
SetOuterRadius
(std::string radius)
-
void
SetStartAngle
(float angle)
-
void
SetStartAngle
(std::string angle)
-
void
SetEndAngle
(float angle)
-
void
SetEndAngle
(std::string angle)
-
void
SetRadius
(float radius)
-
void
SetRadius
(std::string radius)
-
void
SetAngle
(float angle)
-
void
SetAngle
(std::string angle)
-
void
SetCurve
(std::string curve) Set the method used to interpolate a curve between points in the line. For allowed options, see the d3 documntation
-
void
SetTension
(float tension) If interpolation is “bundle”, “cardinal”, “cardinal-open”, or “cardinal-closed”, a tension parameter is used.
-
void
SetDefined
(std::string defined) Set a function indicating where the line is defined (i.e. valid) Can be a C++ function or a string indicating a Javascript function
-
template <typename T, size_t SIZE>
std::stringGenerate
(emp::array<emp::array<T, 2>, SIZE> &data) Generate the string describing the path associated with [data] Assumes [data] is an array of 2-element arrays describing (x,y) coordinates and makes the line that connects them
-
-
class
RadialLineGenerator
: public D3::BaseLineGenerator¶ - #include <svg_shapes.h>
Subclassed by D3::RadialAreaGenerator
Public Functions
-
RadialLineGenerator
()¶
-
void
SetRadius
(float radius)
-
void
SetRadius
(std::string radius)
-
void
SetAngle
(float angle)
-
void
SetAngle
(std::string angle)
-
void
SetCurve
(std::string curve) Set the method used to interpolate a curve between points in the line. For allowed options, see the d3 documntation
-
void
SetTension
(float tension) If interpolation is “bundle”, “cardinal”, “cardinal-open”, or “cardinal-closed”, a tension parameter is used.
-
void
SetDefined
(std::string defined) Set a function indicating where the line is defined (i.e. valid) Can be a C++ function or a string indicating a Javascript function
-
template <typename T, size_t SIZE>
std::stringGenerate
(emp::array<emp::array<T, 2>, SIZE> &data) Generate the string describing the path associated with [data] Assumes [data] is an array of 2-element arrays describing (x,y) coordinates and makes the line that connects them
-
-
class
SvgShapeGenerator
: public D3::D3_Base¶ - #include <svg_shapes.h>
A few particularly common shapes (circles, rectangles, and ellipses) have corresponding SVG elements that you can create directly. All other shapes (including lines) must be created by specifying a “path” describing their outline. Paths are defined with a mini-language that describes how you would draw the shape with a pen. You could write them by hand, but that’s rarely desirable (especially when you’re trying to systematically represent data). So d3 provides functions for generating functions that will convert data to paths. This is a base clase for all objects that manage such functions to inherit from. You probably want to instantiate derived versions, rather than this class directly.
Subclassed by D3::BaseLineGenerator, D3::SymbolGenerator
Public Functions
-
template <typename T, size_t SIZE>
std::stringGenerate
(emp::array<emp::array<T, 2>, SIZE> &data) Generate the string describing the path associated with [data] Assumes [data] is an array of 2-element arrays describing (x,y) coordinates and makes the line that connects them
Protected Functions
-
SvgShapeGenerator
()¶
-
template <typename T, size_t SIZE>
-
class
SymbolGenerator
: public D3::SvgShapeGenerator¶ - #include <svg_shapes.h>
Generate symbols (“circle”, “cross” “diamond”, “square”, “triangle-down”, “triangle-up”). Often useful for making scatter plots.
Public Functions
-
SymbolGenerator
()¶
-
void
SetType
(std::string type)¶ Set the type of symbol generated. Must be a C++ function, a string containing the name of a Javascript function (in the current window, d3, or emp namespaces), or a string specifying a type (“circle”, “cross” “diamond”, “square”, “triangle-down”, “triangle-up”).
-
void
SetSize
(int size)¶ Set size in pixels to [size] - can be an int, a C++ function, or string naming a Javascript function in the current window, the emp namespace, or the d3 namespace.
-
template <typename T, size_t SIZE>
std::stringGenerate
(emp::array<emp::array<T, 2>, SIZE> &data) Generate the string describing the path associated with [data] Assumes [data] is an array of 2-element arrays describing (x,y) coordinates and makes the line that connects them
-
-
class
Datasets¶
Tools to build common SVG shapes.
- 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
-
namespace
D3
-
class
ArcGenerator
: public D3::RadialAreaGenerator¶ - #include <svg_shapes.h>
Public Functions
-
ArcGenerator
()¶
-
void
SetCornerRadius
(float radius)¶
-
void
SetPadRadius
(float radius)¶
-
void
SetPadAngle
(float angle)¶
-
void
SetInnerRadius
(float radius)
-
void
SetInnerRadius
(std::string radius)
-
void
SetOuterRadius
(float radius)
-
void
SetOuterRadius
(std::string radius)
-
void
SetStartAngle
(float angle)
-
void
SetStartAngle
(std::string angle)
-
void
SetEndAngle
(float angle)
-
void
SetEndAngle
(std::string angle)
-
void
SetRadius
(float radius)
-
void
SetRadius
(std::string radius)
-
void
SetAngle
(float angle)
-
void
SetAngle
(std::string angle)
-
void
SetCurve
(std::string curve) Set the method used to interpolate a curve between points in the line. For allowed options, see the d3 documntation
-
void
SetTension
(float tension) If interpolation is “bundle”, “cardinal”, “cardinal-open”, or “cardinal-closed”, a tension parameter is used.
-
void
SetDefined
(std::string defined) Set a function indicating where the line is defined (i.e. valid) Can be a C++ function or a string indicating a Javascript function
-
template <typename T, size_t SIZE>
std::stringGenerate
(emp::array<emp::array<T, 2>, SIZE> &data) Generate the string describing the path associated with [data] Assumes [data] is an array of 2-element arrays describing (x,y) coordinates and makes the line that connects them
-
-
class
AreaGenerator
: public D3::LineGenerator¶ - #include <svg_shapes.h>
An area is defined by two lines, with the area in between shaded.
Public Functions
-
AreaGenerator
()¶
-
template <typename T>
voidSetX0
(T x)¶
-
template <typename T>
voidSetY0
(T y)¶
-
template <typename T>
voidSetX1
(T x)¶
-
template <typename T>
voidSetY1
(T y)¶
-
template <typename X_SCALE_TYPE>
voidAddXScale
(X_SCALE_TYPE &scale) Often, when you’re drawing cartesion lines, you want to use a scale to transform numbers from range of your data to the range of pixels on your screen. Adding an X scale will cause the x-coordinates of all points on the line to be passed through that scale function. This stacks on top of whatever the current function for accessing x is (which means scales will also stack).
-
template <typename Y_SCALE_TYPE>
voidAddYScale
(Y_SCALE_TYPE &scale) Often, when you’re drawing cartesion lines, you want to use a scale to transform numbers from range of your data to the range of pixels on your screen. Adding a Y scale will cause the y-coordinates of all points on the line to be passed through that scale function. This stacks on top of whatever the current function for accessing y is (which means scales will also stack).
-
void
SetX
(std::string x) If the data that you are generating lines from is anything more complicated than a sequence of pairs of numbers, representing x and y (in that order), you need to tell the line generator how it should figure out what the x coordinate of a point in the line is. The parameter you pass to SetX should be instructions for doing so. It can either be a function (as a string indicating a Javascript function or as a literal C++ function) that accepts an element of the data sequence you are generating the line from, or it can be a constant, in which case the x coordinate of every point will be that constant.
Note: This function will re-set any scales that you’ve added to the X coordinate
As an example, the default function expects data like this (array of arrays): [[0,0], [1,1], [2,2]] And has (a Javascript equivalent of) this accessor: int x(emp::array<int, 2> d) {return d[0];}
If your data instead looked like this (array of Javascript objects with x and y values): [{x:0, y:0}, {x:1, y:1}, {x:2, y:2}] You might want to use an accessor like this: int x(JSONObject d) {return d.x();} Where JSONObject is a struct designed to hold necessary data from the Javascript object: struct JSONObject { EMP_BUILD_INTROSPECTIVE_TUPLE( int, x, int, y ) };
-
void
SetY
(std::string y) If the data that you are generating lines from is anything more complicated than a sequence of pairs of numbers, representing x and y (in that order), you need to tell the line generator how it should figure out what the y coordinate of a point in the line is. The parameter you pass to SetY should be instructions for doing so. It can either be a function (as a string indicating a Javascript function or as a literal C++ function) that accepts an element of the data sequence you are generating the line from, or it can be a constant, in which case the y coordinate of every point will be that constant.
Note: This function will re-set any scales that you’ve added to the Y coordinate
As an example, the default function expects data like this (array of arrays): [[0,0], [1,1], [2,2]] And has (a Javascript equivalent of) this accessor: int x(emp::array<int, 2> d) {return d[1];}
If your data instead looked like this (array of Javascript objects with x and y values): [{x:0, y:0}, {x:1, y:1}, {x:2, y:2}] You might want to use an accessor like this: int x(JSONObject d) {return d.y();} Where JSONObject is a struct designed to hold necessary data from the Javascript object: struct JSONObject { EMP_BUILD_INTROSPECTIVE_TUPLE( int, x, int, y ) };
-
void
SetCurve
(std::string curve) Set the method used to interpolate a curve between points in the line. For allowed options, see the d3 documntation
-
void
SetTension
(float tension) If interpolation is “bundle”, “cardinal”, “cardinal-open”, or “cardinal-closed”, a tension parameter is used.
-
void
SetDefined
(std::string defined) Set a function indicating where the line is defined (i.e. valid) Can be a C++ function or a string indicating a Javascript function
-
template <typename T, size_t SIZE>
std::stringGenerate
(emp::array<emp::array<T, 2>, SIZE> &data) Generate the string describing the path associated with [data] Assumes [data] is an array of 2-element arrays describing (x,y) coordinates and makes the line that connects them
-
-
class
BaseLineGenerator
: public D3::SvgShapeGenerator¶ - #include <svg_shapes.h>
Base class for generating both cartesian and radial lines You don’t normally want to instantiate this - use LineGenerator or RadialLineGenerator instead.
Subclassed by D3::LineGenerator, D3::RadialLineGenerator
Public Functions
-
BaseLineGenerator
()¶
-
void
SetCurve
(std::string curve) Set the method used to interpolate a curve between points in the line. For allowed options, see the d3 documntation
-
void
SetTension
(float tension) If interpolation is “bundle”, “cardinal”, “cardinal-open”, or “cardinal-closed”, a tension parameter is used.
-
void
SetDefined
(std::string defined) Set a function indicating where the line is defined (i.e. valid) Can be a C++ function or a string indicating a Javascript function
-
template <typename T, size_t SIZE>
std::stringGenerate
(emp::array<emp::array<T, 2>, SIZE> &data) Generate the string describing the path associated with [data] Assumes [data] is an array of 2-element arrays describing (x,y) coordinates and makes the line that connects them
-
-
class
ChordGenerator
: public D3::RadialAreaGenerator¶ - #include <svg_shapes.h>
Public Functions
-
ChordGenerator
()¶
-
template <typename T>
voidSetSource
(T source)¶
-
template <typename T>
voidSetTarget
(T target)¶
-
void
SetInnerRadius
(float radius)
-
void
SetInnerRadius
(std::string radius)
-
void
SetOuterRadius
(float radius)
-
void
SetOuterRadius
(std::string radius)
-
void
SetStartAngle
(float angle)
-
void
SetStartAngle
(std::string angle)
-
void
SetEndAngle
(float angle)
-
void
SetEndAngle
(std::string angle)
-
void
SetRadius
(float radius)
-
void
SetRadius
(std::string radius)
-
void
SetAngle
(float angle)
-
void
SetAngle
(std::string angle)
-
void
SetCurve
(std::string curve) Set the method used to interpolate a curve between points in the line. For allowed options, see the d3 documntation
-
void
SetTension
(float tension) If interpolation is “bundle”, “cardinal”, “cardinal-open”, or “cardinal-closed”, a tension parameter is used.
-
void
SetDefined
(std::string defined) Set a function indicating where the line is defined (i.e. valid) Can be a C++ function or a string indicating a Javascript function
-
template <typename T, size_t SIZE>
std::stringGenerate
(emp::array<emp::array<T, 2>, SIZE> &data) Generate the string describing the path associated with [data] Assumes [data] is an array of 2-element arrays describing (x,y) coordinates and makes the line that connects them
-
-
class
LineGenerator
: public D3::BaseLineGenerator¶ - #include <svg_shapes.h>
Generator for regular old (cartesian) lines.
Subclassed by D3::AreaGenerator, D3::LinkGenerator
Public Functions
-
LineGenerator
()¶
-
template <typename X_SCALE_TYPE>
voidAddXScale
(X_SCALE_TYPE &scale) Often, when you’re drawing cartesion lines, you want to use a scale to transform numbers from range of your data to the range of pixels on your screen. Adding an X scale will cause the x-coordinates of all points on the line to be passed through that scale function. This stacks on top of whatever the current function for accessing x is (which means scales will also stack).
-
template <typename Y_SCALE_TYPE>
voidAddYScale
(Y_SCALE_TYPE &scale) Often, when you’re drawing cartesion lines, you want to use a scale to transform numbers from range of your data to the range of pixels on your screen. Adding a Y scale will cause the y-coordinates of all points on the line to be passed through that scale function. This stacks on top of whatever the current function for accessing y is (which means scales will also stack).
-
void
SetX
(std::string x) If the data that you are generating lines from is anything more complicated than a sequence of pairs of numbers, representing x and y (in that order), you need to tell the line generator how it should figure out what the x coordinate of a point in the line is. The parameter you pass to SetX should be instructions for doing so. It can either be a function (as a string indicating a Javascript function or as a literal C++ function) that accepts an element of the data sequence you are generating the line from, or it can be a constant, in which case the x coordinate of every point will be that constant.
Note: This function will re-set any scales that you’ve added to the X coordinate
As an example, the default function expects data like this (array of arrays): [[0,0], [1,1], [2,2]] And has (a Javascript equivalent of) this accessor: int x(emp::array<int, 2> d) {return d[0];}
If your data instead looked like this (array of Javascript objects with x and y values): [{x:0, y:0}, {x:1, y:1}, {x:2, y:2}] You might want to use an accessor like this: int x(JSONObject d) {return d.x();} Where JSONObject is a struct designed to hold necessary data from the Javascript object: struct JSONObject { EMP_BUILD_INTROSPECTIVE_TUPLE( int, x, int, y ) };
-
void
SetY
(std::string y) If the data that you are generating lines from is anything more complicated than a sequence of pairs of numbers, representing x and y (in that order), you need to tell the line generator how it should figure out what the y coordinate of a point in the line is. The parameter you pass to SetY should be instructions for doing so. It can either be a function (as a string indicating a Javascript function or as a literal C++ function) that accepts an element of the data sequence you are generating the line from, or it can be a constant, in which case the y coordinate of every point will be that constant.
Note: This function will re-set any scales that you’ve added to the Y coordinate
As an example, the default function expects data like this (array of arrays): [[0,0], [1,1], [2,2]] And has (a Javascript equivalent of) this accessor: int x(emp::array<int, 2> d) {return d[1];}
If your data instead looked like this (array of Javascript objects with x and y values): [{x:0, y:0}, {x:1, y:1}, {x:2, y:2}] You might want to use an accessor like this: int x(JSONObject d) {return d.y();} Where JSONObject is a struct designed to hold necessary data from the Javascript object: struct JSONObject { EMP_BUILD_INTROSPECTIVE_TUPLE( int, x, int, y ) };
-
void
SetCurve
(std::string curve) Set the method used to interpolate a curve between points in the line. For allowed options, see the d3 documntation
-
void
SetTension
(float tension) If interpolation is “bundle”, “cardinal”, “cardinal-open”, or “cardinal-closed”, a tension parameter is used.
-
void
SetDefined
(std::string defined) Set a function indicating where the line is defined (i.e. valid) Can be a C++ function or a string indicating a Javascript function
-
template <typename T, size_t SIZE>
std::stringGenerate
(emp::array<emp::array<T, 2>, SIZE> &data) Generate the string describing the path associated with [data] Assumes [data] is an array of 2-element arrays describing (x,y) coordinates and makes the line that connects them
-
-
class
LinkGenerator
: public D3::LineGenerator¶ - #include <svg_shapes.h>
Public Functions
-
template <typename X_SCALE_TYPE>
voidAddXScale
(X_SCALE_TYPE &scale) Often, when you’re drawing cartesion lines, you want to use a scale to transform numbers from range of your data to the range of pixels on your screen. Adding an X scale will cause the x-coordinates of all points on the line to be passed through that scale function. This stacks on top of whatever the current function for accessing x is (which means scales will also stack).
-
template <typename Y_SCALE_TYPE>
voidAddYScale
(Y_SCALE_TYPE &scale) Often, when you’re drawing cartesion lines, you want to use a scale to transform numbers from range of your data to the range of pixels on your screen. Adding a Y scale will cause the y-coordinates of all points on the line to be passed through that scale function. This stacks on top of whatever the current function for accessing y is (which means scales will also stack).
-
void
SetX
(std::string x) If the data that you are generating lines from is anything more complicated than a sequence of pairs of numbers, representing x and y (in that order), you need to tell the line generator how it should figure out what the x coordinate of a point in the line is. The parameter you pass to SetX should be instructions for doing so. It can either be a function (as a string indicating a Javascript function or as a literal C++ function) that accepts an element of the data sequence you are generating the line from, or it can be a constant, in which case the x coordinate of every point will be that constant.
Note: This function will re-set any scales that you’ve added to the X coordinate
As an example, the default function expects data like this (array of arrays): [[0,0], [1,1], [2,2]] And has (a Javascript equivalent of) this accessor: int x(emp::array<int, 2> d) {return d[0];}
If your data instead looked like this (array of Javascript objects with x and y values): [{x:0, y:0}, {x:1, y:1}, {x:2, y:2}] You might want to use an accessor like this: int x(JSONObject d) {return d.x();} Where JSONObject is a struct designed to hold necessary data from the Javascript object: struct JSONObject { EMP_BUILD_INTROSPECTIVE_TUPLE( int, x, int, y ) };
-
void
SetY
(std::string y) If the data that you are generating lines from is anything more complicated than a sequence of pairs of numbers, representing x and y (in that order), you need to tell the line generator how it should figure out what the y coordinate of a point in the line is. The parameter you pass to SetY should be instructions for doing so. It can either be a function (as a string indicating a Javascript function or as a literal C++ function) that accepts an element of the data sequence you are generating the line from, or it can be a constant, in which case the y coordinate of every point will be that constant.
Note: This function will re-set any scales that you’ve added to the Y coordinate
As an example, the default function expects data like this (array of arrays): [[0,0], [1,1], [2,2]] And has (a Javascript equivalent of) this accessor: int x(emp::array<int, 2> d) {return d[1];}
If your data instead looked like this (array of Javascript objects with x and y values): [{x:0, y:0}, {x:1, y:1}, {x:2, y:2}] You might want to use an accessor like this: int x(JSONObject d) {return d.y();} Where JSONObject is a struct designed to hold necessary data from the Javascript object: struct JSONObject { EMP_BUILD_INTROSPECTIVE_TUPLE( int, x, int, y ) };
-
void
SetCurve
(std::string curve) Set the method used to interpolate a curve between points in the line. For allowed options, see the d3 documntation
-
void
SetTension
(float tension) If interpolation is “bundle”, “cardinal”, “cardinal-open”, or “cardinal-closed”, a tension parameter is used.
-
void
SetDefined
(std::string defined) Set a function indicating where the line is defined (i.e. valid) Can be a C++ function or a string indicating a Javascript function
-
template <typename T, size_t SIZE>
std::stringGenerate
(emp::array<emp::array<T, 2>, SIZE> &data) Generate the string describing the path associated with [data] Assumes [data] is an array of 2-element arrays describing (x,y) coordinates and makes the line that connects them
-
template <typename X_SCALE_TYPE>
-
class
RadialAreaGenerator
: public D3::RadialLineGenerator¶ - #include <svg_shapes.h>
Subclassed by D3::ArcGenerator, D3::ChordGenerator
Public Functions
-
RadialAreaGenerator
()¶
-
void
SetInnerRadius
(float radius)
-
void
SetInnerRadius
(std::string radius)
-
void
SetOuterRadius
(float radius)
-
void
SetOuterRadius
(std::string radius)
-
void
SetStartAngle
(float angle)
-
void
SetStartAngle
(std::string angle)
-
void
SetEndAngle
(float angle)
-
void
SetEndAngle
(std::string angle)
-
void
SetRadius
(float radius)
-
void
SetRadius
(std::string radius)
-
void
SetAngle
(float angle)
-
void
SetAngle
(std::string angle)
-
void
SetCurve
(std::string curve) Set the method used to interpolate a curve between points in the line. For allowed options, see the d3 documntation
-
void
SetTension
(float tension) If interpolation is “bundle”, “cardinal”, “cardinal-open”, or “cardinal-closed”, a tension parameter is used.
-
void
SetDefined
(std::string defined) Set a function indicating where the line is defined (i.e. valid) Can be a C++ function or a string indicating a Javascript function
-
template <typename T, size_t SIZE>
std::stringGenerate
(emp::array<emp::array<T, 2>, SIZE> &data) Generate the string describing the path associated with [data] Assumes [data] is an array of 2-element arrays describing (x,y) coordinates and makes the line that connects them
-
-
class
RadialLineGenerator
: public D3::BaseLineGenerator¶ - #include <svg_shapes.h>
Subclassed by D3::RadialAreaGenerator
Public Functions
-
RadialLineGenerator
()¶
-
void
SetRadius
(float radius)
-
void
SetRadius
(std::string radius)
-
void
SetAngle
(float angle)
-
void
SetAngle
(std::string angle)
-
void
SetCurve
(std::string curve) Set the method used to interpolate a curve between points in the line. For allowed options, see the d3 documntation
-
void
SetTension
(float tension) If interpolation is “bundle”, “cardinal”, “cardinal-open”, or “cardinal-closed”, a tension parameter is used.
-
void
SetDefined
(std::string defined) Set a function indicating where the line is defined (i.e. valid) Can be a C++ function or a string indicating a Javascript function
-
template <typename T, size_t SIZE>
std::stringGenerate
(emp::array<emp::array<T, 2>, SIZE> &data) Generate the string describing the path associated with [data] Assumes [data] is an array of 2-element arrays describing (x,y) coordinates and makes the line that connects them
-
-
class
SvgShapeGenerator
: public D3::D3_Base¶ - #include <svg_shapes.h>
A few particularly common shapes (circles, rectangles, and ellipses) have corresponding SVG elements that you can create directly. All other shapes (including lines) must be created by specifying a “path” describing their outline. Paths are defined with a mini-language that describes how you would draw the shape with a pen. You could write them by hand, but that’s rarely desirable (especially when you’re trying to systematically represent data). So d3 provides functions for generating functions that will convert data to paths. This is a base clase for all objects that manage such functions to inherit from. You probably want to instantiate derived versions, rather than this class directly.
Subclassed by D3::BaseLineGenerator, D3::SymbolGenerator
Public Functions
-
template <typename T, size_t SIZE>
std::stringGenerate
(emp::array<emp::array<T, 2>, SIZE> &data) Generate the string describing the path associated with [data] Assumes [data] is an array of 2-element arrays describing (x,y) coordinates and makes the line that connects them
Protected Functions
-
SvgShapeGenerator
()¶
-
template <typename T, size_t SIZE>
-
class
SymbolGenerator
: public D3::SvgShapeGenerator¶ - #include <svg_shapes.h>
Generate symbols (“circle”, “cross” “diamond”, “square”, “triangle-down”, “triangle-up”). Often useful for making scatter plots.
Public Functions
-
SymbolGenerator
()¶
-
void
SetType
(std::string type)¶ Set the type of symbol generated. Must be a C++ function, a string containing the name of a Javascript function (in the current window, d3, or emp namespaces), or a string specifying a type (“circle”, “cross” “diamond”, “square”, “triangle-down”, “triangle-up”).
-
void
SetSize
(int size)¶ Set size in pixels to [size] - can be an int, a C++ function, or string naming a Javascript function in the current window, the emp namespace, or the d3 namespace.
-
template <typename T, size_t SIZE>
std::stringGenerate
(emp::array<emp::array<T, 2>, SIZE> &data) Generate the string describing the path associated with [data] Assumes [data] is an array of 2-element arrays describing (x,y) coordinates and makes the line that connects them
-
-
class
Animations¶
Manage animations on a web site.
To build an animation, you must provide a function to be run repeatedly. When Start() is triggered, the function will be called 60 time per second (or as close as possible), until Stop() is caled.
- 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
- 2015-2017
-
namespace
emp
¶ If we are in emscripten, make sure to include the header.
This file contains extra analysis tools to use with systematics managers that have non-null DATA_TYPES.
- 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
- 2018
This file contains functions for adding additional data files to Worlds.
- 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
- 2018
-
namespace
web
¶ -
class
Animate
¶ - #include <Animate.h>
An object that, when active, repeatedly calls a function as fast as possible, to a maximum of 60 frames per second.
Parameters to the animation function can be:
- double (representing time since the last frame)
- a const reference to the animation object itself
- nothing
Control methods: void Start() void Stop() void Step() void ToggleActive()
Access methods: bool GetActive() const bool GetDoStep() const double GetStartTime() const double GetPrevTime() const double GetCurTime() const double GetStepTime() const double GetRunTime() const int GetFrameCount() const
Config methods: void SetCallback(const std::function<void(const Animate &)> & fun) void SetCallback(const std::function<void(double)> & fun) void SetCallback(const std::function<void()> & fun)
Public Functions
-
Animate
()¶ Setup an Animate object to call an anim_fun as fast as possible, at most 60 times a second. Call virtual function DoFrame() if no other functon is provided (which can be overridden if you derive a new class from Animate)
-
template <typename... W_TYPES>
Animate
(const anim_fun_t &fun, W_TYPES&... targets)¶ Construct an Animate object with the function to run each animation step and zero or more UI elements that should be updated after each frame.
-
template <typename... W_TYPES>
Animate
(const std::function<void(double)> &fun, W_TYPES&... targets, )¶
-
virtual
~Animate
()¶
-
void
Start
()¶ Start this animation running.
-
void
Stop
()¶ Halt this animation for now.
-
void
Step
()¶ Take a single step in this animation.
-
void
ToggleActive
()¶ Toggle whether this animation is running or paused.
-
bool
GetActive
() const¶ Determine if this animation is currently running.
-
bool
GetDoStep
() const¶ Determine if this animation is currently in the process of running a single step.
-
double
GetStartTime
() const¶ Return the time point that this animation started MOST RECENTLY.
-
double
GetPrevTime
() const¶ Determine the time point when this animation last updated a frame.
-
double
GetCurTime
() const¶ Get the current time of the animation.
-
double
GetStepTime
() const¶ Determine how long the last step between frames took.
-
double
GetRunTime
() const¶ Determine the total amount of time that this animation has run.
-
int
GetFrameCount
() const¶ Determine how many total frames have existed thus far in this animation.
-
void
SetCallback
(const anim_fun_t &fun)¶ Set a new function for this animation to call when running that takes a const reference to the Animation object as an argument.
-
void
SetCallback
(const std::function<void(double)> &fun)¶ Set a new function for this animation to call when running that takes the amount of time since the last frame (a double) as an argument.
-
void
SetCallback
(const std::function<void()> &fun)¶ Set a new function for this animation to call when running that takes no arguments.
-
Button
GetToggleButton
(const std::string &but_name, const std::string &start_label = "Start", const std::string &stop_label = "Stop")¶ Get a toggle button that will start/stop this animation.
- Parameters
but_name
: The HTML identifier used for this button.start_label
: The name on the button when it will start the animation (default=”Start”)stop_label
: The name on the button when it will halt the animation (default=”Stop”)
Protected Types
Protected Attributes
-
anim_fun_t
anim_fun
¶ Function to repeatedly run for animation.
-
bool
active
¶ Is this animation currently running?
-
bool
do_step
¶ Should this animation take just a single step?
-
size_t
callback_id
¶ Intenral ID for javascript to call back AdvanceFrame()
-
double
start_time
¶ At what time did this animation most recently start?
-
double
prev_time
¶ What was the time point of the previous frame?
-
double
cur_time
¶ What time did the current frame start?
-
double
run_time
¶ How much run time has accumulated?
-
int
frame_count
¶ How many animation frames have gone by?
-
class
Attributes¶
An Attributes class for tracking non-style features about HTML objects.
- 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
- 2015-2017
-
namespace
emp
¶ If we are in emscripten, make sure to include the header.
This file contains extra analysis tools to use with systematics managers that have non-null DATA_TYPES.
- 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
- 2018
This file contains functions for adding additional data files to Worlds.
- 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
- 2018
-
namespace
web
¶ -
class
Attributes
¶ - #include <Attributes.h>
Maintains a map of attribute names to values for use in JavaScript Closely related to Style.h, which is for CSS-values.
Public Functions
-
Attributes
()¶
-
Attributes
(const Attributes&)¶
-
Attributes &
operator=
(const Attributes&)¶
-
int
GetSize
() const¶ Return a count of the number of attributes that have been set.
-
Attributes &
DoSet
(const std::string &in_set, const std::string &in_val)¶
-
template <typename SET_TYPE>
Attributes &Set
(const std::string &s, SET_TYPE v)¶ Record that attribute “a” is set to value “v” (converted to string) and return this object.
-
Attributes &
Insert
(const Attributes &in_attr)¶ Set all values from in_attr here as well. Return this object.
-
bool
Has
(const std::string &setting) const¶ Return true/false based on whether “setting” has been given a value in this Attributes obj.
-
const std::string &
Get
(const std::string &setting)¶ Return the (string) value of “setting” that has been recorded in this Attributes obj. If setting did not exist, this does create an empty entry and return it.
-
void
Clear
()¶ Remove all setting values.
-
void
Apply
(const std::string &widget_id)¶ Apply ALL of the Attribute’s settings to dom element “widget_id”.
-
void
Apply
(const std::string &widget_id, const std::string &setting)¶ Apply onlay a SPECIFIC attributes setting from the setting library to widget_id.
-
operator bool
() const¶ Convert to true if there are any setting, false otherwise.
Public Static Functions
-
-
class
Buttons¶
Create/control an HTML button and call a specified function when that button is clicked.
Use example:
- 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
- 2015-2017
emp::web::Button my_button(MyFun, “Button Name”, “html_id”);
Where my_button is the C++ object linking to the button, MyFun is the function you want to call on clicks, “Button Name” is the label on the button itself, and “html_id” is the optional id you want it to use in the HTML code (otherwise it will generate a unique name on its own.)
Member functions to set state: Button & Callback(const std::function<void()> & in_callback) Button & Label(const std::string & in_label) Button & Title(const std::string & in_t) Button & Autofocus(bool in_af) Button & Disabled(bool in_dis)
Retriving current state: const std::string & GetLabel() const const std::string & GetTitle() const bool HasAutofocus() const bool IsDisabled() const
-
namespace
emp
If we are in emscripten, make sure to include the header.
This file contains extra analysis tools to use with systematics managers that have non-null DATA_TYPES.
- 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
- 2018
This file contains functions for adding additional data files to Worlds.
- 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
- 2018
-
namespace
web
-
class
Button
: public emp::web::internal::WidgetFacet<Button>¶ - #include <Button.h>
Create or control an HTML Button object that you can manipulate and update as needed.
Public Types
-
using
INFO_TYPE
= ButtonInfo¶
Public Functions
-
Button
(const std::function<void()> &in_cbconst std::string &in_label, const std::string &in_id = "", )¶ Create a new button.
- Parameters
in_cb
: The function to call when the button is clicked.in_label
: The label that should appear on the button.in_id
: The HTML ID to use for this button (leave blank for auto-generated)
-
Button
()¶
-
virtual
~Button
()¶
-
Button &
Callback
(const std::function<void()> &in_cb)¶ Set a new callback function to trigger when the button is clicked.
-
bool
HasAutofocus
() const¶ Determine if this button currently has autofocus.
-
bool
IsDisabled
() const¶ Determine if this button is currently disabled.
Protected Functions
-
ButtonInfo *
Info
()¶
-
const ButtonInfo *
Info
() const¶
-
Button
(ButtonInfo *in_info)¶
Friends
-
friend
emp::web::ButtonInfo
-
class
ButtonInfo
: public emp::web::internal::WidgetInfo¶ - #include <Button.h>
Protected Functions
-
ButtonInfo
(const ButtonInfo&)¶
-
ButtonInfo &
operator=
(const ButtonInfo&)¶
-
virtual
~ButtonInfo
()¶
-
virtual bool
IsButtonInfo
() const¶
-
void
DoCallback
()¶
-
void
UpdateAutofocus
(bool in_af)¶
-
void
UpdateDisabled
(bool in_dis)¶
Private Members
-
friend emp::web::Button::ButtonInfo::Button
-
-
using
-
class
Canvas¶
Manage an HTML canvas object.
- 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
- 2015-2018
-
namespace
emp
If we are in emscripten, make sure to include the header.
This file contains extra analysis tools to use with systematics managers that have non-null DATA_TYPES.
- 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
- 2018
This file contains functions for adding additional data files to Worlds.
- 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
- 2018
-
namespace
web
-
class
Canvas
: public emp::web::internal::WidgetFacet<Canvas>¶ - #include <Canvas.h>
Manage an HTML Canvas object.
Public Types
-
using
INFO_TYPE
= CanvasInfo¶
Public Functions
-
Canvas
(double w, double h, const std::string &in_id = "")¶ Create a new canvas with the specified size and optional HTML identifier.
-
Canvas
()¶
-
virtual
~Canvas
()¶
-
template <typename... Ts>
Canvas &Circle
(Point center, double _r, Ts&&... vals)¶ Add a Circle to this canvas; provide constructor for the CanvasCircle with a position and radius as well as optional face color, line color, and line width.
-
template <typename... Ts>
Canvas &Rect
(Point corner, double w, double h, Ts&&... vals)¶ Add a Rectangle to this canvas at x,y with width w and heigh h. Optional face color and line color.
-
template <typename... Ts>
Canvas &Image
(const emp::RawImage &image, Point corner, Ts&&... vals)¶ Add an Image to this canvas at x,y with width w and heigh h.
-
template <typename... Ts>
Canvas &Image
(const emp::RawImage &image, double x, double y, Ts&&... vals)¶
-
template <typename... Ts>
Canvas &Line
(double x1, double y1, double x2, double y2, Ts&&... vals)¶ Add a Line from x1,y1 to x2,y2. Optional face color and line color.
-
template <typename... Ts>
Canvas &MultiLine
(emp::Point p1, const emp::vector<emp::Point> &points, Ts&&... vals)¶ Add a Line from x1,y1 to x2,y2. Optional face color and line color.
-
template <typename... Ts>
Canvas &Text
(emp::Point p, Ts&&... vals)¶ Add a string to this canvas at x,y with specified text. Optional face color and line color.
-
template <typename... Ts>
Canvas &CenterText
(emp::Point p, Ts&&... vals)¶ Add a string to this canvas centered at x,y with specified text. Optional face color and line color.
-
Canvas &
Draw
(const emp::Circle &circle, const std::string &fc = "", const std::string &lc = "")¶ Draw a circle onto this canvas.
-
Canvas &
Draw
(const CanvasShape &shape)¶ Draw an arbitrary shape onto this canvas.
Protected Functions
-
CanvasInfo *
Info
()¶
-
const CanvasInfo *
Info
() const¶
-
Canvas
(CanvasInfo *in_info)¶
Friends
-
friend
emp::web::CanvasInfo
-
class
CanvasInfo
: public emp::web::internal::WidgetInfo¶ - #include <Canvas.h>
Protected Functions
-
CanvasInfo
(const CanvasInfo&)¶
-
CanvasInfo &
operator=
(const CanvasInfo&)¶
-
virtual
~CanvasInfo
()¶
-
virtual bool
IsCanvasInfo
() const¶
-
void
TargetCanvas
()¶
-
void
TriggerJS
()¶
-
void
AddAction
(CanvasAction *new_action)¶
-
void
ClearActions
()¶
Protected Attributes
-
double
width
¶ pixel width of the canvas.
-
double
height
¶ pixel height of the canvas.
-
emp::vector<CanvasAction *>
actions
¶
Private Members
-
friend emp::web::Canvas::CanvasInfo::Canvas
-
-
using
-
class
Canvas Utilities¶
Various versions of the Draw() function to draw images onto a canvas.
Each version of
Draw() takes a canvas widget and some form of data to be drawn on the widget, such as a circle, a bit matrix, or a geometric surface.- 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
- 2015-2018
-
namespace
emp
If we are in emscripten, make sure to include the header.
This file contains extra analysis tools to use with systematics managers that have non-null DATA_TYPES.
- 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
- 2018
This file contains functions for adding additional data files to Worlds.
- 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
- 2018
-
namespace
web
Functions
-
void
Draw
(Canvas canvas, const emp::Circle &circle, const std::string &fill = "", const std::string &line = "")¶ Draw a Circle onto the canvas.
-
template <size_t COLS, size_t ROWS>
voidDraw
(Canvas canvas, const BitMatrix<COLS, ROWS> &matrix, double w, double h)¶ Draw a BitMatrix onto a canvas using black and white squares (can specify cell width and height)
-
template <typename BODY_TYPE>
voidDraw
(Canvas canvas, const Surface2D<BODY_TYPE> &surface, const emp::vector<std::string> &color_map)¶ Draw a Surface2D, specifying the full colormap to be used. The surface has a range of circle bodies, each with a color id.
- Parameters
canvas
: The Canvas to draw on.surface
: A surface containing a set of shapes to draw.color_map
: Mapping of values to the colors with which they should be associated.
-
template <typename BODY_TYPE>
voidDraw
(Canvas canvas, const Surface2D<BODY_TYPE> &surface, size_t num_colors)¶ Draw a Surface2D, just specifying the number of colors (and using a generated hue map). The surface has a range of circle bodies, each with a color id.
- Parameters
canvas
: The Canvas to draw on.surface
: A surface containing a set of shapes to draw.num_colors
: The number of distinct colors to use in visualization.
-
void
Draw
(Canvas canvas, const emp::vector<emp::vector<size_t>> &grid, const emp::vector<std::string> &color_map, std::string line_color, double cell_width, double cell_height, double offset_x, double offset_y)¶ Draw a grid onto a canvas.
- Parameters
canvas
: The Canvas to draw on.grid
: A vector of vectors of color IDs.color_map
: Mapping of values to the colors with which they should be associated.line_color
: The background line color for the grid.cell_width
: How many pixels wide is each cell to draw?cell_height
: How many pixels tall is each cell to draw?offset_x
: How far should we shift the grid relative to the left side of the canvas?offset_y
: How far should we shift the grid relative to the top of the canvas?
-
void
Draw
(Canvas canvas, const emp::vector<emp::vector<size_t>> &grid, const emp::vector<std::string> &color_map, std::string line_color, double cell_w, double cell_h)¶ Draw a grid onto a canvas, but without offsets provided the grid is centered.
- Parameters
canvas
: The Canvas to draw on.grid
: A vector of vectors of color IDs.color_map
: Mapping of values to the colors with which they should be associated.line_color
: The background line color for the grid.cell_width
: How many pixels wide is each cell to draw?cell_height
: How many pixels tall is each cell to draw?
-
void
Draw
(Canvas canvas, const emp::vector<emp::vector<size_t>> &grid, const emp::vector<std::string> &color_map, std::string line_color = "black")¶ Draw a grid onto a canvas, but without cell size provided maximize to fill the canvas!
- Parameters
canvas
: The Canvas to draw on.grid
: A vector of vectors of color IDs.color_map
: Mapping of values to the colors with which they should be associated.line_color
: The background line color for the grid.
-
void
Draw
(Canvas canvas, const emp::vector<size_t> &grid, size_t grid_cols, const emp::vector<std::string> &color_map, std::string line_color, double cell_width, double cell_height, double offset_x, double offset_y)¶ Draw a vector onto a canvas as a grid.
- Parameters
canvas
: The Canvas to draw on.grid
: A vector of vectors of color IDsgrid_cols
: Number of columns in the gridcolor_map
: Mapping of values to the colors with which they should be associated.line_color
: The background line color for the gridcell_width
: How many pixels wide is each cell to draw?cell_height
: How many pixels tall is each cell to draw?offset_x
: How far should we shift the grid relative to the left side of the canvas?offset_y
: How far should we shift the grid relative to the top of the canvas?
-
void
Draw
(Canvas canvas, const StateGrid &state_grid, const emp::vector<std::string> &color_map, std::string line_color = "black")¶ Draw a state grid onto a canvas.
- Parameters
canvas
: The Canvas to draw on.state_grid
: A StateGrid object.color_map
: Mapping of values to the colors with which they should be associated.line_color
: The background line color for the grid.
-
void
DrawGridBG
(Canvas canvas, size_t rows, size_t cols, const std::string &bg_color, const std::string &line_color)¶ Draw a grid as the background of a canvas. Since this is a BG, clear the canvas first.
- Parameters
canvas
: The Canvas to draw on.rows
: Number of rows to draw in the grid.cols
: Number of columns to draw in the grid.bg_color
: The background color for the grid.line_color
: The color of the liens on the grid.
-
void
Canvas Actions¶
Define a base class for all actions that can be done to widgets, plus simple actions.
CanvasAction objects modify the appearance of a canvas and can be tracked to reconstruct the state of the canvas from scratch.
- 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
- 2015-2018
Other, more specific actions defined here are: CanvasStrokeColor CanvasRotate CanvasFont
See also CanvasShape.h for more actions.
-
namespace
emp
If we are in emscripten, make sure to include the header.
This file contains extra analysis tools to use with systematics managers that have non-null DATA_TYPES.
- 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
- 2018
This file contains functions for adding additional data files to Worlds.
- 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
- 2018
-
namespace
web
-
class
CanvasAction
¶ - #include <CanvasAction.h>
Base class to maintain canvas actions.
Subclassed by emp::web::CanvasFont, emp::web::CanvasImage, emp::web::CanvasRotate, emp::web::CanvasShape, emp::web::CanvasStrokeColor
Public Functions
-
CanvasAction
()¶
-
CanvasAction
(const CanvasAction&)¶
-
virtual
~CanvasAction
()¶
-
virtual void
Apply
() = 0¶ Apply current action to emp_i.ctx.
-
virtual CanvasAction *
Clone
() const = 0¶ Make a copy of the current action.
-
-
class
CanvasFont
: public emp::web::CanvasAction¶ - #include <CanvasAction.h>
Change the default font to be used.
Public Functions
-
void
Apply
()¶ Apply current action to emp_i.ctx.
-
CanvasAction *
Clone
() const¶ Make a copy of the current action.
Protected Functions
-
void
LineWidth
(double line_width = 1.0)¶ Helper function to set the stroke status.
-
void
-
class
CanvasImage
: public emp::web::CanvasAction¶ - #include <CanvasAction.h>
Change the default font to be used.
Public Functions
-
CanvasImage
(const RawImage &raw_image, double _x = 0.0, double _y = 0.0, double _w = 0.0, double _h = 0.0)¶
-
CanvasImage
(const std::string &url, double _x = 0.0, double _y = 0.0, double _w = 0.0, double _h = 0.0)¶
-
void
Apply
()¶ Apply current action to emp_i.ctx.
-
CanvasAction *
Clone
() const¶ Make a copy of the current action.
-
-
class
CanvasRotate
: public emp::web::CanvasAction¶ - #include <CanvasAction.h>
Rotate the entire canvas for subsequent drawings.
Public Functions
-
CanvasRotate
(double a)¶
-
void
Apply
()¶ Apply current action to emp_i.ctx.
-
CanvasAction *
Clone
() const¶ Make a copy of the current action.
Protected Functions
-
void
Fill
(const std::string &style = "") Helper function to set the fill status.
-
void
Stroke
(const std::string &style = "") Helper function to set the stroke status.
-
void
LineWidth
(double line_width = 1.0) Helper function to set the stroke status.
Protected Attributes
-
double
angle
¶
-
-
class
CanvasStrokeColor
: public emp::web::CanvasAction¶ - #include <CanvasAction.h>
Set the line color on subsequent draw-related actions.
Public Functions
-
void
Apply
()¶ Apply current action to emp_i.ctx.
-
CanvasAction *
Clone
() const¶ Make a copy of the current action.
-
void
-
class
Canvas Shapes¶
Define simple shapes to draw on a canvas.
Canvas shapes can be definied in detail, describing how they modify a canvas.
- 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
- 2015-2017
Other, more specific actions defined here are: CanvasCircle CanvasRect
-
namespace
emp
If we are in emscripten, make sure to include the header.
This file contains extra analysis tools to use with systematics managers that have non-null DATA_TYPES.
- 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
- 2018
This file contains functions for adding additional data files to Worlds.
- 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
- 2018
-
namespace
web
-
class
CanvasCircle
: public emp::web::CanvasShape¶ - #include <CanvasShape.h>
Track a circle shape to be drawn on a canvas.
Public Functions
-
CanvasCircle
(double _x, double _y, double _r, const std::string &fc = "", const std::string &lc = "", double lw = 1.0)¶
-
CanvasCircle
(Point _p, double _r, const std::string &fc = "", const std::string &lc = "", double lw = 1.0)¶
-
CanvasCircle
(emp::Circle circle, const std::string &fc = "", const std::string &lc = "", double lw = 1.0)¶
-
void
Apply
()¶ Apply current action to emp_i.ctx.
-
CanvasAction *
Clone
() const¶ Make a copy of the current action.
-
void
MoveTo
(Point _p)¶ Shift the position of this shape to a point.
-
void
MoveTo
(double _x, double _y)¶ Shift the position of this shape to coordinates.
-
void
SetLineWidth
(double lw = 1.0)¶ Setup details needed before drawing lines.
-
void
ApplyColor
()¶ Actually change the color on screen.
Protected Attributes
-
Point
p
¶ Anchor point for this shape.
-
double
line_width
¶ How wide should lines be?
Private Members
-
double
radius
¶ Circle radius.
-
-
class
CanvasClearRect
: public emp::web::CanvasShape¶ - #include <CanvasShape.h>
Clear a rectangular area in a canvas.
Public Functions
-
CanvasClearRect
(Point _p, double _w, double _h)¶
-
void
Apply
()¶ Apply current action to emp_i.ctx.
-
CanvasAction *
Clone
() const¶ Make a copy of the current action.
-
void
MoveTo
(Point _p)¶ Shift the position of this shape to a point.
-
void
MoveTo
(double _x, double _y)¶ Shift the position of this shape to coordinates.
-
void
SetLineWidth
(double lw = 1.0)¶ Setup details needed before drawing lines.
-
void
ApplyColor
()¶ Actually change the color on screen.
-
-
class
CanvasLine
: public emp::web::CanvasShape¶ - #include <CanvasShape.h>
A line segment on the canvas.
Public Functions
-
CanvasLine
(double _x1, double _y1, double _x2, double _y2, const std::string &lc = "", double lw = 1.0)¶ Y-position for second point of line segment.
-
void
Apply
()¶ Apply current action to emp_i.ctx.
-
CanvasAction *
Clone
() const¶ Make a copy of the current action.
-
void
MoveTo
(Point _p) Shift the position of this shape to a point.
-
void
MoveTo
(double _x, double _y) Shift the position of this shape to coordinates.
-
void
SetLineWidth
(double lw = 1.0) Setup details needed before drawing lines.
-
void
SetFillColor
(const std::string &color) Change the fill color of this shape.
-
void
SetLineColor
(const std::string &color) Change the stroke color of this shape.
-
void
ApplyColor
() Actually change the color on screen.
-
-
class
CanvasMultiLine
: public emp::web::CanvasShape¶ - #include <CanvasShape.h>
A whole series of line segments on the canvas. Currently not working…
Public Functions
-
CanvasMultiLine
(double _x1, double _y1, const emp::vector<Point> &_points, const std::string &lc = "", double lw = 1.0)¶
-
CanvasMultiLine
(Point p1, const emp::vector<Point> &_points, const std::string &lc = "", double lw = 1.0)¶
-
void
Apply
()¶ Apply current action to emp_i.ctx.
-
CanvasAction *
Clone
() const¶ Make a copy of the current action.
-
void
MoveTo
(Point _p) Shift the position of this shape to a point.
-
void
MoveTo
(double _x, double _y) Shift the position of this shape to coordinates.
-
void
SetLineWidth
(double lw = 1.0) Setup details needed before drawing lines.
-
void
SetFillColor
(const std::string &color) Change the fill color of this shape.
-
void
SetLineColor
(const std::string &color) Change the stroke color of this shape.
-
void
ApplyColor
() Actually change the color on screen.
-
-
class
CanvasPolygon
: public emp::web::CanvasShape¶ - #include <CanvasShape.h>
An arbitrary-sized polygon to be drawn on a canvas.
Public Functions
-
CanvasPolygon &
AddPoint
(double x, double y)¶
-
CanvasPolygon &
AddPoint
(Point p)¶
-
void
Apply
()¶ Apply current action to emp_i.ctx.
-
CanvasAction *
Clone
() const¶ Make a copy of the current action.
-
void
MoveTo
(Point _p) Shift the position of this shape to a point.
-
void
MoveTo
(double _x, double _y) Shift the position of this shape to coordinates.
-
void
SetLineWidth
(double lw = 1.0) Setup details needed before drawing lines.
-
void
SetFillColor
(const std::string &color) Change the fill color of this shape.
-
void
SetLineColor
(const std::string &color) Change the stroke color of this shape.
-
void
ApplyColor
() Actually change the color on screen.
-
CanvasPolygon &
-
class
CanvasRect
: public emp::web::CanvasShape¶ - #include <CanvasShape.h>
Track a rectangle shape to be drawn on a canvas.
Public Functions
-
CanvasRect
(double _x, double _y, double _w, double _h, const std::string &fc = "", const std::string &lc = "")¶
-
void
Apply
()¶ Apply current action to emp_i.ctx.
-
CanvasAction *
Clone
() const¶ Make a copy of the current action.
-
void
MoveTo
(Point _p) Shift the position of this shape to a point.
-
void
MoveTo
(double _x, double _y) Shift the position of this shape to coordinates.
-
void
SetLineWidth
(double lw = 1.0) Setup details needed before drawing lines.
-
void
SetFillColor
(const std::string &color) Change the fill color of this shape.
-
void
SetLineColor
(const std::string &color) Change the stroke color of this shape.
-
void
ApplyColor
() Actually change the color on screen.
-
-
class
CanvasShape
: public emp::web::CanvasAction¶ - #include <CanvasShape.h>
Define an arbitrary shape to draw on a canvas (base clase)
Subclassed by emp::web::CanvasCircle, emp::web::CanvasClearRect, emp::web::CanvasLine, emp::web::CanvasMultiLine, emp::web::CanvasPolygon, emp::web::CanvasRect, emp::web::CanvasText
Public Functions
-
CanvasShape
(double _x, double _y, const std::string &fc = "", const std::string &lc = "", double lw = 1.0)¶
-
virtual
~CanvasShape
()¶
-
void
MoveTo
(Point _p) Shift the position of this shape to a point.
-
void
MoveTo
(double _x, double _y) Shift the position of this shape to coordinates.
-
void
SetLineWidth
(double lw = 1.0) Setup details needed before drawing lines.
-
void
SetFillColor
(const std::string &color) Change the fill color of this shape.
-
void
SetLineColor
(const std::string &color) Change the stroke color of this shape.
-
void
ApplyColor
() Actually change the color on screen.
-
-
class
CanvasText
: public emp::web::CanvasShape¶ - #include <CanvasShape.h>
Text to be written on a canvas.
Public Functions
-
CanvasText
(Point p, const std::string &_text, const std::string &fc = "", const std::string &lc = "")¶
-
void
Apply
()¶ Apply current action to emp_i.ctx.
-
void
Center
(bool c = true)¶ Center this text.
-
bool
GetCenter
() const¶ Identify if text is centered.
-
CanvasAction *
Clone
() const¶ Make a copy of the current action.
-
void
MoveTo
(Point _p) Shift the position of this shape to a point.
-
void
MoveTo
(double _x, double _y) Shift the position of this shape to coordinates.
-
void
SetLineWidth
(double lw = 1.0) Setup details needed before drawing lines.
-
void
SetFillColor
(const std::string &color) Change the fill color of this shape.
-
void
SetLineColor
(const std::string &color) Change the stroke color of this shape.
-
void
ApplyColor
() Actually change the color on screen.
-
-
class
Color maps¶
Tools to dynamically build (and cache) color maps.
- 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
- 2015-2017
-
namespace
emp
If we are in emscripten, make sure to include the header.
This file contains extra analysis tools to use with systematics managers that have non-null DATA_TYPES.
- 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
- 2018
This file contains functions for adding additional data files to Worlds.
- 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
- 2018
Functions
-
std::string
ColorHSL
(double h, double s, double l)¶ Generate a string to describe a JS color out of HSL values.
-
std::string
ColorRGB
(int r, int g, int b)¶ Generate a string to describe a JS color out of RGB values.
-
std::string
ColorRGB
(int r, int g, int b, double a)¶ Generate a string to describe a JS color with an alpha channel.
Commands¶
A set of command-defining classes that can be fed into widgets using the << operator.
- 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
- 2015-2017
-
namespace
emp
If we are in emscripten, make sure to include the header.
This file contains extra analysis tools to use with systematics managers that have non-null DATA_TYPES.
- 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
- 2018
This file contains functions for adding additional data files to Worlds.
- 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
- 2018
-
namespace
web
Functions
-
static const PrintStr emp::web::endl("<br>")
Pre-define emp::endl to insert a “<br>” and thus acting like a newline.
-
class
Close
: public emp::web::internal::WidgetCommand¶ - #include <commands.h>
The Close command will prevent the specified widget from accepting further appends (and instead revert to trying parents)
Public Functions
-
bool
Trigger
(internal::WidgetInfo &w) const¶
-
bool
-
Divs¶
Div Widgets maintain an ordered collection of other widgets in an HTML div.
To create a Div:
- 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
- 2015-2017
- Note
- Formerly called Slate.h When printed to the web page, these internal widgets are presented in order.
emp::web::Div my_div(“name”);
To use a Div:
my_div << “Add this text!” << emp::web::Image(“my_image.png”) << “<br>”;
To register a Div in a Document:
my_doc << my_div;
-
namespace
emp
If we are in emscripten, make sure to include the header.
This file contains extra analysis tools to use with systematics managers that have non-null DATA_TYPES.
- 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
- 2018
This file contains functions for adding additional data files to Worlds.
- 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
- 2018
-
namespace
web
-
class
Div
: public emp::web::internal::WidgetFacet<Div>¶ - #include <Div.h>
A widget to track a div in an HTML file, and all of its contents.
Subclassed by emp::web::Document
Public Functions
-
Div
()¶
-
~Div
()¶
-
double
ScrollTop
() const¶ Where is the top of the scroll region?
-
void
Clear
()¶ Clear the contents of this div.
-
void
ClearChildren
()¶ Remove all child widgets from this div.
-
bool
HasChild
(const Widget &test_child) const¶ Determine if a specified widget is internal to this one.
-
void
Deactivate
(bool top_level)¶ Remove this widget from the current document.
-
Widget &
Find
(const std::string &test_name)¶ Get an internal widget to this div, by the specified name.
-
-
namespace
internal
¶ -
class
DivInfo
: public emp::web::internal::WidgetInfo¶ - #include <Div.h>
Protected Functions
-
virtual
~DivInfo
()¶
-
virtual bool
IsDivInfo
() const¶
-
void
ClearChildren
()¶
-
void
Clear
()¶
-
void
DoActivate
(bool top_level = true)¶
-
bool
AppendOK
() const¶
-
void
PreventAppend
()¶
-
Widget
Append
(const Font &font)¶ Start a new set of Text with this font (even if one already exists.)
-
void
ReplaceHTML
()¶
Protected Attributes
-
double
scroll_top
¶ Where should div scroll to? (0.0 to 1.0)
-
bool
append_ok
¶ Can we add more children?
-
bool
text_append
¶ Can we append to a current text widget?
Private Members
-
friend emp::web::internal::DivInfo::Div
-
friend emp::web::internal::DivInfo::TableInfo
-
virtual
-
class
-
class
Documents¶
Manage an entire document.
The Document class is built off of Div, but initializes the EMP web framework, if neeeded, and activates itself. It also provides quick ways to add and lookup widgets.
- 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
- 2015-2017
For example, you can use doc.AddButon(…) to add a new button to the document, where the … can be any of the mechanisms to build a new button. This technique works for any widget type.
You can also look up any widget by name. For example, if you previously created a Canvas widget with the HTML id “my_canvas”, you can look it up later by using doc.Canvas(“my_canvas”)
-
namespace
emp
If we are in emscripten, make sure to include the header.
This file contains extra analysis tools to use with systematics managers that have non-null DATA_TYPES.
- 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
- 2018
This file contains functions for adding additional data files to Worlds.
- 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
- 2018
Useful functions for emscripten¶
Specialized, useful function for Empirical.
- 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
- 2015-2017
Defines
-
AlertVar
(VAR)¶
-
namespace
emp
If we are in emscripten, make sure to include the header.
This file contains extra analysis tools to use with systematics managers that have non-null DATA_TYPES.
- 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
- 2018
This file contains functions for adding additional data files to Worlds.
- 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
- 2018
Functions
-
static void
DelayCall
(const std::function<void()> &in_funint delay, )¶ Call a function after a specified amount of time.
-
static void
OnResize
(const std::function<void()> &in_fun)¶ Provide a function to call whenever a window’s size changes (no arguments).
-
static void
OnResize
(const std::function<void(int, int)> &in_fun)¶ Provide a function to call whenever a window’s size changes (new size as arguments)
-
double
GetTime
()¶ Get the current time, as provided by the web browser.
-
int
GetWindowInnerWidth
()¶ Determine with width of the current window.
-
int
GetWindowInnerHeight
()¶ Determine with height of the current window.
-
static void
SetCursor
(const char *type)¶
Event Handling¶
Event handlers that use JQuery.
- 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
- 2015-2017
-
namespace
emp
If we are in emscripten, make sure to include the header.
This file contains extra analysis tools to use with systematics managers that have non-null DATA_TYPES.
- 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
- 2018
This file contains functions for adding additional data files to Worlds.
- 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
- 2018
-
namespace
web
Functions
-
template <typename FUN_TYPE>
voidOnDocumentReady
(FUN_TYPE &&fun)¶ Runs the specified function when the document is finished loading and being set up.
-
struct
Event
¶ - #include <events.h>
Data common to all web events.
Subclassed by emp::web::KeyboardEvent, emp::web::MouseEvent, emp::web::WheelEvent
Public Functions
-
template <int ARG_ID>
voidLoadFromArg
()¶
-
template <int ARG_ID>
-
struct
KeyboardEvent
: public emp::web::Event¶ - #include <events.h>
Keyboard-specific information about web events.
Public Functions
-
template <int ARG_ID>
voidLoadFromArg
()¶
Public Members
-
bool
altKey
¶ Was “ALT” key was pressed?
-
bool
ctrlKey
¶ Was “CTRL” key pressed?
-
bool
metaKey
¶ Was “META” key pressed?
-
bool
shiftKey
¶ Was “SHIFT” key pressed?
-
int
charCode
¶ Unicode character pressed.
-
int
keyCode
¶ Which key was pressed on the keyboard (e.g., ‘a’ and ‘A’ are the same)
-
bool
bubbles
¶ Is this a bubbling event?
-
bool
cancelable
¶ Can the default action be prevented?
-
template <int ARG_ID>
-
struct
MouseEvent
: public emp::web::Event¶ - #include <events.h>
Mouse-specific information about web events.
Public Functions
-
template <int ARG_ID>
voidLoadFromArg
()¶
Public Members
-
bool
altKey
¶ Was “ALT” key was pressed?
-
bool
ctrlKey
¶ Was “CTRL” key pressed?
-
bool
metaKey
¶ Was “META” key pressed?
-
bool
shiftKey
¶ Was “SHIFT” key pressed?
Which mouse button was pressed? -1=none (0/1/2)
-
int
detail
¶ How many clicks happened in short succession?
-
int
clientX
¶ X-mouse postion, relative to current window.
-
int
clientY
¶ Y-mouse postion, relative to current window.
-
int
screenX
¶ X-mouse position, relative to the screen.
-
int
screenY
¶ Y-mouse position, relative to the screen.
-
bool
bubbles
Is this a bubbling event?
-
bool
cancelable
Can the default action be prevented?
-
template <int ARG_ID>
-
struct
WheelEvent
: public emp::web::Event¶ - #include <events.h>
Mouse-wheel-specific information about web events.
Public Functions
-
template <int ARG_ID>
voidLoadFromArg
()¶
Public Members
-
int
deltaX
¶ Horizontal scroll amount.
-
int
deltaY
¶ Vertical scroll amount.
-
int
deltaZ
¶ Scroll amount of a mouse wheel for the z-axis.
-
int
deltaMode
¶ The unit of measurements for delta values (pixels, lines or pages)
-
bool
bubbles
Is this a bubbling event?
-
bool
cancelable
Can the default action be prevented?
-
template <int ARG_ID>
-
template <typename FUN_TYPE>
File Input¶
Specs for the FileInput widget (click on to upload a file)
- 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
- 2015-2018
-
namespace
emp
If we are in emscripten, make sure to include the header.
This file contains extra analysis tools to use with systematics managers that have non-null DATA_TYPES.
- 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
- 2018
This file contains functions for adding additional data files to Worlds.
- 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
- 2018
-
namespace
web
-
class
FileInput
: public emp::web::internal::WidgetFacet<FileInput>¶ - #include <FileInput.h>
FileInput will convert the file to a std::string and pass the result to a designated function.
To create a new file input, you must pass it a void function that takes a const std::string & as its only argument. When a file is loaded, the specified function is called and the body of the file is passed in as the string.
Public Types
-
using
INFO_TYPE
= FileInputInfo¶
Public Functions
-
FileInput
(const std::function<void(const std::string&)> &in_cb, const std::string &in_id = "", )¶ Create a new Fileinput; supply the function to call with the file contents as a string (and optionally the HTML identifier to be used).
-
FileInput
(const std::function<void(const emp::File&)> &cb, const std::string &in_id = "", )¶ Create a new FileInput; supply the function to call with the file contents as a File object (and optionally the HTML identifier to be used).
-
virtual
~FileInput
()¶
-
FileInput &
Callback
(const std::function<void(const std::string&)> &in_cb)¶ Change the callback function to use when a new file is loaded.
-
bool
HasAutofocus
() const¶ Determine if this object currently has autofocus.
-
bool
IsDisabled
() const¶ Determine if this object is currently disabled.
Protected Functions
-
FileInputInfo *
Info
()¶
-
const FileInputInfo *
Info
() const¶
-
FileInput
(FileInputInfo *in_info)¶
Friends
-
friend
emp::web::FileInputInfo
-
class
FileInputInfo
: public emp::web::internal::WidgetInfo¶ - #include <FileInput.h>
Protected Functions
-
FileInputInfo
(const FileInputInfo&)¶
-
FileInputInfo &
operator=
(const FileInputInfo&)¶
-
virtual
~FileInputInfo
()¶
-
void
UpdateAutofocus
(bool in_af)¶
-
void
UpdateDisabled
(bool in_dis)¶
Private Members
-
friend emp::web::FileInput::FileInputInfo::FileInput
-
-
using
-
class
Font¶
Maintains basic information about a font to be used in HTML.
- 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
- 2015-2017
-
namespace
emp
If we are in emscripten, make sure to include the header.
This file contains extra analysis tools to use with systematics managers that have non-null DATA_TYPES.
- 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
- 2018
This file contains functions for adding additional data files to Worlds.
- 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
- 2018
-
namespace
web
-
class
Font
¶ - #include <Font.h>
Maintain information about an HTML font.
Public Functions
-
Font
(const std::string &_family = "Helvetica", int _size = 15, const std::string &_color = "black", bool _bold = false, bool _italic = false)¶
-
~Font
()¶
-
int
GetSize
() const¶
-
bool
IsBold
() const¶
-
bool
IsItalic
() const¶
-
bool
IsSmallcaps
() const¶
-
bool
IsUnderlined
() const¶
-
bool
IsOverlined
() const¶
-
bool
IsStrikethrough
() const¶
-
bool
IsWavyLine
() const¶
-
bool
HasLine
() const¶
Protected Attributes
-
bool
is_bold
¶ Is this font bold?
-
bool
is_italic
¶ Is this font itaic?
-
bool
is_smallcaps
¶ Should this test be in small caps?
-
bool
is_underlined
¶ Should this text be underlined?
-
bool
is_overlined
¶ Should this text have a line above it?
-
bool
is_linethrough
¶ Should this text have a line through it?
-
bool
is_wavy_line
¶ Should lines be made wavy?
-
-
class
Images¶
Easily load an image and place it in a document.
- 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
- 2015-2017
-
namespace
emp
If we are in emscripten, make sure to include the header.
This file contains extra analysis tools to use with systematics managers that have non-null DATA_TYPES.
- 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
- 2018
This file contains functions for adding additional data files to Worlds.
- 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
- 2018
-
namespace
web
-
class
Image
: public emp::web::internal::WidgetFacet<Image>¶ - #include <Image.h>
The Image widget will load an image from a specified URL. For example, you can use emp::web::Image(“http://kripken.github.io/emscripten-site/_static/Emscripten_logo_full.png”) to load the emscripten logo from its website. These can be easily inserted into a web document using << and all JS callbacks (after loading) will be handled automatically.
You can also set the Alt-text with the Alt() function.
Public Functions
-
Image
(const std::string &in_url, const std::string &in_id = "")¶ Create a new image, indicating the URL to load from.
-
virtual
~Image
()¶
Friends
-
friend
emp::web::ImageInfo
-
class
ImageInfo
: public emp::web::internal::WidgetInfo¶ - #include <Image.h>
Private Members
-
friend emp::web::Image::ImageInfo::Image
-
-
-
class
Initialization¶
Define Initialize() and other functions to set up Empirical to build Emscripten projects.
- 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
- 2015-2017
-
namespace
emp
If we are in emscripten, make sure to include the header.
This file contains extra analysis tools to use with systematics managers that have non-null DATA_TYPES.
- 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
- 2018
This file contains functions for adding additional data files to Worlds.
- 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
- 2018
Javascript Utilities¶
Tools for passing data between C++ and Javascript.
- 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
- 2015-2018
-
namespace
emp
If we are in emscripten, make sure to include the header.
This file contains extra analysis tools to use with systematics managers that have non-null DATA_TYPES.
- 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
- 2018
This file contains functions for adding additional data files to Worlds.
- 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
- 2018
Functions
-
std::map<std::string, std::string>
get_type_to_string_map
()¶ This function returns a std::map mapping typeid names to the appropriate strings to describe those types in Javscript. This is useful when using getValue() from within EM_ASM macros.
For example, say we have a templated function that takes a pointer to type T. We find out the appropriate string for type T: std::map<const char*, std::string> type_map = GetTypeToStringMap(); std::string type_string = type_map[typeid(T).name()];
Now we can pass type_string.c_str() into EM_ASM_ARGS: `EM_ASM_ARGS({ var value = getValue($0, $1); }, pointer, type_string.c_str();`
-
template <typename C, class = typename C::value_type>
voidpass_array_to_javascript
(C values)¶ This function can be called to pass an array, vector, or other container with contiguously stored data into Javascript. The array will be stored in emp.__incoming_array. Currently supports arrays containing all of the types defined in get_type_to_string_map, which are also all of the types that emscripten supports getting via pointer. This function also supports nested arrays, and arrays of objects created with introspective tuple structs.
-
template <std::size_t SIZE, typename T>
voidpass_array_to_cpp
(emp::array<T, SIZE> &arr, bool recurse = false)¶ This function lets you pass an array from javascript to C++! It takes a reference to the array as an argument and populates it with the contents of emp.__outgoing_array.
Currently accepts arrays of ints, floats, doubles, chars, and std::strings The size of the passed array must be equal to the size of the array stored in emp.__outgoing_array
JSWrap¶
Wrap a C++ function and convert it to an integer that can be called from Javascript.
To wrap a function, call:
- 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
- 2015-2018
uint32_t fun_id = emp::JSWrap(FunctionToBeWrapped, "JS_Function_Name");
`
To manually callback a function from Javascript, first set emp_i.cb_args
to an array of function arguments, then call empCppCallback( fun_id );
This all happens automatically if you use the emp.Callback(fun_id, args...)
function from Javascript.
The JS_Function_Name string is optional, but if you use it, the appropriate function will be automatically generated in Javascript by JSWrap, in the emp class.
For example, if you have:
int AddPair(int x, int y) { return x + y; }
`
You can wrap it with:
size_t fun_id = emp::JSWrap(AddPair, "AddPair");
And then in Javascript, you can simply call it as:
emp.AddPair(4, 5); // will return 9.
Keypress Manager¶
KeypressManager is a tracker for keypresses in HTML5 pages.
When a KeypressManager is created, it can be given functions to run in response to different types of key presses via overloaded version of the AddKeydownCallback method. Each of these accepts an order parameter that is optional and, if provided, will indicate the order in which tests should be performed to resolve a keypress. If order is not provided, tests will occur in the order that they were given to the manager.
- 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
- 2015-2017
The specific versions of AddKeydownCallback are:
void AddKeydownCallback(std::function<bool(const html5::KeyboardEvent &)> cb_fun, int order=-1)
Link a function to the KeypressManager that is called for any unresolved keypress. The function must take in an html5::KeyboardEvent (which includes information about the specific key pressed as well as any modifiers such as SHIFT or CTRL) and it must return a boolean value indicating whether it has resolved the keypress.
void AddKeydownCallback(char key, std::function<void()> cb_fun, int order=-1)
Link a specific key to a target function to be called when that key is pressed. The function my return a void and take no arguments.
void AddKeydownCallback(const std::string & key_set, std::function<void()> cb_fun, int order=-1)
Same as the previous method, but will respond to any of the keys in the provided string.
-
namespace
emp
If we are in emscripten, make sure to include the header.
This file contains extra analysis tools to use with systematics managers that have non-null DATA_TYPES.
- 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
- 2018
This file contains functions for adding additional data files to Worlds.
- 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
- 2018
-
namespace
web
-
class
KeypressManager
¶ - #include <KeypressManager.h>
Public Functions
-
KeypressManager
()¶
-
~KeypressManager
()¶
-
int
GetFunCount
() const¶
-
int
GetNextOrder
() const¶
-
void
AddKeydownCallback
(std::function<bool(const KeyboardEvent&)> cb_fun, int order = -1, )¶ Link a function to the KeypressManager that is called for any unresolved keypress. The function must take in an html5::KeyboardEvent (which includes information about the specific key pressed as well as any modifiers such as SHIFT or CTRL) and it must return a boolean value indicating whether it has resolved the keypress.
-
void
AddKeydownCallback
(char key, std::function<void()> cb_funint order = -1, )¶ Link a specific key to a target function to be called when that key is pressed. The function my return a void and take no arguments.
Private Functions
-
bool
DoCallback
(const KeyboardEvent &evt_info)¶
-
-
class
Listeners¶
A class for tracking font event listeners for Widgets.
- 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
- 2015-2017
-
namespace
emp
If we are in emscripten, make sure to include the header.
This file contains extra analysis tools to use with systematics managers that have non-null DATA_TYPES.
- 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
- 2018
This file contains functions for adding additional data files to Worlds.
- 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
- 2018
-
namespace
web
-
class
Listeners
¶ - #include <Listeners.h>
Track a set of JavaScript Listeners with their callback IDs.
Public Functions
-
Listeners
()¶
-
size_t
GetSize
() const¶ How many listeners are we tracking?
-
Listeners &
Set
(const std::string &name, size_t fun_id)¶ Use a pre-calculated function ID with a new listener.
-
template <typename... Ts>
Listeners &Set
(const std::string &name, const std::function<void(Ts... args)> &in_fun)¶ Calculate its own function ID with JSWrap.
-
void
Clear
()¶ Remove all listeners.
-
operator bool
() const¶ true/false : do any listeners exist?
Public Static Functions
-
-
class
Raw Image¶
Handle the fundamental loading of an image (without Widget tracking)
- 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
- 2015-2018
-
namespace
emp
If we are in emscripten, make sure to include the header.
This file contains extra analysis tools to use with systematics managers that have non-null DATA_TYPES.
- 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
- 2018
This file contains functions for adding additional data files to Worlds.
- 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
- 2018
-
class
RawImage
¶ - #include <RawImage.h>
Fundamental information about a single image.
Public Functions
-
~RawImage
()¶
-
int
GetID
() const¶
-
bool
HasLoaded
() const¶
-
bool
HasError
() const¶
Private Static Functions
-
static internal::ImageManager &
GetManager
()¶
-
-
namespace
internal
¶ -
struct
ImageInfo
¶ - #include <RawImage.h>
Detailed information about an image.
Public Functions
-
void
MarkLoaded
()¶ Trigger this image as loaded.
-
void
MarkError
()¶ Trigger this image as having an error.
-
void
-
class
ImageManager
¶ - #include <RawImage.h>
-
struct
Selector¶
Specs for the Selector widget.
A Selector widget provides the user with a pull-down menu. It can be examined at any time (via GetSelectID()) or else alerts call a designated function when a particular option is chosen.
- 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
- 2015-2017
UI::Selector sel(“sel”);
sel.SetOption(“Option 1”); sel.SetOption(“Option B”, TriggerB) ; sel.SetOption(“Option the Third”, [](){ emp::Alert(“3 chosen!”} ); sel.SetOption(“Option IV”);
In this example, the second option will call TriggerB when it is chosen, while the third option will call the provided lambda function.
-
namespace
emp
If we are in emscripten, make sure to include the header.
This file contains extra analysis tools to use with systematics managers that have non-null DATA_TYPES.
- 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
- 2018
This file contains functions for adding additional data files to Worlds.
- 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
- 2018
-
namespace
web
-
class
Selector
: public emp::web::internal::WidgetFacet<Selector>¶ - #include <Selector.h>
Public Types
-
using
INFO_TYPE
= SelectorInfo¶
Public Functions
-
virtual
~Selector
()¶
-
size_t
GetSelectID
() const¶ Get the ID of the currently active selection.
-
size_t
GetNumOptions
() const¶ Get the total number of options setup in the selector.
-
bool
HasAutofocus
() const¶ Determine if the selector has autofocus.
-
bool
IsDisabled
() const¶ Is the selector currently disabled?
-
Selector &
SetOption
(const std::string &in_option, const std::function<void()> &in_cb)¶ Add a new option to the selector and the function to be called if it is chosen.
-
Selector &
SetOption
(const std::string &in_option, const std::function<void()> &in_cbsize_t opt_id, )¶ Add an option to the selector associated with a specific ID (and the function to be called if it is chosen)
-
Selector &
SetOption
(const std::string &in_option)¶ Set a selector option name, but no function to be called.
Protected Functions
-
SelectorInfo *
Info
()¶
-
const SelectorInfo *
Info
() const¶
-
Selector
(SelectorInfo *in_info)¶
Friends
-
friend
emp::web::SelectorInfo
-
class
SelectorInfo
: public emp::web::internal::WidgetInfo¶ - #include <Selector.h>
Protected Functions
-
SelectorInfo
(const SelectorInfo&)¶
-
SelectorInfo &
operator=
(const SelectorInfo&)¶
-
virtual
~SelectorInfo
()¶
-
virtual bool
IsSelectorInfo
() const¶
-
void
DoChange
(size_t new_id)¶
-
void
UpdateAutofocus
(bool in_af)¶
-
void
UpdateDisabled
(bool in_dis)¶
Protected Attributes
-
size_t
select_id
¶ Which index is currently selected?
-
bool
autofocus
¶
-
bool
disabled
¶
-
size_t
callback_id
¶
Private Members
-
friend emp::web::Selector::SelectorInfo::Selector
-
-
using
-
class
Styles¶
A CSS class for tracking font style, etc.
- 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
- 2015-2017
-
namespace
emp
If we are in emscripten, make sure to include the header.
This file contains extra analysis tools to use with systematics managers that have non-null DATA_TYPES.
- 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
- 2018
This file contains functions for adding additional data files to Worlds.
- 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
- 2018
-
namespace
web
-
class
Style
¶ - #include <Style.h>
Class to maintain a map of setting names to values that can be easily ported over to JavaScript. A companial class, Attributes, also exists.
Public Functions
-
Style
()¶
-
size_t
GetSize
() const¶ Return a count of the number of settings that have been set.
-
template <typename SET_TYPE>
Style &Set
(const std::string &s, SET_TYPE v)¶ Record that setting “s” is set to value “v” (converted to string) and return this object.
-
bool
Has
(const std::string &setting) const¶ Return true/false based on whether “setting” has been given a value in this Style.
-
const std::string &
Get
(const std::string &setting)¶ Return the (string) value of “setting” that has been recorded in this Style. If setting did not exist, this does create an empty entry and return it.
-
void
Clear
()¶ Remove all setting values.
-
void
Apply
(const std::string &widget_id, const std::string &setting)¶ Apply only a SPECIFIC style setting from the setting library.
-
operator bool
() const¶ Have any settings be set?
Public Static Functions
-
-
class
Tables¶
Specs for the Table widget.
TableInfo is the core information for a table and has two helper classes: TableRowInfo and TableDataInfo. The Table class is a smart pointer to a TableInfo object.
- 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
- 2015-2017
A Table is composed of a series of rows, each with the same number of columns. TableDataInfo may be muliple cells wide/tall, masking other cells.
-
namespace
emp
If we are in emscripten, make sure to include the header.
This file contains extra analysis tools to use with systematics managers that have non-null DATA_TYPES.
- 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
- 2018
This file contains functions for adding additional data files to Worlds.
- 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
- 2018
-
namespace
web
-
class
Table
: public emp::web::TableWidget¶ - #include <Table.h>
Public Functions
-
Table
(const TableWidget &in)¶
-
Table
()¶
-
template <typename SETTING_TYPE>
Table &RowCSS
(size_t row_id, const std::string &setting, SETTING_TYPE &&value)¶ Apply CSS to target row.
-
template <typename SETTING_TYPE>
Table &CellCSS
(size_t row_id, size_t col_id, const std::string &setting, SETTING_TYPE &&value)¶ Apply CSS to target cell.
-
template <typename SETTING_TYPE>
Table &RowsCSS
(const std::string &setting, SETTING_TYPE &&value)¶ Apply CSS to all rows. (: Should we use fancier jquery here?)
-
template <typename SETTING_TYPE>
Table &CellsCSS
(const std::string &setting, SETTING_TYPE &&value)¶ Apply CSS to all cells.
-
size_t
GetNumCols
() const¶
-
size_t
GetNumRows
() const¶
-
size_t
GetNumCells
() const¶
-
virtual void
PrepareAppend
()¶ Setup << operator to redirect to Append; option preparation can be overridden.
-
size_t
GetCurRow
() const¶ Determine which row currnetly has focus.
-
size_t
GetCurCol
() const¶ Determine which column currently has focus.
-
void
ClearTable
()¶
-
void
ClearRows
()¶
-
void
ClearRow
(size_t r)¶
-
void
ClearCol
(size_t c)¶
-
void
ClearRowGroup
(size_t r)¶
-
void
ClearColGroup
(size_t c)¶
-
void
ClearCells
()¶
-
void
ClearCell
(size_t r, size_t c)¶
-
TableCell
GetCell
(size_t r, size_t c)¶ Focus on a specifc cell in the table.
-
TableRow
GetRow
(size_t r)¶ Focus on a specifc row in the table.
-
TableCol
GetCol
(size_t c)¶ Focus on a specifc column in the table.
-
TableRowGroup
GetRowGroup
(size_t r)¶ Focus on a specifc group of rows in the table.
-
TableColGroup
GetColGroup
(size_t c)¶ Focus on a specifc group of columns in the table.
-
Widget
AddText
(size_t r, size_t c, const std::string &text)¶ Add text to a specified cell in the table.
Protected Types
-
using
parent_t
= internal::WidgetFacet<TableWidget>¶
-
-
class
TableWidget
: public emp::web::internal::WidgetFacet<TableWidget>¶ - #include <Table.h>
Subclassed by emp::web::Table, emp::web::TableCell, emp::web::TableCol, emp::web::TableColGroup, emp::web::TableRow, emp::web::TableRowGroup
Public Functions
-
TableWidget
(const TableWidget &in)¶
-
TableWidget
()¶
-
virtual
~TableWidget
()¶
-
size_t
GetNumCols
() const¶
-
size_t
GetNumRows
() const¶
-
size_t
GetNumCells
() const¶
-
virtual void
PrepareAppend
()¶ Setup << operator to redirect to Append; option preparation can be overridden.
-
size_t
GetCurRow
() const¶ Determine which row currnetly has focus.
-
size_t
GetCurCol
() const¶ Determine which column currently has focus.
-
void
ClearTable
()¶
-
void
ClearRows
()¶
-
void
ClearRow
(size_t r)¶
-
void
ClearCol
(size_t c)¶
-
void
ClearRowGroup
(size_t r)¶
-
void
ClearColGroup
(size_t c)¶
-
void
ClearCells
()¶
-
void
ClearCell
(size_t r, size_t c)¶
-
TableCell
GetCell
(size_t r, size_t c)¶ Focus on a specifc cell in the table.
-
TableRow
GetRow
(size_t r)¶ Focus on a specifc row in the table.
-
TableCol
GetCol
(size_t c)¶ Focus on a specifc column in the table.
-
TableRowGroup
GetRowGroup
(size_t r)¶ Focus on a specifc group of rows in the table.
-
TableColGroup
GetColGroup
(size_t c)¶ Focus on a specifc group of columns in the table.
-
Widget
AddText
(size_t r, size_t c, const std::string &text)¶ Add text to a specified cell in the table.
Protected Types
-
using
parent_t
= internal::WidgetFacet<TableWidget>
Protected Functions
-
void
DoCSS
(const std::string &setting, const std::string &value)¶ Apply CSS to appropriate component based on current state.
Friends
-
friend
emp::web::internal::TableInfo
-
-
namespace
internal
¶ -
struct
TableColInfo
¶ - #include <Table.h>
Public Members
-
WidgetExtras
extras
¶
-
WidgetExtras
-
struct
TableDataInfo
¶ - #include <Table.h>
Public Functions
Public Members
-
size_t
colspan
=1¶ How many columns wide is this TableData?
-
size_t
rowspan
=1¶ How many rows deep is this TableData?
-
bool
header
=false¶ Is this TableData a header (
vs
)?
-
bool
masked
=false¶ Is this cell masked by another cell?
-
WidgetExtras
extras
¶ Extra annotations (attributes, style, listeners)
-
size_t
-
struct
TableGroupInfo
: public emp::web::WidgetExtras¶ - #include <Table.h>
Public Members
-
size_t
span
= 1¶
-
bool
masked
= false¶ How many rows/columns does this group represent?
-
WidgetExtras
extras
¶ Is the current group masked because of a previous span?
-
size_t
-
class
TableInfo
: public emp::web::internal::WidgetInfo¶ - #include <Table.h>
Protected Functions
-
virtual
~TableInfo
()¶
-
virtual bool
IsTableInfo
() const¶
-
void
Resize
(size_t new_rows, size_t new_cols)¶
-
void
DoActivate
(bool top_level = true)¶
-
void
ClearCellChildren
(size_t row_id, size_t col_id)¶
-
void
ClearRowChildren
(size_t row_id)¶
-
void
ClearColChildren
(size_t col_id)¶
-
void
ClearRowGroupChildren
(size_t row_id)¶
-
void
ClearColGroupChildren
(size_t col_id)¶
-
void
ClearTableChildren
()¶
-
void
ClearCell
(size_t row_id, size_t col_id)¶
-
void
ClearRowCells
(size_t row_id)¶
-
void
ClearColCells
(size_t col_id)¶
-
void
ClearRow
(size_t row_id)¶
-
void
ClearCol
(size_t col_id)¶
-
void
ClearRowGroup
(size_t row_id)¶
-
void
ClearColGroup
(size_t col_id)¶
-
void
ClearTableCells
()¶
-
void
ClearTableRows
()¶
-
void
ClearTable
()¶
-
void
ReplaceHTML
()¶
Protected Attributes
-
size_t
row_count
¶
-
size_t
col_count
¶ How big is this table?
-
emp::vector<TableRowInfo>
rows
¶
-
emp::vector<TableColInfo>
cols
¶ Detail object for each row.
-
emp::vector<TableGroupInfo>
col_groups
¶ Detail object for each column (if needed)
-
emp::vector<TableGroupInfo>
row_groups
¶ Detail object for each column group (if needed)
-
size_t
append_row
¶ Detail object for each row group (if needed)
-
size_t
append_col
¶ Which row is triggering an append?
Private Members
-
friend emp::web::internal::TableInfo::TableWidget
-
friend emp::web::internal::TableInfo::Table
-
friend emp::web::internal::TableInfo::TableCell
-
friend emp::web::internal::TableInfo::TableRow
-
friend emp::web::internal::TableInfo::TableCol
-
friend emp::web::internal::TableInfo::TableRowGroup
-
friend emp::web::internal::TableInfo::TableColGroup
-
virtual
-
struct
TableRowInfo
¶ - #include <Table.h>
Public Functions
-
template <typename SETTING_TYPE>
TableRowInfo &CellsCSS
(const std::string &setting, SETTING_TYPE &&value)¶ Apply CSS to all cells in row.
-
template <typename SETTING_TYPE>
TableRowInfo &CellCSS
(size_t col_id, const std::string &setting, SETTING_TYPE &&value)¶ Apply CSS to specific cell in row.
Public Members
-
emp::vector<TableDataInfo>
data
¶ detail object for each cell in this row.
-
WidgetExtras
extras
¶ Extra annotations (attributes, style, listeners)
-
template <typename SETTING_TYPE>
-
struct
-
class
Text¶
Specs for the Text widget.
A representation of text on a web page. Text Widgets can be included inside of Divs or Tables to cordon off a section of text (and will be automatically created when text is streamed into these other widgets). The primary benefit of explicitly creating your own text widget is to control the text style.
- 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
- 2015-2017
-
namespace
emp
If we are in emscripten, make sure to include the header.
This file contains extra analysis tools to use with systematics managers that have non-null DATA_TYPES.
- 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
- 2018
This file contains functions for adding additional data files to Worlds.
- 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
- 2018
-
namespace
web
-
class
Text
: public emp::web::internal::WidgetFacet<Text>¶ - #include <Text.h>
A Text widget handles putting text on a web page that can be controlled and modified.
Public Functions
-
~Text
()¶
Friends
-
friend
emp::web::TextInfo
-
class
TextInfo
: public emp::web::internal::WidgetInfo¶ - #include <Text.h>
Protected Functions
-
virtual
~TextInfo
()¶
-
virtual bool
IsTextInfo
() const¶
-
bool
AppendOK
() const¶
-
void
PreventAppend
()¶
-
Widget
Append
(const std::function<std::string()> &in_fun)¶ Add a function that produces text to this widget. Every time the widget is re-drawn, the function will be re-run to get the latest version of the text. When a Live() function wraps a variable it simply makes sure that this version of Append is called so that the value of the variable is kept live.
Protected Attributes
-
DynamicString
strings
¶ All string (and functions returning strings) in Text widget.
Private Members
-
friend emp::web::Text::TextInfo::Text
-
virtual
-
-
class
Text Areas¶
Specs for the TextArea widget.
- 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
- 2015-2017
-
namespace
emp
If we are in emscripten, make sure to include the header.
This file contains extra analysis tools to use with systematics managers that have non-null DATA_TYPES.
- 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
- 2018
This file contains functions for adding additional data files to Worlds.
- 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
- 2018
-
namespace
web
-
class
TextArea
: public emp::web::internal::WidgetFacet<TextArea>¶ - #include <TextArea.h>
An input field for text data. A function provided at creation time will be called each time the contents of the TextWidget are changed. The current text contents can also always be accessed with the GetText() member function.
Public Types
-
using
INFO_TYPE
= TextAreaInfo¶
Public Functions
-
TextArea
(std::function<void(const std::string&)> in_cb, const std::string &in_id = "", )¶ Build a text area with a specified function to call with every change.
-
virtual
~TextArea
()¶
-
TextArea &
SetCallback
(const std::function<void(const std::string&)> &in_cb)¶ Change the callback function for this TextArea.
-
bool
HasAutofocus
() const¶ Does this widget have auto focus set?
-
bool
IsDisabled
() const¶ Is this widget currently disabled?
Protected Functions
-
TextAreaInfo *
Info
()¶
-
const TextAreaInfo *
Info
() const¶
-
TextArea
(TextAreaInfo *in_info)¶
Friends
-
friend
emp::web::TextAreaInfo
-
class
TextAreaInfo
: public emp::web::internal::WidgetInfo¶ - #include <TextArea.h>
Protected Functions
-
TextAreaInfo
(const TextAreaInfo&)¶
-
TextAreaInfo &
operator=
(const TextAreaInfo&)¶
-
virtual
~TextAreaInfo
()¶
-
virtual bool
IsTextAreaInfo
() const¶
-
void
UpdateAutofocus
(bool in_af)¶
-
void
UpdateDisabled
(bool in_dis)¶
Protected Attributes
-
int
cols
¶ How many columns of text in the area?
-
int
rows
¶ How many rows of text in the area?
-
int
max_length
¶ Maximum number of total characters allowed.
-
uint32_t
callback_id
¶ Callback ID the built-in function for this text area.
Private Members
-
friend emp::web::TextArea::TextAreaInfo::TextArea
-
-
using
-
class
Tweens¶
A Tween manages the gradual shift in properties of one or more widgets over time.
To create a Tween, a duration must be specified, along with an optional default target. Once a Tween is setup, paths can be added to it, which represent the changes that should occur over the specified duration.
- 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
- 2015-2017
A path can be a function to call (with the 0.0 to 1.0 fraction of the time that’s gone by) or a variable to set to the current fraction. Dependants can also be set to refresh with each Tween update.
Available methods include: Tween & AddPath(std::function<void(double)> set_fun, double start_val, double end_val, std::function<double(double)> timing=LINEAR); Tween & AddPath(double & set_var, double start_val, double end_val, std::function<double(double)> timing=LINEAR); Tween & AddDependant(Widget w); void Start(); void Stop();
-
namespace
emp
If we are in emscripten, make sure to include the header.
This file contains extra analysis tools to use with systematics managers that have non-null DATA_TYPES.
- 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
- 2018
This file contains functions for adding additional data files to Worlds.
- 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
- 2018
-
namespace
web
-
class
Tween
¶ - #include <Tween.h>
Public Functions
-
Tween
(double d = 1.0, const Widget &t = nullptr)¶ Build a new tween, specifying the duration it should run for and the widget it should modify.
-
~Tween
()¶
-
Tween &
AddPath
(std::function<void(double)> set_fun, double start_val, double end_val, std::function<double(double)> timing = LINEAR)¶ Alter the path of the change that this tween should take and the function it should call.
-
Tween &
AddPath
(double &set_var, double start_val, double end_val, std::function<double(double)> timing = LINEAR)¶ Alter the path of the change that this tween should take and the variable it should modify.
-
Tween &
AddPath
(Widget w, std::string setting, double start_val, double end_val)¶ Alter the path of the change that this tween should take and the widget setting it should alter. (TODO!)
Private Functions
-
void
AdvanceFrame
()¶
Private Members
-
double
duration
¶
-
bool
running
¶
-
size_t
callback_id
¶
-
double
start_time
¶
-
double
cur_time
¶
-
double
run_time
¶
Private Static Functions
-
static double
LINEAR
(double in)¶
-
struct
Event
¶
-
-
class
Widgets¶
Widgets maintain individual components on a web page and link to Elements.
Each HTML Widget has all of its details stored in a WidgetInfo object; Multiple Widgets can be attached to the same WidgetInfo, simplifying the usage. All the library user needs to worry about is the Widget object itself; the WidgetInfo will be managed behind the scenes.
- 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
- 2015-2017
WidgetInfo contains the basic information for all Widgets Widget is a generic base class, with a shared pointer to WidgetInfo WidgetFacet is a template that allows Set* methods to return derived return-type.
In other files, Widgets will be used to define specific elements. ELEMENTInfo maintains information about the specific widget (derived from WidgetInfo) ELEMENT interfaces to ELEMENTInfo so multiple elements use same core; derived from WidgetFacet
Library users should not need to access Widgets directly, only specific derived types.
Tips for using widgets:
- If you are about to make a lot of changes at once, run Freeze(), make the changes, and then run Activate() again. Freeze prevents widgets from being updated immediately.
- Trust the Widget to handle all of the manipulation behind the scenes
-
namespace
emp
If we are in emscripten, make sure to include the header.
This file contains extra analysis tools to use with systematics managers that have non-null DATA_TYPES.
- 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
- 2018
This file contains functions for adding additional data files to Worlds.
- 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
- 2018
-
namespace
web
-
class
Widget
¶ - #include <Widget.h>
Widget is effectively a smart pointer to a WidgetInfo object, plus some basic accessors.
Subclassed by emp::web::internal::WidgetFacet< RETURN_TYPE >, emp::web::internal::WidgetFacet< Button >, emp::web::internal::WidgetFacet< Canvas >, emp::web::internal::WidgetFacet< D3Visualization >, emp::web::internal::WidgetFacet< Div >, emp::web::internal::WidgetFacet< FileInput >, emp::web::internal::WidgetFacet< Image >, emp::web::internal::WidgetFacet< Selector >, emp::web::internal::WidgetFacet< TableWidget >, emp::web::internal::WidgetFacet< Text >, emp::web::internal::WidgetFacet< TextArea >
Public Functions
-
Widget
(WidgetInfo *in_info = nullptr)¶
-
~Widget
()¶
-
bool
IsNull
() const¶ Test if this widget is valid.
-
bool
IsInactive
() const¶ Test if the activity state of this widget is currently INACTIVE.
-
bool
IsWaiting
() const¶ Test if the activity state of this widget is currently WAITING.
-
bool
IsFrozen
() const¶ Test if the activity state of this widget is currently FROZEN.
-
bool
IsActive
() const¶ Test if the activity state of this widget is currently ACTIVE.
-
bool
AppendOK
() const¶ Is it okay to add more internal Widgets into this one?
-
std::string
GetCSS
(const std::string &setting)¶ Retrieve a specific CSS trait associated with this Widget. Note: CSS-related options may be overridden in derived classes that have multiple styles.
-
std::string
GetAttr
(const std::string &setting)¶ Retrieve a specific attribute associated with this Widget.
-
void
Activate
()¶ Make this widget live, so changes occur immediately (once document is ready)
-
void
Freeze
()¶ Record changes internally, but keep static screen until Activate() is called.
-
void
Deactivate
(bool top_level = true)¶ Record changes internally and REMOVE from screen until Activate is called. (Argument is for recursive, internal use only.)
-
bool
ToggleActive
()¶ Doggle between Active and Deactivated.
-
void
Redraw
()¶ Clear and redraw the current widget on the screen.
-
Widget &
AddDependant
(const Widget &w)¶ Add a dependant to this Widget that should be redrawn when it is.
-
virtual void
PrepareAppend
()¶ Setup << operator to redirect to Append; option preparation can be overridden.
Protected Types
-
enum
ActivityState
¶ Four activity states for any widget: INACTIVE - Not be in DOM at all. WAITING - Will become active once the page finishes loading. FROZEN - Part of DOM, but not updating on the screen. ACTIVE - Fully active; changes are reflected as they happen.
Values:
-
INACTIVE
¶
-
WAITING
¶
-
FROZEN
¶
-
ACTIVE
¶
-
-
using
WidgetInfo
= internal::WidgetInfo¶
Protected Functions
-
template <typename FWD_TYPE>
Widget &ForwardAppend
(FWD_TYPE &&arg)¶ If an Append doesn’t work with current class, forward it to the parent and try there.
-
Widget &
SetInfo
(WidgetInfo *in_info)¶ Set the information associated with this widget.
-
WidgetInfo *
operator->
()¶ Internally, we can treat a Widget as a pointer to its WidgetInfo.
Protected Attributes
-
WidgetInfo *
info
¶ Information associated with this widget.
Protected Static Functions
-
static WidgetInfo *
Info
(const Widget &w)¶ Give derived classes the ability to access widget info.
-
-
namespace
internal
Functions
-
class
WidgetCommand
¶ - #include <Widget.h>
Base class for command-objects that can be fed into widgets.
Subclassed by emp::web::Close, emp::web::PrintStr
-
template <typename RETURN_TYPE>
classWidgetFacet
: public emp::web::Widget¶ - #include <Widget.h>
WidgetFacet is a template that provides accessors into Widget with a derived return type.
Public Types
-
template<>
usingreturn_t
= RETURN_TYPE¶
Public Functions
-
template <typename SETTING_TYPE>
return_t &SetCSS
(const std::string &setting, SETTING_TYPE &&value)¶ Set a specific CSS value for this widget.
-
template <typename SETTING_TYPE>
return_t &SetAttr
(const std::string &setting, SETTING_TYPE &&value)¶ Set a specific Attribute value for this widget.
-
template <typename T1, typename T2, typename... OTHER_SETTINGS>
return_t &SetCSS
(const std::string &setting1, T1 &&val1, const std::string &setting2, T2 &&val2, OTHER_SETTINGS... others)¶ Multiple CSS settings can be provided simultaneously.
-
template <typename T1, typename T2, typename... OTHER_SETTINGS>
return_t &SetAttr
(const std::string &setting1, T1 &&val1, const std::string &setting2, T2 &&val2, OTHER_SETTINGS... others)¶ Multiple Attributes can be provided simultaneously.
-
return_t &
SetCSS
(const Style &in_style)¶ Allow multiple CSS settings to be provided as a single object. (still go through DoCSS given need for virtual re-routing.)
-
return_t &
SetAttr
(const Attributes &in_attr)¶ Allow multiple Attr settings to be provided as a single object. (still go through DoAttr given need for virtual re-routing.)
-
return_t &
On
(const std::string &event_name, const std::function<void()> &fun)¶ Provide an event and a function that will be called when that event is triggered. In this case, the function as no arguments.
-
return_t &
On
(const std::string &event_name, const std::function<void(MouseEvent evt)> &fun)¶ Provide an event and a function that will be called when that event is triggered. In this case, the function takes a mouse event as an argument, with full info about mouse.
-
return_t &
On
(const std::string &event_name, const std::function<void(double, double)> &fun)¶ Provide an event and a function that will be called when that event is triggered. In this case, the function takes two doubles which will be filled in with mouse coordinates.
-
template <typename T>
return_t &OnResize
(T &&arg)¶ Provide a function to be called when the window is resized.
-
template <typename T>
return_t &OnClick
(T &&arg)¶ Provide a function to be called when the mouse button is clicked in this Widget.
-
template <typename T>
return_t &OnDoubleClick
(T &&arg)¶ Provide a function to be called when the mouse button is double clicked in this Widget.
-
template <typename T>
return_t &OnMouseDown
(T &&arg)¶ Provide a function to be called when the mouse button is pushed down in this Widget.
-
template <typename T>
return_t &OnMouseUp
(T &&arg)¶ Provide a function to be called when the mouse button is released in this Widget.
-
template <typename T>
return_t &OnMouseMove
(T &&arg)¶ Provide a function to be called whenever the mouse moves in this Widget.
-
template <typename T>
return_t &OnMouseOut
(T &&arg)¶ Provide a function to be called whenever the mouse leaves the Widget.
-
template <typename T>
return_t &OnMouseOver
(T &&arg)¶ Provide a function to be called whenever the mouse moves over the Widget.
-
template <typename T>
return_t &OnMouseWheel
(T &&arg)¶ Provide a function to be called whenever the mouse wheel moves in this Widget.
-
template <typename T>
return_t &OnKeydown
(T &&arg)¶ Provide a function to be called whenever a key is pressed down in this Widget.
-
template <typename T>
return_t &OnKeypress
(T &&arg)¶ Provide a function to be called whenever a key is pressed down and released in this Widget.
-
template <typename T>
return_t &OnKeyup
(T &&arg)¶ Provide a function to be called whenever a key is pressed released in this Widget.
-
template <typename T>
return_t &OnCopy
(T &&arg)¶ Provide a function to be called whenever text is copied in this Widget.
-
template <typename T>
return_t &OnCut
(T &&arg)¶ Provide a function to be called whenever text is cut in this Widget.
-
template <typename T>
return_t &OnPaste
(T &&arg)¶ Provide a function to be called whenever text is pasted in this Widget.
-
return_t &
SetWidth
(double w, const std::string &unit = "px")¶ Update the width of this Widget.
- Parameters
unit
: defaults to pixels (“px”), but can also be a measured distance (e.g, “inches”) or a percentage(“%”)
-
return_t &
SetHeight
(double h, const std::string &unit = "px")¶ Update the height of this Widget.
- Parameters
unit
: defaults to pixels (“px”), but can also be a measured distance (e.g, “inches”) or a percentage(“%”)
-
return_t &
SetSize
(double w, double h, const std::string &unit = "px")¶ Update the size (width and height) of this widget.
- Parameters
unit
: defaults to pixels (“px”), but can also be a measured distance (e.g, “inches”) or a percentage(“%”)
-
return_t &
Center
()¶ Move this widget to the center of its container.
-
return_t &
SetPosition
(int x, int y, const std::string &unit = "px", const std::string &pos_type = "absolute", const std::string &x_anchor = "left", const std::string &y_anchor = "top")¶ Set the x-y position of this widget within its container.
-
return_t &
SetPositionRT
(int x, int y, const std::string &unit = "px")¶ Set the x-y position of this Widget within its container, using the TOP-RIGHT as an anchor.
-
return_t &
SetPositionRB
(int x, int y, const std::string &unit = "px")¶ Set the x-y position of this Widget within its container, using the BOTTOM-RIGHT as an anchor.
-
return_t &
SetPositionLB
(int x, int y, const std::string &unit = "px")¶ Set the x-y position of this Widget within its container, using the BOTTOM-LEFT as an anchor.
-
return_t &
SetPositionFixed
(int x, int y, const std::string &unit = "px")¶ Set the x-y position of this Widget, fixed within the browser window.
-
return_t &
SetPositionFixedRT
(int x, int y, const std::string &unit = "px")¶ Set the x-y position of the top-right corner this Widget, fixed within the browser window.
-
return_t &
SetPositionFixedRB
(int x, int y, const std::string &unit = "px")¶ Set the x-y position of the bottom-right corner this Widget, fixed within the browser window.
-
return_t &
SetPositionFixedLB
(int x, int y, const std::string &unit = "px")¶ Set the x-y position of the bottom-left corner this Widget, fixed within the browser window.
-
return_t &
SetFloat
(const std::string &f = "left")¶ Set this Widget to float appropriately within its containter.
-
return_t &
SetFontSizeVW
(double s)¶ Setup the size of the Font to be used in this Widget in units of % of viewport width.
-
return_t &
SetCenterText
()¶ Align text to be centered.
-
return_t &
SetPadding
(double p, const std::string &unit = "px")¶ The the number of pixels (or alternate unit) for the padding around cells (used with Tables)
-
bool
IsNull
() const¶ Test if this widget is valid.
-
bool
IsInactive
() const¶ Test if the activity state of this widget is currently INACTIVE.
-
bool
IsWaiting
() const¶ Test if the activity state of this widget is currently WAITING.
-
bool
IsFrozen
() const¶ Test if the activity state of this widget is currently FROZEN.
-
bool
IsActive
() const¶ Test if the activity state of this widget is currently ACTIVE.
-
bool
AppendOK
() const¶ Is it okay to add more internal Widgets into this one?
-
std::string
GetCSS
(const std::string &setting)¶ Retrieve a specific CSS trait associated with this Widget. Note: CSS-related options may be overridden in derived classes that have multiple styles.
-
std::string
GetAttr
(const std::string &setting)¶ Retrieve a specific attribute associated with this Widget.
-
void
Activate
()¶ Make this widget live, so changes occur immediately (once document is ready)
-
void
Freeze
()¶ Record changes internally, but keep static screen until Activate() is called.
-
void
Deactivate
(bool top_level = true)¶ Record changes internally and REMOVE from screen until Activate is called. (Argument is for recursive, internal use only.)
-
bool
ToggleActive
()¶ Doggle between Active and Deactivated.
-
void
Redraw
()¶ Clear and redraw the current widget on the screen.
-
Widget &
AddDependant
(const Widget &w)¶ Add a dependant to this Widget that should be redrawn when it is.
-
virtual void
PrepareAppend
()¶ Setup << operator to redirect to Append; option preparation can be overridden.
Protected Types
-
enum
ActivityState
¶ Four activity states for any widget: INACTIVE - Not be in DOM at all. WAITING - Will become active once the page finishes loading. FROZEN - Part of DOM, but not updating on the screen. ACTIVE - Fully active; changes are reflected as they happen.
Values:
-
INACTIVE
¶
-
WAITING
¶
-
FROZEN
¶
-
ACTIVE
¶
-
-
using
WidgetInfo
= internal::WidgetInfo
Protected Functions
-
WidgetFacet
(const std::string &in_id = "")¶ WidgetFacet cannot be built unless within derived class, so constructors are protected.
-
WidgetFacet
(const WidgetFacet &in)¶
-
WidgetFacet
(WidgetInfo *in_info)¶
-
WidgetFacet &
operator=
(const WidgetFacet &in)¶
-
virtual
~WidgetFacet
()¶
-
virtual void
DoCSS
(const std::string &setting, const std::string &value)¶ CSS-related options may be overridden in derived classes that have multiple styles. By default DoCSS will track the new information and apply it (if active) to the widget.
-
virtual void
DoAttr
(const std::string &setting, const std::string &value)¶ Attr-related options may be overridden in derived classes that have multiple attributes. By default DoAttr will track the new information and apply it (if active) to the widget.
-
virtual void
DoListen
(const std::string &event_name, size_t fun_id)¶ Listener options may be overridden in derived classes that have multiple listen targets. By default DoListen will track new listens and set them up immediately, if active.
-
template <typename FWD_TYPE>
Widget &ForwardAppend
(FWD_TYPE &&arg)¶ If an Append doesn’t work with current class, forward it to the parent and try there.
-
Widget &
SetInfo
(WidgetInfo *in_info)¶ Set the information associated with this widget.
-
WidgetInfo *
operator->
()¶ Internally, we can treat a Widget as a pointer to its WidgetInfo.
Protected Attributes
-
WidgetInfo *
info
¶ Information associated with this widget.
Protected Static Functions
-
static WidgetInfo *
Info
(const Widget &w)¶ Give derived classes the ability to access widget info.
-
template<>
-
class
WidgetInfo
¶ - #include <Widget.h>
Subclassed by emp::web::Button::ButtonInfo, emp::web::Canvas::CanvasInfo, emp::web::D3Visualization::D3VisualizationInfo, emp::web::FileInput::FileInputInfo, emp::web::Image::ImageInfo, emp::web::internal::DivInfo, emp::web::internal::TableInfo, emp::web::Selector::SelectorInfo, emp::web::Text::TextInfo, emp::web::TextArea::TextAreaInfo
Public Functions
-
WidgetInfo
(const std::string &in_id = "")¶ WidgetInfo cannot be built unless within derived class, so constructor is protected.
-
WidgetInfo
(const WidgetInfo&)¶ No copies of INFO allowed.
-
WidgetInfo &
operator=
(const WidgetInfo&)¶
-
virtual
~WidgetInfo
()¶
-
virtual bool
IsButtonInfo
() const¶
-
virtual bool
IsCanvasInfo
() const¶
-
virtual bool
IsImageInfo
() const¶
-
virtual bool
IsSelectorInfo
() const¶
-
virtual bool
IsDivInfo
() const¶
-
virtual bool
IsTableInfo
() const¶
-
virtual bool
IsTextInfo
() const¶
-
virtual bool
IsTextAreaInfo
() const¶
-
virtual bool
IsD3VisualiationInfo
() const¶
-
void
AddDependants
()¶
-
void
UpdateDependants
()¶
-
virtual void
DoActivate
(bool top_level = true)¶
-
virtual bool
AppendOK
() const¶
-
virtual void
PreventAppend
()¶
-
virtual void
TriggerJS
()¶
-
virtual void
ReplaceHTML
()¶
Public Members
-
int
ptr_count
¶ How many widgets are pointing to this info?
-
WidgetExtras
extras
¶ HTML attributes, CSS style, and listeners for web events.
-
WidgetInfo *
parent
¶ Which WidgetInfo is this one contained within?
-
-
class
-
class
A collection of extra details about HTML Widgets (attributes, style, listerns)
- 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
- 2015-2017
-
namespace
emp
If we are in emscripten, make sure to include the header.
This file contains extra analysis tools to use with systematics managers that have non-null DATA_TYPES.
- 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
- 2018
This file contains functions for adding additional data files to Worlds.
- 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
- 2018
-
namespace
web
-
struct
WidgetExtras
¶ - #include <WidgetExtras.h>
Subclassed by emp::web::internal::TableGroupInfo
Public Functions
-
void
Clear
()¶ Clear all of style, attributes, and listeners.
-
operator bool
() const¶ Have any details been set?
Public Members
-
Attributes
attr
¶ HTML Attributes about a cell.
-
void
-
struct
Other Tools¶
Alert¶
-
namespace
emp
¶ If we are in emscripten, make sure to include the header.
This file contains extra analysis tools to use with systematics managers that have non-null DATA_TYPES.
- 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
- 2018
This file contains functions for adding additional data files to Worlds.
- 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
- 2018
Functions
-
void
Alert
(const std::string &msg)¶ Send msg to cerr if in C++, or show msg in an alert box if compiled to Javascript Input can be any number of arguments of any types as long as the can be converted to strings with emp::to_string().
-
template <typename... TYPE_SET>
static voidCappedAlert
(size_t cap, TYPE_SET... inputs)¶ A version of Alert that will cap how many times it can go off.
-
struct
AlertObj
¶ - #include <alert.h>
An object that will automatically output a message during construction or destruction, usually for use in debugging to disentangle timings.
BitMatrix¶
A COL x ROW matrix of bits and provides easy indexing and manipulation.
- 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-2017
- Note
- Status: BETA
-
namespace
emp
¶ If we are in emscripten, make sure to include the header.
This file contains extra analysis tools to use with systematics managers that have non-null DATA_TYPES.
- 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
- 2018
This file contains functions for adding additional data files to Worlds.
- 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
- 2018
-
template <size_t COLS, size_t ROWS>
classBitMatrix
¶ - #include <BitMatrix.h>
A simple class to manage a COLS x ROWS matrix of bits.
Bits are translated to a bitset with 0 in the upper left and moving through bits from left to right and top to bottom. For example, the indecies in a 3x3 bit matrix would be organized as such:
0 1 2 3 4 5 6 7 8
Public Functions
-
template <size_t START_POS, size_t STEP_POS, size_t END_POS>
constexpr BitSet<COLS*ROWS>Mask
() const¶
-
BitMatrix
()¶
-
~BitMatrix
()¶
-
constexpr size_t
NumRows
() const¶ How many rows are in this matrix?
-
constexpr size_t
NumCols
() const¶ How many columns are in this matrix?
-
constexpr size_t
GetSize
() const¶ How many total cells are in this matrix?
-
bool
Any
() const¶
-
bool
None
() const¶
-
bool
All
() const¶
-
bool
Get
(size_t col, size_t row) const¶
-
bool
Get
(size_t id) const¶
-
void
Set
(size_t col, size_t row, bool val = true)¶
-
void
Set
(size_t id)¶
-
void
Unset
(size_t col, size_t row)¶
-
void
Unset
(size_t id)¶
-
void
Flip
(size_t col, size_t row)¶
-
void
Flip
(size_t id)¶
-
void
SetAll
()¶
-
void
SetCol
(size_t col)¶
-
void
SetRow
(size_t row)¶
-
void
Clear
()¶
-
void
ClearCol
(size_t col)¶
-
void
ClearRow
(size_t row)¶
-
size_t
CountOnes
() const¶
-
int
FindBit
() const¶
-
bool
IsConnected
() const¶
-
bool
Has2x2
() const¶
Public Static Functions
-
template <size_t COL_ID>
static const BitSet<COLS*ROWS> &MaskCol
()¶ Keep only a single column of values, reducing all others to zeros.
-
template <size_t ROW_ID>
static const BitSet<COLS*ROWS> &MaskRow
()¶ Keep only a single row of values, reducing all others to zeros.
-
static size_t
ToCol
(size_t id)¶ Identify which column a specific ID is part of.
-
static size_t
ToRow
(size_t id)¶ Identify which row a specific ID is part of.
-
static size_t
ToID
(size_t col, size_t row)¶ Identify the ID associated with a specified row and column.
-
template <size_t START_POS, size_t STEP_POS, size_t END_POS>
BitSet¶
A drop-in replacement for std::bitset, with additional bit magic features.
- 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-2017
- Note
- Status: RELEASE
- Note
- Like std::bitset, bit zero is on the right side. Unlike std::bitset, emp::BitSet gives access to bit fields for easy access to different sized chucnk of bits and implementation new bit-magic tricks.
Functions
-
namespace
emp
If we are in emscripten, make sure to include the header.
This file contains extra analysis tools to use with systematics managers that have non-null DATA_TYPES.
- 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
- 2018
This file contains functions for adding additional data files to Worlds.
- 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
- 2018
Functions
-
template <size_t NUM_BITS1, size_t NUM_BITS2>
BitSet<NUM_BITS1+NUM_BITS2>join
(const BitSet<NUM_BITS1> &in1, const BitSet<NUM_BITS2> &in2)¶
-
template <size_t NUM_BITS>
doubleSimpleMatchCoeff
(const BitSet<NUM_BITS> &in1, const BitSet<NUM_BITS> &in2)¶ Computes simple matching coefficient (https://en.wikipedia.org/wiki/Simple_matching_coefficient).
-
template <size_t NUM_BITS>
classBitSet
¶ - #include <BitSet.h>
A fixed-sized (but arbitrarily large) array of bits, and optimizes operations on those bits to be as fast as possible.
Public Functions
-
BitSet
()¶ Constructor: Assume all zeroes in set.
-
~BitSet
()¶ Destructor.
-
void
Randomize
(Random &random, const double p1 = 0.5)¶ Set all bits randomly, with a given probability of being a 1.
-
template <size_t NUM_BITS2>
BitSet &Import
(const BitSet<NUM_BITS2> &in_set)¶ Assign from a BitSet of a different size.
-
template <size_t NUM_BITS2>
BitSet<NUM_BITS2>Export
() const¶ Convert to a Bitset of a different size.
-
bool
operator<
(const BitSet &in_set) const¶ Compare two BitSet objects, based on the associated binary value.
-
bool
operator<=
(const BitSet &in_set) const¶ Compare two BitSet objects, based on the associated binary value.
-
bool
operator>
(const BitSet &in_set) const¶ Compare two BitSet objects, based on the associated binary value.
-
bool
operator>=
(const BitSet &in_set) const¶ Compare two BitSet objects, based on the associated binary value.
-
bool
Get
(size_t index) const¶ Retrieve the bit as a specified index.
-
void
Set
(size_t index, bool value)¶ Set the bit as a specified index.
-
uint8_t
GetByte
(size_t index) const¶ Get the full byte starting from the bit at a specified index.
-
void
SetByte
(size_t index, uint8_t value)¶ Set the full byte starting at the bit at the specified index.
-
uint32_t
GetUInt
(size_t index) const¶ Get the 32-bit unsigned int; index in in 32-bit jumps (i.e., this is a field ID not bit id)
-
void
SetUInt
(size_t index, uint32_t value)¶ Set the 32-bit unsigned int; index in in 32-bit jumps (i.e., this is a field ID not bit id)
-
uint32_t
GetUIntAtBit
(size_t index)¶ Get the full 32-bit unsigned int starting from the bit at a specified index.
-
template <size_t OUT_BITS>
uint32_tGetValueAtBit
(size_t index)¶ Get OUT_BITS bits starting from the bit at a specified index (max 32)
-
BitProxy
operator[]
(size_t index)¶ Index into a BitSet, returning a proxy that will allow bit assignment to work.
-
void
Clear
()¶ Set all bits to zero.
-
void
SetAll
()¶ Set all bits to one.
-
void
PrintArray
(std::ostream &out = std::cout) const¶ Print all bits from smallest to largest, as if this were an array, not a bit representation.
-
void
PrintOneIDs
(std::ostream &out = std::cout, char spacer = ' ') const¶ Print the locations of all one bits, using the provided spacer (default is a single space)
-
size_t
CountOnes_Sparse
() const¶ Count 1’s by looping through once for each bit equal to 1.
-
size_t
CountOnes_Mixed
() const¶ Count 1’s in semi-parallel; fastest for even 0’s & 1’s.
-
int
FindBit
() const¶ Return the index of the first one in the sequence; return -1 if no ones are available.
-
int
PopBit
()¶ Return index of first one in sequence (or -1 if no ones); change this position to zero.
-
int
FindBit
(const size_t start_pos) const¶ Return index of first one in sequence AFTER start_pos (or -1 if no ones)
-
emp::vector<size_t>
GetOnes
() const¶ Return a vector indicating the posistions of all ones in the BitSet.
-
BitSet
AND
(const BitSet &set2) const¶ Perform a Boolean AND with a second BitSet and return the result.
-
BitSet
OR
(const BitSet &set2) const¶ Perform a Boolean OR with a second BitSet and return the result.
-
BitSet
NAND
(const BitSet &set2) const¶ Perform a Boolean NAND with a second BitSet and return the result.
-
BitSet
NOR
(const BitSet &set2) const¶ Perform a Boolean NOR with a second BitSet and return the result.
-
BitSet
XOR
(const BitSet &set2) const¶ Perform a Boolean XOR with a second BitSet and return the result.
-
BitSet
EQU
(const BitSet &set2) const¶ Perform a Boolean EQU with a second BitSet and return the result.
-
BitSet &
NOT_SELF
()¶ Perform a Boolean NOT on this BitSet, store result here, and return this object.
-
BitSet &
AND_SELF
(const BitSet &set2)¶ Perform a Boolean AND with a second BitSet, store result here, and return this object.
-
BitSet &
OR_SELF
(const BitSet &set2)¶ Perform a Boolean OR with a second BitSet, store result here, and return this object.
-
BitSet &
NAND_SELF
(const BitSet &set2)¶ Perform a Boolean NAND with a second BitSet, store result here, and return this object.
-
BitSet &
NOR_SELF
(const BitSet &set2)¶ Perform a Boolean NOR with a second BitSet, store result here, and return this object.
-
BitSet &
XOR_SELF
(const BitSet &set2)¶ Perform a Boolean XOR with a second BitSet, store result here, and return this object.
-
BitSet &
EQU_SELF
(const BitSet &set2)¶ Perform a Boolean EQU with a second BitSet, store result here, and return this object.
-
BitSet
SHIFT
(const int shift_size) const¶ Positive shifts go left and negative go right (0 does nothing); return result.
-
BitSet &
SHIFT_SELF
(const int shift_size)¶ Positive shifts go left and negative go right; store result here, and return this object.
-
bool
all
() const¶ Function to allow drop-in replacement with std::bitset.
-
bool
any
() const¶ Function to allow drop-in replacement with std::bitset.
-
bool
none
() const¶ Function to allow drop-in replacement with std::bitset.
-
size_t
count
() const¶ Function to allow drop-in replacement with std::bitset.
Public Static Functions
-
static constexpr size_t
size
()¶ Function to allow drop-in replacement with std::bitset.
Private Functions
-
void
Copy
(const uint32_t in_set[NUM_FIELDS])¶
-
void
ShiftLeft
(const uint32_t shift_size)¶ Helper: call SHIFT with positive number instead.
-
void
ShiftRight
(const uint32_t shift_size)¶ Helper for calling SHIFT with negative number.
Private Members
Private Static Functions
-
static size_t
FieldID
(const size_t index)¶
-
static size_t
FieldPos
(const size_t index)¶
-
static size_t
Byte2Field
(const size_t index)¶
-
static size_t
Byte2FieldPos
(const size_t index)¶
Private Static Attributes
-
const uint32_t
NUM_FIELDS
= 1 + ((NUM_BITS - 1) >> 5)¶ Fields hold bits in groups of 32 (as uint32_t); how many feilds do we need?
-
const uint32_t
LAST_BIT
= NUM_BITS & 31¶ End position of the stored bits in the last field; 0 if perfect fit.
-
const uint32_t
NUM_BYTES
= 1 + ((NUM_BITS - 1) >> 3)¶ How many total bytes are needed to represent these bits? (rounded up to full bytes)
Friends
-
friend
emp::BitProxy
-
BitSet Utilities¶
A set of simple functions to manipulate bitsets.
- 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-2017
- Note
- Status: BETA
-
namespace
emp
If we are in emscripten, make sure to include the header.
This file contains extra analysis tools to use with systematics managers that have non-null DATA_TYPES.
- 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
- 2018
This file contains functions for adding additional data files to Worlds.
- 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
- 2018
Functions
-
template <int NUM_BITS>
constexpr uint32_tUIntMaskFirst
()¶ Create a series of a specified number of ones (at compile time) in a uint.
-
template <>
template<>
constexpr uint32_tUIntMaskFirst
<0>()¶ Create an empty bit mask (all zeros)
-
constexpr size_t
count_bits
(uint64_t val)¶ Count the number of bits in a 64-bit unsigned integer.
-
constexpr size_t
count_bits
(uint32_t val)¶ Count the number of bits in a 32-bit unsigned integer.
-
constexpr size_t
find_bit
(const uint64_t &val)¶ Return the position of the first one bit (in a 64-bit unsigned int)
-
constexpr size_t
find_bit
(const uint32_t &val)¶ Return the position of the first one bit (in a 32-bit unsigned int)
Variables
-
constexpr size_t
ByteCount
[256]= {
0, 1, 1, 2, 1, 2, 2, 3, 1, 2, 2, 3, 2, 3, 3, 4, 1, 2, 2, 3, 2, 3, 3, 4, 2, 3, 3, 4, 3, 4, 4, 5,
1, 2, 2, 3, 2, 3, 3, 4, 2, 3, 3, 4, 3, 4, 4, 5, 2, 3, 3, 4, 3, 4, 4, 5, 3, 4, 4, 5, 4, 5, 5, 6,
1, 2, 2, 3, 2, 3, 3, 4, 2, 3, 3, 4, 3, 4, 4, 5, 2, 3, 3, 4, 3, 4, 4, 5, 3, 4, 4, 5, 4, 5, 5, 6,
2, 3, 3, 4, 3, 4, 4, 5, 3, 4, 4, 5, 4, 5, 5, 6, 3, 4, 4, 5, 4, 5, 5, 6, 4, 5, 5, 6, 5, 6, 6, 7,
1, 2, 2, 3, 2, 3, 3, 4, 2, 3, 3, 4, 3, 4, 4, 5, 2, 3, 3, 4, 3, 4, 4, 5, 3, 4, 4, 5, 4, 5, 5, 6,
2, 3, 3, 4, 3, 4, 4, 5, 3, 4, 4, 5, 4, 5, 5, 6, 3, 4, 4, 5, 4, 5, 5, 6, 4, 5, 5, 6, 5, 6, 6, 7,
2, 3, 3, 4, 3, 4, 4, 5, 3, 4, 4, 5, 4, 5, 5, 6, 3, 4, 4, 5, 4, 5, 5, 6, 4, 5, 5, 6, 5, 6, 6, 7,
3, 4, 4, 5, 4, 5, 5, 6, 4, 5, 5, 6, 5, 6, 6, 7, 4, 5, 5, 6, 5, 6, 6, 7, 5, 6, 6, 7, 6, 7, 7, 8
}
¶ How many bits are set to one in each possible byte?
BitVector¶
A drop-in replacement for std::vector<bool>, with additional bitwise logic features.
- 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-2017
- Note
- Status: RELEASE
- Note
- This class is 15-20% slower than emp::BitSet, but more flexible & run-time configurable.
-
template <>
template<>
structhash
<emp::BitVector>¶ - #include <BitVector.h>
Hash function to allow BitVector to be used with maps and sets (must be in std).
-
namespace
emp
If we are in emscripten, make sure to include the header.
This file contains extra analysis tools to use with systematics managers that have non-null DATA_TYPES.
- 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
- 2018
This file contains functions for adding additional data files to Worlds.
- 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
- 2018
-
class
BitVector
¶ - #include <BitVector.h>
A drop-in replacement for std::vector<bool>, but with extra bitwise logic features.
This class stores an arbirary number of bits in a set of “fields” (either 32-bit or 64-bit, depending on which should be faster.) Individual bits can be extracted, -or- bitwise logic (or bit magic) can be used on the groups of bits,
Public Functions
-
BitVector
(size_t in_num_bits = 0, bool init_val = false)¶ Build a new BitVector with specified bit count (default 0) and initialization (default 0)
-
~BitVector
()¶ Destructor.
-
bool
operator<
(const BitVector &in_set) const¶ Compare the would-be numerical values of two bit vectors.
-
bool
operator<=
(const BitVector &in_set) const¶ Compare the would-be numerical values of two bit vectors.
-
bool
operator>
(const BitVector &in_set) const¶ Compare the would-be numerical values of two bit vectors.
-
bool
operator>=
(const BitVector &in_set) const¶ Compare the would-be numerical values of two bit vectors.
-
size_t
GetSize
() const¶ How many bits do we currently have?
-
bool
Get
(size_t index) const¶ Retrive the bit value from the specified index.
-
void
Set
(size_t index, bool value = true)¶ Update the bit value at the specified index.
-
uint8_t
GetByte
(size_t index) const¶ Retrive the byte at the specified byte index.
-
void
SetByte
(size_t index, uint8_t value)¶ Update the byte at the specified byte index.
-
uint32_t
GetUInt
(size_t index) const¶ Retrive the 32-bit uint from the specifeid uint index.
-
void
SetUInt
(size_t index, uint32_t value)¶ Update the 32-bit uint at the specified uint index.
-
uint32_t
GetUIntAtBit
(size_t index)¶ Retrive the 32-bit uint at the specified BIT index.
-
template <size_t OUT_BITS>
field_tGetValueAtBit
(size_t index)¶ Retrieve the specified number of bits (stored in the field type) at the target bit index.
-
bool
Any
() const¶ Return true if ANY bits are set to 1, otherwise return false.
-
bool
None
() const¶ Return true if NO bits are set to 1, otherwise return false.
-
bool
All
() const¶ Return true if ALL bits are set to 1, otherwise return false.
-
operator bool
() const¶ Casting a bit array to bool identifies if ANY bits are set to 1.
-
bool
operator[]
(size_t index) const¶ Const index operator return the bit at the specified position.
-
BitProxy
operator[]
(size_t index)¶ Index operator return a proxy to the bit at the specified position so it can be an lvalue.
-
void
Clear
()¶ Set all bits to 0.
-
void
SetAll
()¶ Set all bits to 1.
-
void
Print
(std::ostream &out = std::cout) const¶ Regular print function (from most significant bit to least)
-
void
PrintFields
(std::ostream &out = std::cout, const std::string spacer = " ") const¶ Print a space between each field (or other provided spacer)
-
void
PrintOneIDs
(std::ostream &out = std::cout, std::string spacer = " ") const¶ Print the positions of all one bits, spaces are the default separator.
-
size_t
CountOnes_Sparse
() const¶ Count 1’s by looping through once for each bit equal to 1.
-
size_t
CountOnes_Mixed
() const¶ Count 1’s in semi-parallel; fastest for even 0’s & 1’s.
-
int
FindBit
() const¶ Return the position of the first one; return -1 if no ones in vector.
-
int
PopBit
()¶ Return the position of the first one and change it to a zero. Return -1 if no ones.
-
int
FindBit
(const size_t start_pos) const¶ Return the position of the first one after start_pos; return -1 if no ones in vector. You can loop through all 1-bit positions of a BitVector “bv” with:
for (int pos = bv.FindBit(); pos >= 0; pos = bv.FindBit(pos+1)) { … }
-
BitVector
AND
(const BitVector &set2) const¶ Perform a Boolean AND on this BitVector and return the result.
-
BitVector
OR
(const BitVector &set2) const¶ Perform a Boolean OR on this BitVector and return the result.
-
BitVector
NAND
(const BitVector &set2) const¶ Perform a Boolean NAND on this BitVector and return the result.
-
BitVector
NOR
(const BitVector &set2) const¶ Perform a Boolean NOR on this BitVector and return the result.
-
BitVector
XOR
(const BitVector &set2) const¶ Perform a Boolean XOR on this BitVector and return the result.
-
BitVector
EQU
(const BitVector &set2) const¶ Perform a Boolean EQU on this BitVector and return the result.
-
BitVector &
NOT_SELF
()¶ Perform a Boolean NOT with this BitVector, store result here, and return this object.
-
BitVector &
AND_SELF
(const BitVector &set2)¶ Perform a Boolean AND with this BitVector, store result here, and return this object.
-
BitVector &
OR_SELF
(const BitVector &set2)¶ Perform a Boolean OR with this BitVector, store result here, and return this object.
-
BitVector &
NAND_SELF
(const BitVector &set2)¶ Perform a Boolean NAND with this BitVector, store result here, and return this object.
-
BitVector &
NOR_SELF
(const BitVector &set2)¶ Perform a Boolean NOR with this BitVector, store result here, and return this object.
-
BitVector &
XOR_SELF
(const BitVector &set2)¶ Perform a Boolean XOR with this BitVector, store result here, and return this object.
-
BitVector &
EQU_SELF
(const BitVector &set2)¶ Perform a Boolean EQU with this BitVector, store result here, and return this object.
-
BitVector
SHIFT
(const int shift_size) const¶ Positive shifts go left and negative go right (0 does nothing); return result.
-
BitVector &
SHIFT_SELF
(const int shift_size)¶ Positive shifts go left and negative go right; store result here, and return this object.
-
size_t
size
() const¶ Function to allow drop-in replacement with std::vector<bool>.
-
bool
all
() const¶ Function to allow drop-in replacement with std::vector<bool>.
-
bool
any
() const¶ Function to allow drop-in replacement with std::vector<bool>.
-
bool
none
() const¶ Function to allow drop-in replacement with std::vector<bool>.
-
size_t
count
() const¶ Function to allow drop-in replacement with std::vector<bool>.
Private Types
-
using
field_t
= uint64_t¶ Field sizes are 64 bits in native.
Private Functions
-
size_t
LastBitID
() const¶ End position of the stored bits in the last field; 0 if perfect fit.
-
size_t
NumFields
() const¶ How many feilds do we need?
-
size_t
NumBytes
() const¶ How many bytes are used in the current vector (round up to whole bytes.)
-
size_t
NumSizeFields
() const¶ How many fields would we need if they had the same number of bits as size_t?
-
void
RawCopy
(const Ptr<field_t> in_set)¶ Assume that the size of the bit_set has already been adjusted to be the size of the one being copied and only the fields need to be copied over.
-
void
ShiftLeft
(const size_t shift_size)¶ Helper: call SHIFT with positive number.
-
void
ShiftRight
(const size_t shift_size)¶ Helper for calling SHIFT with negative number.
Private Members
-
size_t
num_bits
¶ How many total bits are we using?
Private Static Functions
-
static constexpr size_t
FieldID
(const size_t index)¶ Identify the field that a specified bit is in.
-
static constexpr size_t
FieldPos
(const size_t index)¶ Identify the position in a field where a specified bit is.
-
static constexpr size_t
Byte2Field
(const size_t index)¶ Identify which field a specified byte position would be in.
Private Static Attributes
-
constexpr size_t
FIELD_BITS
= sizeof(field_t)*8¶ How many bits are in a field?
-
struct
BitProxy
¶ BitProxy lets us use operator[] on with BitVector as an lvalue.
Public Functions
-
BitProxy &
operator=
(bool b)¶ Assignment operator to the bit associated with this proxy (as an lvalue).
-
operator bool
() const¶ Conversion of this proxy to Boolean (as an rvalue)
-
BitProxy &
operator&=
(bool b)¶ Compound assignement operator AND using BitProxy as lvalue.
- Note
- Implemented in BitProxy since it needs to work, but may not be efficient.
-
BitProxy &
operator|=
(bool b)¶ Compound assignement operator OR using BitProxy as lvalue.
- Note
- Implemented in BitProxy since it needs to work, but may not be efficient.
-
BitProxy &
operator^=
(bool b)¶ Compound assignement operator XOR using BitProxy as lvalue.
- Note
- Implemented in BitProxy since it needs to work, but may not be efficient.
-
BitProxy &
operator+=
(bool b)¶ Compound assignement operator PLUS using BitProxy as lvalue.
- Note
- Implemented in BitProxy since it needs to work, but may not be efficient.
-
BitProxy &
operator-=
(bool b)¶ Compound assignement operator MINUS using BitProxy as lvalue.
- Note
- Implemented in BitProxy since it needs to work, but may not be efficient.
-
BitProxy &
-
-
namespace
std
¶ Functions
Cache¶
similar to an std::unordered_map, but all lookups come with a function to generate the result should the lookup fail.
- 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
-
namespace
emp
If we are in emscripten, make sure to include the header.
This file contains extra analysis tools to use with systematics managers that have non-null DATA_TYPES.
- 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
- 2018
This file contains functions for adding additional data files to Worlds.
- 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
- 2018
-
template <class KEY, class T, class HASH = std::hash<KEY>, class PRED = std::equal_to<KEY>, class ALLOC = std::allocator< std::pair<const KEY,T> >>
classCache
¶ - #include <Cache.h>
Public Types
-
template<>
usingkey_type
= KEY¶ Type we are using to look up values.
-
template<>
usingmapped_type
= T¶ Contents of the value we look up.
-
template<>
usinghasher
= HASH¶ Hash method to use.
-
template<>
usingkey_equal
= PRED¶ Function to test if two values are identical.
-
template<>
usingallocator_type
= ALLOC¶ Function to allocate new space.
Public Functions
-
Cache
()¶
-
size_t
size
() const¶ How many entries are stored in the cache?
-
bool
Has
(const KEY &k) const¶ Determine if a specific key is already in the cache.
-
void
Clear
()¶ Erase contents of cache.
-
void
Erase
(const KEY &k)¶ Erase a specific entry from cache.
-
template<>
Combinations¶
Tools to step through combinations of items.
Step through all combinations of size K from a set of N values. For ComboIDs just return the indecies (the specific of the container don’t matter). Other versions will directly wrapper containers.
- 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
- 2017
-
namespace
emp
If we are in emscripten, make sure to include the header.
This file contains extra analysis tools to use with systematics managers that have non-null DATA_TYPES.
- 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
- 2018
This file contains functions for adding additional data files to Worlds.
- 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
- 2018
-
class
ComboIDs
¶ - #include <combos.h>
Public Functions
-
ComboIDs
(size_t in_max, size_t combo_size)¶
-
~ComboIDs
()¶
-
size_t
GetComboSize
() const¶
-
size_t
GetNumCombos
() const¶
-
size_t &
operator[]
(const size_t index)¶
-
const size_t &
operator[]
(const size_t index) const¶
-
bool
NextCombo
()¶
-
void
ResizeCombos
(size_t new_size)¶
-
size_t
size
()¶
Private Static Functions
-
size_t
CountCombos
(size_t max_count, size_t combo_size)¶
-
Constants¶
Commonly used constant values.
- 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
- 2015-2017
- Note
- Status: RELEASE
-
namespace
emp
If we are in emscripten, make sure to include the header.
This file contains extra analysis tools to use with systematics managers that have non-null DATA_TYPES.
- 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
- 2018
This file contains functions for adding additional data files to Worlds.
- 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
- 2018
Functions
-
template <typename T>
constexpr TMaxValue
()¶ Determine the maximum value for any type.
-
template <typename T>
constexpr doubleInterpolateTable
(T &&table, double pos, double tsize)¶ The following function takes a table and a position [0.0, 1.0) and intepolates a value.
Variables
-
constexpr const double
E
= 2.71828¶ e
-
constexpr const double
PHI
= 1.61803398874¶ Golden ratio.
-
constexpr const double
PI
= 3.14159265358979¶ pi
-
constexpr const double
SQRT2
= 1.41421356237310¶ sqrt(2)
-
constexpr const uint32_t
MAX_BYTE
= 255¶ (2^8 - 1)
-
constexpr const uint32_t
MAX_2BYTE
= 65535¶ (2^16 - 1)
-
constexpr const uint32_t
MAX_WORD
= 65535¶ (2^16 - 1)
-
constexpr const uint32_t
MAX_3BYTE
= 16777215¶ (2^24 - 1)
-
constexpr const uint32_t
MAX_UINT
= 4294967295¶ (2^32 - 1)
-
constexpr const uint32_t
MAX_4BYTE
= 4294967295¶ (2^32 - 1)
-
constexpr const int32_t
MIN_INT
= -2147483648¶ (- 2^31)
-
constexpr const double
log2_chart_1_2
[]¶ Large table to log base-2 results.
-
constexpr const double
pow2_chart_bits
[]=
{
1.4142135623730951, 1.1892071150027210, 1.0905077326652577, 1.0442737824274138,
1.0218971486541166, 1.0108892860517005, 1.0054299011128027, 1.0027112750502025,
1.0013547198921082, 1.0006771306930664, 1.0003385080526823, 1.0001692397053021,
1.0000846162726944, 1.0000423072413958, 1.0000211533969647, 1.0000105766425498,
1.0000052883072919, 1.0000026441501502, 1.0000013220742012, 1.0000006610368821,
1.0000003305183864, 1.0000001652591795, 1.0000000826295863, 1.0000000413147923,
1.0000000206573960, 1.0000000103286979, 1.0000000051643489, 1.0000000025821745,
1.0000000012910872, 1.0000000006455436, 1.0000000003227718, 1.0000000001613858
}
¶ Table to provide results of Pow2 for values of bits (0.1, 0.01, 0.001, etc, in binary)
-
constexpr const double
pow2_chart_0_1
[]¶ Table to provide results of Pow2 from 0 to 1.
Debugging Tools¶
Basic tools for use in developing high-assurance 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
- 2015-2017
- Note
- Status: BETA
Defines
-
BlockRelease
(BLOCK)¶ BlockRelease() will halt compilation if NDEBUG is on. It is useful to include alongside debug print code that you want to remember to remove when you are done debugging.
-
namespace
emp
If we are in emscripten, make sure to include the header.
This file contains extra analysis tools to use with systematics managers that have non-null DATA_TYPES.
- 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
- 2018
This file contains functions for adding additional data files to Worlds.
- 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
- 2018
Functions
-
static void
Depricated
(const std::string &name, const std::string &desc = "")¶ Depricated() prints its contents exactly once to notify a user of a depricated function.
Deterministic Finite Automata¶
A Deterministic Finite Automata simulator.
- 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-2017
- Note
- Status: BETA
-
namespace
emp
If we are in emscripten, make sure to include the header.
This file contains extra analysis tools to use with systematics managers that have non-null DATA_TYPES.
- 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
- 2018
This file contains functions for adding additional data files to Worlds.
- 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
- 2018
Typedefs
-
using
emp::DFA = typedef tDFA<128, uint8_t>
Setup DFA to be a simple tDFA with the basic character set for symbols.
-
template <int NUM_SYMBOLS = 128, typename STOP_TYPE = uint8_t>
classtDFA
¶ - #include <DFA.h>
Public Types
-
template<>
usingstop_t
= STOP_TYPE¶
Public Functions
-
tDFA
(size_t num_states = 0)¶
-
~tDFA
()¶
-
size_t
GetSize
() const¶ How many states is this DFA using?
-
void
Resize
(size_t new_size)¶ Add Additional empty states.
-
const emp::array<int, NUM_SYMBOLS> &
GetTransitions
(size_t from) const¶ Return an array of all transitions associated with a specified state.
-
void
SetTransition
(size_t from, size_t to, size_t sym)¶ Add a specific transition associated with an input symbol.
-
void
SetStop
(size_t state, stop_t stop_val = 1)¶ Set the stop value (no matter what it currently is)
-
void
AddStop
(size_t state, stop_t stop_val = 1)¶ Set the stop value only if it’s higher than the current stop value.
-
stop_t
GetStop
(int state) const¶ Get the stop value associated with a state.
-
bool
IsActive
(int state) const¶ Test if a state is still valid.
-
bool
IsStop
(int state) const¶ Test if a state has a stop.
-
stop_t
GetStop
(size_t state) const¶
-
bool
IsActive
(size_t state) const¶
-
bool
IsStop
(size_t state) const¶
-
int
Next
(int state, size_t sym) const¶ Return the new state after a symbol occurs.
-
template<>
Dynamic Strings¶
A string handler where sections update dynamically based on functions.
- 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-2017
- Note
- Status: BETA
-
namespace
emp
If we are in emscripten, make sure to include the header.
This file contains extra analysis tools to use with systematics managers that have non-null DATA_TYPES.
- 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
- 2018
This file contains functions for adding additional data files to Worlds.
- 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
- 2018
-
class
DynamicString
¶ - #include <DynamicString.h>
A string handler where some sections can be fixed strings, while others update dynamically based on functions.
Public Functions
-
DynamicString
()¶
-
DynamicString
(const DynamicString&)¶
-
size_t
GetSize
() const¶ How many string components (funcations or continuous substrings) are in this DynamicString?
-
std::string
operator[]
(size_t id) const¶ Index in to a specific component (not a specific character, since size is variable) and return it’s associated string.
-
const value_t &
GetFunction
(size_t id) const¶ Index in to a specific component (not a specific character, since size is variable) and return it’s associated function.
-
DynamicString &
Clear
()¶ Remove all contents on this DynamicString.
-
DynamicString &
Set
(size_t id, const value_t &in_fun)¶ Set the value of a specified component to the provided function.
-
DynamicString &
Set
(size_t id, const std::string &in_text)¶ Set the value of a specified component to the provided std::string text.
-
DynamicString &
Append
(const value_t &in_fun)¶ Add a new function to the end of the DynamicString.
-
DynamicString &
Append
(const std::string &in_text)¶ Add new std::string text to the end of the DynamicString.
-
template <typename IN_TYPE>
DynamicString &operator<<
(IN_TYPE &&_in)¶ Allow operator<< to append to the back of a DynamicString.
-
Errors¶
Warning
doxygenfile: Cannot find file “tools/errors.h
In-memory Files¶
The File object maintains a simple, in-memory file.
- 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
- 2018
- Note
- Status: BETA
-
namespace
emp
If we are in emscripten, make sure to include the header.
This file contains extra analysis tools to use with systematics managers that have non-null DATA_TYPES.
- 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
- 2018
This file contains functions for adding additional data files to Worlds.
- 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
- 2018
-
class
File
¶ - #include <File.h>
A class to maintin files for loading, writing, storing, and easy access to components.
Public Functions
-
File
()¶
-
~File
()¶
-
auto
begin
() const¶ Return const iterator to beginning of file.
-
auto
end
() const¶ Return const iterator to end of file.
-
auto
begin
()¶ Return iterator to beginning of file.
-
auto
end
()¶ Return iterator to end of file.
-
size_t
GetNumLines
() const¶ How many lines are in this file?
-
File &
Append
(const emp::vector<std::string> &in_lines)¶ Append a vector of lines to the end of the file.
-
template <typename T>
autooperator<<
(T &&in)¶ Insert formatted data into file This is exactly the same as operator+=
-
File &
Load
(const std::string &filename)¶ Load a file from disk using the provided name. If file does not exist, this is a nop
-
std::set<std::string>
AsSet
() const¶ Convert this file into an std::set of lines (loses line ordering).
-
File &
Apply
(const std::function<void(std::string&)> &fun)¶ Apply a string manipulation function to all lines in the file.
-
File &
KeepIf
(const std::function<bool(const std::string&)> &fun)¶ Purge functions that don’t meet a certain criterion.
-
File &
CompressWhitespace
()¶ Any time multiple whitespaces are next to each other, collapse to a single WS char. Prefer ‘
’ if in whitespace collapsed, otherwise use ‘ ‘.
-
Flex Functions¶
Based on std::function, but holds default parameter values for calls with fewer args.
A collection of broadly-useful functions (that don’t fit elsewhere)
- 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-2017
- Note
- Status: ALPHA
- 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 (though new functions are added frequently)
-
namespace
emp
If we are in emscripten, make sure to include the header.
This file contains extra analysis tools to use with systematics managers that have non-null DATA_TYPES.
- 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
- 2018
This file contains functions for adding additional data files to Worlds.
- 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
- 2018
-
template <class R, class... ARGS>
template<>
classflex_function
<R(ARGS...)>¶ - #include <flex_function.h>
A functon class that is almost identical to std::function, but is provided with default values for all parameters so that it can be called with fewer arguments, as needed.
Public Functions
-
template <typename T>
flex_function
(T &&fun_info)¶
-
flex_function
(const this_t&)¶
-
flex_function
(this_t&&)¶
-
flex_function
()¶
-
this_t &
operator=
(const this_t&)¶
-
this_t &
operator=
(this_t&&)¶
-
this_t &
operator=
(const fun_t &_f)¶
-
this_t &
operator=
(fun_t &&_f)¶
-
template <typename T>
this_t &operator=
(T &&arg)¶
-
template <int ID>
voidSetDefault
(pack_id<ID, ARGS...> &in_default)¶ Set the default value for a specific parameter.
-
void
SetDefaults
(ARGS... args)¶ Set the default values for all parameters.
-
return_t
operator()
(ARGS... k) const¶ Allow the function to be called with all args.
-
template <class... IN_ARGS>
return_toperator()
(IN_ARGS&&... k) const¶ All the function to be called with a subset of arguments (and the rest set to defaults)
-
operator bool
() const¶ Determine whether this function has been set.
Public Static Attributes
-
constexpr int
num_args
= sizeof...(ARGS)¶
-
template <typename T>
Functions¶
-
namespace
emp
If we are in emscripten, make sure to include the header.
This file contains extra analysis tools to use with systematics managers that have non-null DATA_TYPES.
- 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
- 2018
This file contains functions for adding additional data files to Worlds.
- 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
- 2018
Functions
-
static double
TimeFun
(std::function<void()> test_fun)¶ A function timer that takes a functor an identifies how long it takes to complete when run.
-
bool
Toggle
(bool &in_bool)¶ Toggle an input bool.
-
constexpr bool
AllTrue
()¶ Combine bools to AND them all together.
-
template <typename... Ts>
boolAllTrue
(bool result, Ts... OTHER)¶
-
constexpr bool
AnyTrue
()¶ Combine bools to OR them all together.
-
template <typename... Ts>
boolAnyTrue
(bool result, Ts... OTHER)¶
-
template <typename T>
static emp::vector<T>BuildRange
(T min, T max, T step = 1)¶ Build a vector with a range of values from min to max at the provided step size.
-
template <typename T, size_t N>
constexpr size_tGetSize
(T (&)[N])¶ Determine the size of a built-in array.
-
static size_t
UniqueVal
()¶ A function that will always return a unique value (and trip an assert if it can’t…)
Function Sets¶
Setup a collection of functions, all with the same signature, that can be run as a group.
- 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-2017
- Note
- Status: BETA
-
namespace
emp
If we are in emscripten, make sure to include the header.
This file contains extra analysis tools to use with systematics managers that have non-null DATA_TYPES.
- 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
- 2018
This file contains functions for adding additional data files to Worlds.
- 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
- 2018
-
template <typename RETURN_T, typename... ARGS>
template<>
classFunctionSet
<RETURN_T(ARGS...)> : public emp::vector<std::function<RETURN_T(ARGS...)>>¶ - #include <FunctionSet.h>
A vector of functions that can all be triggered at onece; results can either be returned in a vector or post-processed in a function (such as max, min, etc.) Derived from emp::vector, hence with all of the same methods as vector.
Public Types
-
template<>
usingreturn_t
= RETURN_T¶
Public Functions
-
FunctionSet
()¶
-
~FunctionSet
()¶
-
size_t
GetSize
() const¶ How many functions are in this FunctionSet?
-
void
Add
(const value_type &in_fun)¶ Add a new funtion to this FunctionSet.
-
void
Remove
(size_t pos)¶ Remove the function at a specified position.
-
const emp::vector<RETURN_T> &
Run
(ARGS... args) const¶ Run all functions and return a vector of all results.
-
RETURN_T
Run
(ARGS... args, std::function<RETURN_T(RETURN_T, RETURN_T)> comp_fun, RETURN_T default_val = 0, ) const¶ If you want to provide a filter function, you can retrieve a specific return value. The filter should take in two return values and indicate which is “better”.
-
RETURN_T
FindMax
(ARGS... args, RETURN_T default_val = 0) const¶ Run all functions and return the highest value.
-
RETURN_T
FindMin
(ARGS... args, RETURN_T default_val = 0) const¶ Run all functions and return the lowest value.
-
RETURN_T
FindSum
(ARGS... args, RETURN_T default_val = 0) const¶ Run all functions and return the total value.
-
RETURN_T
FindProduct
(ARGS... args, RETURN_T default_val = 1) const¶ Run all functions and return a product of all values.
-
template<>
Generic Functions¶
Warning
doxygenfile: Cannot find file “tools/GenericFunctions.h
Graph Utilities¶
This file provides a number of tools for manipulating graphs.
- 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
- 2017
- Note
- Status: BETA
-
namespace
emp
If we are in emscripten, make sure to include the header.
This file contains extra analysis tools to use with systematics managers that have non-null DATA_TYPES.
- 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
- 2018
This file contains functions for adding additional data files to Worlds.
- 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
- 2018
Functions
-
Graph
shuffle_graph
(const Graph &in_graph, Random &random)¶ Take an existing graph, and build a new one that is isomorphic to it, but with randomized vertex IDs.
-
Graph
build_graph_ring
(size_t v_count, Random &random)¶ Construct a graph where all vertics are degree two and form a single ring.
-
Graph
build_graph_tree
(size_t v_count, Random &random)¶ Construct a random tree graph (new vertices are repeatedly attached to a random position in a treee as it is constructed.)
-
Graph
build_graph_random
(size_t v_count, size_t e_count, Random &random, bool connected = true)¶ Construct a random, graph with the specified number of vertices and edges. If connected is set, start by building a tree. Then connect random (unconnected) pairs of vertices until the proper number of edges are included.
-
Graph
build_graph_grid
(size_t width, size_t height, Random &random, double prob_use = 1.0)¶ Construct a graph with width x height vertices setup into a grid structure.
-
Graph
build_graph_clique_set
(size_t clique_size, size_t clique_count, Random &random, double extra_prob = 0.5)¶ Build a set of cliques (such that one member of each can be part of an independent set) and then links them together
-
Graph
build_graph_dag
(size_t v_count, size_t e_count, Random &random, bool connected = true)¶ Construct a random, graph with the specified number of vertices and edges. If connected is set, start by building a tree. Then connect random (unconnected) pairs of vertices until the proper number of edges are included.
-
WeightedGraph
build_weighted_graph_tree
(size_t v_count, size_t min_weight, size_t max_weight, Random &random)¶ Construct a random WEIGHTED tree graph (new vertices are repeatedly attached to a random position in a treee as it is constructed.)
-
WeightedGraph
build_weighted_graph_random
(size_t v_count, size_t e_count, size_t min_weight, size_t max_weight, Random &random, bool connected = true)¶ Construct a random, WEIGHTED graph with the specified number of vertices, edges, and range of edge weights. If connected is set, start by building a tree. Then connect random (unconnected) pairs of vertices until the proper number of edges are included.
-
Graph
load_graph_sym
(std::istream &is, bool sub1 = false)¶ Helper function for loading symetric graphs from an input stream. sub1 indicates that verticies are numbered 1 to N instead of 0 to N-1.
-
Graph
load_graph_sym
(std::string filename, bool sub1 = false)¶ Load a graph with a specified filename.
Graphs¶
A simple, fast class for managing verticies (nodes) and edges.
- 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
- 2017
- Note
- Status: BETA
-
namespace
emp
If we are in emscripten, make sure to include the header.
This file contains extra analysis tools to use with systematics managers that have non-null DATA_TYPES.
- 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
- 2018
This file contains functions for adding additional data files to Worlds.
- 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
- 2018
-
class
Graph
¶ - #include <Graph.h>
A graph class that maintains a set of vertices (nodes) and edges (connecting pairs of nodes)
Subclassed by emp::WeightedGraph
Public Functions
-
Graph
(size_t num_nodes = 0)¶ Construct a new graph with the specified number of nodes.
-
~Graph
()¶
-
size_t
GetSize
() const¶ Get number of vertices in this graph.
-
size_t
GetEdgeCount
() const¶ Get the total number of edges in this graph.
-
void
Resize
(size_t new_size)¶ Change the number of vertices in this graph.
-
const BitVector &
GetEdgeSet
(size_t id) const¶ Get the set of nodes that a specified node is connected to.
-
size_t
GetDegree
(size_t id) const¶ Get the degree of a specified node.
-
size_t
GetMaskedDegree
(size_t id, const BitVector &mask) const¶ Get how many of a set of nodes that a specified node is connected to.
-
bool
HasEdge
(size_t from, size_t to) const¶ Determine if a specific edge is included in this graph.
-
void
AddEdge
(size_t from, size_t to)¶ Add a specified edge into this graph.
-
void
RemoveEdge
(size_t from, size_t to)¶ Remove a specified edge from this graph.
-
void
SetEdge
(size_t from, size_t to, bool val)¶ Set the status of a specified edge as to whether or not it should be in the graph.
-
bool
HasEdgePair
(size_t from, size_t to) const¶ Determine if edges exist in both directions between a pair of vertices.
-
void
AddEdgePair
(size_t from, size_t to)¶ Add a pair of edges between two vertieces (in both directions)
-
void
RemoveEdgePair
(size_t from, size_t to)¶ Remove edges in both directions between a pair of vertices.
-
void
SetEdgePairs
(size_t from, size_t to, bool val)¶ Set the status as to whether a pair of edges (in both direction) exist.
-
class
Node
¶ - #include <Graph.h>
Information about nodes within a graph.
Public Functions
-
Node
(size_t num_nodes)¶ What other node IDs is this one connected to?
-
~Node
()¶
-
bool
HasEdge
(size_t to) const¶ Is this node connect to a specific other node?
-
void
AddEdge
(size_t to)¶ Add a connection between this node and another.
-
void
RemoveEdge
(size_t to)¶ Remove the connection (if there is one) between this node and another one.
-
void
SetEdge
(size_t to, bool val)¶ Set whether a connection to another specific node should exist or not.
-
const BitVector &
GetEdgeSet
() const¶ Get a BitVector representing which nodes this one is connected to.
-
void
Resize
(size_t new_size)¶ Change the number of potential node connections that we are tracking.
-
void
Clear
()¶ Remove all edges from this node.
-
size_t
GetDegree
() const¶ Identify how many other nodes this one is connected to.
-
-
-
class
WeightedGraph
: public emp::Graph¶ - #include <Graph.h>
Public Functions
-
WeightedGraph
(size_t num_nodes = 0)¶
-
WeightedGraph
(const WeightedGraph&)¶ Copy constructor.
-
WeightedGraph
(WeightedGraph&&)¶ Move constructor.
-
~WeightedGraph
()¶
-
WeightedGraph &
operator=
(const WeightedGraph&)¶ Copy operator.
-
WeightedGraph &
operator=
(WeightedGraph&&)¶ Move operator.
-
void
Resize
(size_t new_size)¶
-
double
GetWeight
(size_t from, size_t to) const¶ Determine weight of a specific edge in this graph.
-
void
AddEdge
(size_t from, size_t to, double weight)¶ When Adding an edge, must also provide a weight.
-
void
AddEdgePair
(size_t from, size_t to, double weight)¶ When Adding an edge pair, must also provide a weight.
-
void
Merge
(const WeightedGraph &in_graph)¶ Merge two WeightedGraphs into one.
-
void
PrintSym
(std::ostream &os = std::cout)¶ Print a symmetric graph to the provided output stream (defaulting to standard out)
-
void
PrintDirected
(std::ostream &os = std::cout)¶ Print a directed graph to the provided output stream (defaulting to standard out)
-
size_t
GetSize
() const¶ Get number of vertices in this graph.
-
size_t
GetEdgeCount
() const¶ Get the total number of edges in this graph.
-
const BitVector &
GetEdgeSet
(size_t id) const¶ Get the set of nodes that a specified node is connected to.
-
size_t
GetDegree
(size_t id) const¶ Get the degree of a specified node.
-
size_t
GetMaskedDegree
(size_t id, const BitVector &mask) const¶ Get how many of a set of nodes that a specified node is connected to.
-
bool
HasEdge
(size_t from, size_t to) const¶ Determine if a specific edge is included in this graph.
-
void
AddEdge
(size_t from, size_t to)¶ Add a specified edge into this graph.
-
void
RemoveEdge
(size_t from, size_t to)¶ Remove a specified edge from this graph.
-
void
SetEdge
(size_t from, size_t to, bool val)¶ Set the status of a specified edge as to whether or not it should be in the graph.
-
bool
HasEdgePair
(size_t from, size_t to) const¶ Determine if edges exist in both directions between a pair of vertices.
-
void
AddEdgePair
(size_t from, size_t to)¶ Add a pair of edges between two vertieces (in both directions)
-
void
RemoveEdgePair
(size_t from, size_t to)¶ Remove edges in both directions between a pair of vertices.
-
void
SetEdgePairs
(size_t from, size_t to, bool val)¶ Set the status as to whether a pair of edges (in both direction) exist.
-
Grids¶
-
namespace
emp
If we are in emscripten, make sure to include the header.
This file contains extra analysis tools to use with systematics managers that have non-null DATA_TYPES.
- 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
- 2018
This file contains functions for adding additional data files to Worlds.
- 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
- 2018
-
namespace
Grid
¶ -
template <typename CELL_TYPE = int, typename EDGE_TYPE = void, class POINT_TYPE = void>
classBoard
¶ - #include <grid.h>
Public Functions
-
CELL_TYPE
GetCellValue
(int id) const¶
-
EDGE_TYPE
GetEdgeHValue
(int id) const¶
-
EDGE_TYPE
GetEdgeVValue
(int id) const¶
-
POINT_TYPE
GetPointValue
(int id) const¶
-
void
SetCellValue
(int id, CELL_TYPE value)¶
-
void
SetEdgeHValue
(int id, EDGE_TYPE value)¶
-
void
SetEdgeVValue
(int id, EDGE_TYPE value)¶
-
void
SetPointValue
(int id, POINT_TYPE value)¶
-
CELL_TYPE
-
template <typename CELL_TYPE>
classCell
¶ - #include <grid.h>
-
template <typename EDGE_TYPE>
classHEdge
¶ - #include <grid.h>
-
class
Layout
¶ - #include <grid.h>
Public Functions
-
Layout
(int w, int h)¶
-
~Layout
()¶
-
int
GetWidth
() const¶
-
int
GetHeight
() const¶
-
int
GetNumRegions
() const¶
-
int
GetX
(int id) const¶
-
int
GetY
(int id) const¶
-
int
GetID
(int x, int y) const¶
-
int
GetTopID
(int id) const¶
-
int
GetBottomID
(int id) const¶
-
int
GetLeftID
(int id) const¶
-
int
GetRightID
(int id) const¶
-
-
template <typename POINT_TYPE>
classPoint
¶ - #include <grid.h>
-
template <typename STATE_TYPE>
classStateSet
¶ - #include <grid.h>
-
template <>
template<>
classStateSet
<bool>¶ - #include <grid.h>
-
template <>
template<>
classStateSet
<void>¶ - #include <grid.h>
-
template <typename CELL_TYPE = int, typename EDGE_TYPE = void, class POINT_TYPE = void>
Index Map¶
A simple class to weight items differently within a container and return the correct index.
- 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
- 2015-2018
- Note
- Status: BETA
-
namespace
emp
If we are in emscripten, make sure to include the header.
This file contains extra analysis tools to use with systematics managers that have non-null DATA_TYPES.
- 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
- 2018
This file contains functions for adding additional data files to Worlds.
- 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
- 2018
-
class
IndexMap
¶ - #include <IndexMap.h>
A map of weighted indecies. If a random index is selected, the probability of an index being returned is directly proportional to its weight.
Public Functions
-
IndexMap
(size_t _items = 0)¶ Construct an IndexMap where num_items is the maximum number of items that can be placed into the data structure. All item weigths default to zero.
-
IndexMap
(size_t _items, double init_weight)¶
-
~IndexMap
()¶
-
size_t
GetSize
() const¶ How many indices are in this map?
-
double
GetWeight
() const¶ What is the total weight of all indices in this map?
-
double
RawWeight
(size_t id) const¶ What is the current weight of the specified index?
-
double
GetWeight
(size_t id) const¶
-
double
RawProb
(size_t id) const¶ What is the probability of the specified index being selected?
-
double
GetProb
(size_t id) const¶
-
void
Resize
(size_t new_size, double def_value = 0.0)¶ Change the number of indecies in the map.
-
size_t
size
() const¶ Standard library compatibility.
-
void
resize
(size_t new_size)¶ Standard library compatibility.
-
void
Clear
()¶ Reset all item weights to zero.
-
void
ResizeClear
(size_t new_size)¶ Change the size of this map AND change all weights to zero.
-
void
RawAdjust
(size_t id, const double new_weight)¶ Adjust the weight associated with a particular index in the map.
- Parameters
id
: is the identification number of the item whose weight is being adjusted.weight
: is the new weight for that entry.
-
void
Adjust
(size_t id, const double new_weight)¶
-
void
AdjustAll
(double new_weight)¶ Adjust all index weights to the set provided.
-
size_t
Index
(double index, size_t cur_id = 0) const¶ Determine the ID at the specified index position.
-
double
operator[]
(size_t id) const¶
-
IndexMap &
operator-=
(IndexMap &in_map)¶ Substract the weigthes from another index map from this one.
-
void
DeferRefresh
()¶ Indicate that we need to adjust weights before relying on them in the future; this will prevent refreshes from occuring immediately and is useful when many updates to weights are likely to be done before any are accessed again.
Private Functions
-
size_t
ParentID
(size_t id) const¶ Which ID is the parent of the ID provided?
-
size_t
LeftID
(size_t id) const¶ Which ID is the left child of the ID provided?
-
size_t
RightID
(size_t id) const¶ Which ID is the right child of the ID provided?
-
size_t
CalcZeroOffset
() const¶ Sift through the nodes to find the where index zero maps to.
-
size_t
ToInternalID
(size_t id) const¶
-
size_t
ToInternalID
(size_t id, size_t _items, size_t _offset) const¶
-
size_t
ToExternalID
(size_t id) const¶
-
void
ResolveRefresh
() const¶ Check if we need to do a refresh, and if so do it!
-
Information Theory Tools¶
-
namespace
emp
If we are in emscripten, make sure to include the header.
This file contains extra analysis tools to use with systematics managers that have non-null DATA_TYPES.
- 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
- 2018
This file contains functions for adding additional data files to Worlds.
- 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
- 2018
Functions
-
template <typename CONTAINER>
doubleEntropy
(const CONTAINER &weights)¶ Convert a vector of weights to probabilities and return the entropy of the system.
-
template <typename CONTAINER, typename WEIGHT_FUN>
doubleEntropy
(const CONTAINER &objs, WEIGHT_FUN fun, double total = 0.0)¶ Calculate the entropy in a container of arbitrary objects. Args are a container, a function to extract the weight of each member, and an (optional) total weight.
-
constexpr double
Entropy2
(const double p)¶ Calculate the entropy when their are two possibile states based on one state’s probability.
-
template <typename CONTAINER, typename CAT_FUN_X, typename CAT_FUN_Y, typename WEIGHT_FUN>
doubleEntropy
(const CONTAINER &objs, CAT_FUN_X funX, CAT_FUN_Y funY, WEIGHT_FUN funW)¶ Conitional Entropy: H(X|Y) Allow for entropy of arbitrary objects with a converter.
Lexer Utilities¶
A set of utilities to convert between NFAs and DFAs.
- 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-2017
- Note
- Status: BETA
-
namespace
emp
If we are in emscripten, make sure to include the header.
This file contains extra analysis tools to use with systematics managers that have non-null DATA_TYPES.
- 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
- 2018
This file contains functions for adding additional data files to Worlds.
- 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
- 2018
Functions
-
static const DFA &
to_DFA
(const DFA &dfa)¶ Converting DFA to DFA no change needed.
-
static const NFA &
to_NFA
(const NFA &nfa)¶ Converting NFA to MFA no change needed.
-
static DFA
to_DFA
(const NFA &nfa, int keep_invalid = false)¶ Systematic conversion of NFA to DFA…
-
static NFA
to_NFA
(const DFA &dfa)¶ Systematic up-conversion of DFA to NFA…
-
template <typename T1>
static NFAMergeNFA
(T1 &&in)¶ Merge multiple automata into one NFA (base case, single converstion)
-
template <typename T1, typename T2, typename... Ts>
static NFAMergeNFA
(T1 &&in1, T2 &&in2, Ts&&... others)¶ Merge multiple automata (DFA, NFA, RegEx) into one NFA.
-
struct
DFAStatus
¶ - #include <lexer_utils.h>
Structure to track the current status of a DFA.
Lexer¶
A general-purpose, fast lexer.
- 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-2017
- Note
- Status: BETA
-
namespace
emp
If we are in emscripten, make sure to include the header.
This file contains extra analysis tools to use with systematics managers that have non-null DATA_TYPES.
- 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
- 2018
This file contains functions for adding additional data files to Worlds.
- 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
- 2018
-
class
Lexer
¶ - #include <Lexer.h>
A lexer with a set of token types (and associated regular expressions)
Public Functions
-
Lexer
()¶
-
~Lexer
()¶
-
size_t
AddToken
(const std::string &in_name, const std::string &in_regex)¶ Add a new token, specified by a name and the regex used to identify it.
-
size_t
GetTokenID
(const std::string &name) const¶ Get the ID associated with a token type (you provide the token name)
-
std::string
GetTokenName
(size_t id) const¶ Get the name associated with a token type (you provide the ID)
-
TokenInfo
GetTokenInfo
(const std::string &name) const¶ Get the full information about a token (you provide the name)
-
void
Generate
() const¶ Create the NFA that will identify the current set of tokens in a sequence.
Public Static Functions
-
static bool
TokenOK
(size_t id)¶
-
static constexpr size_t
MaxTokenID
()¶ How many total token types are allowed in this lexer?
-
-
struct
Token
¶ - #include <Lexer.h>
Information about a token instance from an input stream.
Public Functions
Map Utilities¶
A set of simple functions to manipulate maps.
- 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-2017
- Note
- Status: BETA
-
namespace
emp
If we are in emscripten, make sure to include the header.
This file contains extra analysis tools to use with systematics managers that have non-null DATA_TYPES.
- 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
- 2018
This file contains functions for adding additional data files to Worlds.
- 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
- 2018
Functions
-
template <class MAP_T, class KEY_T>
boolHas
(const MAP_T &in_map, const KEY_T &key)¶ Take any map type, and run find to determine if a key is present.
-
template <class MAP_T, class KEY_T>
autoFind
(const MAP_T &in_map, const KEY_T &key, const typename MAP_T::mapped_type &dval)¶ Take any map, run find() member function, and return the result found (or default value if no results found).
-
template <class MAP_T, class KEY_T>
const auto &FindRef
(const MAP_T &in_map, const KEY_T &key, const typename MAP_T::mapped_type &dval)¶ Take any map and element, run find() member function, and return a reference to the result found (or default value if no results found).
Math¶
Useful mathematical functions (that are constexpr when possible.)
- 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 (though new functions are added frequently)
-
namespace
emp
If we are in emscripten, make sure to include the header.
This file contains extra analysis tools to use with systematics managers that have non-null DATA_TYPES.
- 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
- 2018
This file contains functions for adding additional data files to Worlds.
- 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
- 2018
Functions
-
constexpr int
Mod
(int in_val, int mod_val)¶ % is actually remainder; Mod is a proper modulus command that handles negative #’s correctly
-
double
Mod
(double in_val, double mod_val)¶ Regular Mod doesn’t work on doubles. Build one that does!
-
template <typename T>
constexpr TAbs
(T in)¶ Find the absolute value for any variable.
-
template <typename TYPE>
constexpr TYPEToRange
(const TYPE &value, const TYPE &in_min, const TYPE &in_max)¶ Run both min and max on a value to put it into a desired range.
-
template <typename T>
constexpr TMin
(T in1)¶ Min of only one element is that element itself!
-
template <typename T, typename... Ts>
constexpr TMin
(T in1, T in2, Ts... extras)¶ Min of multiple elements is solved recursively.
-
template <typename T>
constexpr TMax
(T in1)¶ Max of only one element is that element itself!
-
template <typename T, typename... Ts>
constexpr TMax
(T in1, T in2, Ts... extras)¶ Max of multiple elements is solved recursively.
-
template <typename T>
constexpr const T &MinRef
(const T &in1)¶ MinRef works like Min, but never copies any inputs; always treats as references. MinRef of only one element returns reference to that element itself!
-
template <typename T, typename... Ts>
constexpr const T &MinRef
(const T &in1, const T &in2, const Ts&... extras)¶ MinRef of multiple elements returns reference to minimum value.
-
template <typename T>
constexpr const T &MaxRef
(const T &in1)¶ MaxRef works like Max, but never copies any inputs; always treats as references. MaxRef of only one element returns reference to that element itself!
-
template <typename T, typename... Ts>
constexpr const T &MaxRef
(const T &in1, const T &in2, const Ts&... extras)¶ MaxRef of multiple elements returns reference to maximum value.
-
static constexpr double
Log2
(double x)¶ Compile-time log base 2 calculator.
-
static constexpr double
Log
(double x, double base = 10.0)¶ Compile-time log calculator.
-
static constexpr double
Ln
(double x)¶ Compile-time natural log calculator.
-
static constexpr double
Log10
(double x)¶ Compile-time log base 10 calculator.
-
template <typename T>
static constexpr TSquare
(T val)¶ A simple function to square a value.
-
template <typename T>
static constexpr type_if<T, std::is_integral>Pow
(T base, T p)¶ A fast (O(log p)) integral-power command.
-
static constexpr double
Pow2
(double exp)¶ A fast 2^x command.
-
template <typename TYPE>
static constexpr TYPEIntPow
(TYPE base, TYPE exp)¶ A fast method for calculating exponents for int types.
-
static constexpr double
Pow
(double base, double exp)¶ A fast method for calculating exponents on doubles.
-
static constexpr double
Exp
(double exp)¶ A fast method of calculating e^x.
-
template <typename TYPE>
static constexpr intIntLog2
(TYPE x)¶ A compile-time int-log calculator (aka, significant bits)
-
template <typename TYPE>
static constexpr intCountOnes
(TYPE x)¶ A compile-time bit counter.
-
template <typename TYPE>
static constexpr TYPEMaskLow
(std::size_t num_bits)¶ Quick bit-mask generator for low bits.
-
template <typename TYPE>
static constexpr TYPEMaskHigh
(std::size_t num_bits)¶ Quick bit-mask generator for high bits.
-
template <typename T>
constexpr const T &Min
(const T &in1, const T &in2, const T &in3)¶ Return the minimum of three values.
-
namespace
internal
¶
Memory Tracking¶
A set of macros to track how many instances of specific classes are made.
One way of tracking memory leaks is to simply count instances of classes. The macros here simplify this process.
- 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
- 2015-2017
- Note
- Status: BETA
To setup, every constructor for a class must incude EMP_TRACK_CONSTRUCT(CLASS_NAME), and every destructor must have EMP_TRACK_DESTRUCT(CLASS_NAME). Make sure to avoid implicit constructors/destructors or counts will be off.
To collect information, EMP_TRACK_COUNT(CLASS_NAME) will provide the current count for a specific class, and EMP_TRACK_STATUS will translate into a string providing information about all available classes.
Developer notes:
-
namespace
emp
If we are in emscripten, make sure to include the header.
This file contains extra analysis tools to use with systematics managers that have non-null DATA_TYPES.
- 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
- 2018
This file contains functions for adding additional data files to Worlds.
- 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
- 2018
-
namespace
internal
¶
Memoized Functions¶
Warning
doxygenfile: Cannot find file “tools/memo_functions.h
Non-Deterministic Finite Automata¶
A Non-deterministic Finite Automata simulator.
To build a standard NFA, use
emp::NFA. If you want to have more symbols or more stop states, use emp::tNFA<S,T> where S is the number of symbols and T is the type used for stop. (defaults are 128 for ASCII-128 and uint8_t respectively.)- 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-2017
- Note
- Status: BETA
The constructor can take as parameters the number of states and the id of the start state (both default to 0)
- Note
- DFA’s use SetTransition(), but NFA’s use AddTransition. This distinction is intentional since in a DFA a second SetTransition with the same start state and symbol will override first, while in an NFA a second AddTransition will always add a new option.
-
namespace
emp
If we are in emscripten, make sure to include the header.
This file contains extra analysis tools to use with systematics managers that have non-null DATA_TYPES.
- 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
- 2018
This file contains functions for adding additional data files to Worlds.
- 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
- 2018
Typedefs
-
using
emp::NFA = typedef tNFA<128, uint8_t>
NFA is the most standard tNFA setup.
-
using
emp::NFA_State = typedef tNFA_State<128, uint8_t>
NFA_State is the most standard tNFA_State setup.
-
template <size_t S = 128, typename STOP_TYPE = uint8_t>
classtNFA
¶ - #include <NFA.h>
A dynamic NFA class, for easily building non-determanistic finite automata.
Public Functions
-
tNFA
(size_t num_states = 1, size_t start_state = 0)¶
-
~tNFA
()¶
-
size_t
GetSize
() const¶ Return the current number of states.
-
const std::set<size_t> &
GetStart
() const¶ Return start state and all others reachable through empty transitions.
-
std::set<size_t>
GetNext
(size_t sym, size_t from_id = 0) const¶ Return the states reachable from the current state given the provided symbol.
-
std::set<size_t>
GetNext
(size_t sym, const std::set<size_t> from_set) const¶ return the states reachable from the current set of states given the provided symbol.
-
bool
HasFreeTransitions
(size_t id) const¶ Does the provided state have free transitions?
-
bool
HasSymTransitions
(size_t id) const¶ Does the provided state have symbol-transitions?
-
opts_t
GetSymbolOptions
(const std::set<size_t> &test_set) const¶ Return an emp::BitSet indicating the symbols available from the provided set of states.
-
void
Resize
(size_t new_size)¶ Change the number of available states.
-
size_t
AddNewState
()¶ Add a new state into the NFA and return its id.
-
void
AddTransition
(size_t from, size_t to, size_t sym)¶ Add a transition between states ‘from’ and ‘to’ that can be taken with the provided symbol.
-
void
AddTransition
(size_t from, size_t to, const std::string &sym_set)¶ Add a transition between states ‘from’ and ‘to’ that can be taken with the provided symbols.
-
void
AddTransition
(size_t from, size_t to, const BitSet<NUM_SYMBOLS> &sym_set)¶ Add a transition between states ‘from’ and ‘to’ that can be taken with the provided symbols.
-
void
AddFreeTransition
(size_t from, size_t to)¶ Create a free transition between ‘from’ and ‘to’.
-
template <typename T = stop_t>
voidSetStop
(size_t state, T stop_val = 1)¶ Set the specified state to be a stop state (with an optional stop value.)
-
stop_t
GetStop
(size_t state) const¶ Get any stop value associated with the provided state.
-
bool
IsStart
(size_t state) const¶ Test if NFA begins at provided state (may have free transitions to other states)
-
bool
IsStop
(size_t state) const¶ Test if this state is a legal endpoint for the NFA.
-
bool
IsEmpty
(size_t state) const¶ Test if this state has only empty transitions from it, and not stop state.
-
void
Merge
(const tNFA<NUM_SYMBOLS, STOP_TYPE> &nfa2)¶ Merge another NFA into this one.
-
void
Print
() const¶ Print information about this NFA (for debugging)
-
void
PrintFreeMoves
()¶ Identify free moves in NFA (for debugging)
Public Static Attributes
-
constexpr const size_t
NUM_SYMBOLS
= S¶
Private Members
-
size_t
start
¶ Main start state (others might be reached for free.)
-
-
template <size_t NUM_SYMBOLS = 128, typename STOP_TYPE = uint8_t>
classtNFA_State
¶ - #include <NFA.h>
Information about the current full state (i.e., set of legal states) of an NFA.
Public Functions
-
~tNFA_State
()¶
-
bool
IsActive
() const¶ Are there currently any legal NFA states?
-
bool
IsStop
() const¶ Can we legally stop in any of the current states?
-
bool
HasState
(size_t id)¶ Is a particular NFA state currently included?
-
size_t
GetSize
()¶ How many states are currently included?
-
void
Reset
()¶ Change current states to start + free transitions from start.
-
void
Next
(size_t sym)¶ Update states given a new input symbol.
-
void
Next
(const std::string &sym_set)¶ Update states given a new series of input symbols (as a string)
-
void
Print
()¶ Print out current information about this NFA State (for debugging)
-
Parser¶
A general-purpose, fast parser.
- 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-2017
- Note
- Status: DEVELOPMENT
-
namespace
emp
If we are in emscripten, make sure to include the header.
This file contains extra analysis tools to use with systematics managers that have non-null DATA_TYPES.
- 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
- 2018
This file contains functions for adding additional data files to Worlds.
- 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
- 2018
-
class
Parser
¶ - #include <Parser.h>
Full information about a parser, including a lexer, symbols, and rules.
Public Functions
-
~Parser
()¶
-
size_t
GetID
(size_t id) const¶ Trivial conversions of ID to ID…
-
ParseSymbol &
GetParseSymbol
(const std::string &name)¶ Get the parser symbol information associated with a provided name.
-
template <typename... STATES>
Parser &Rule
(STATES... states)¶ Use the currently active symbol and attach a rule to it.
-
template <typename... STATES>
size_tAddRule
(const std::string &name, STATES&&... states)¶ Specify the name of the symbol and add a rule to it, returning the symbol id.
Private Functions
-
template <typename T, typename... EXTRAS>
voidBuildRule
(emp::vector<size_t> &new_pattern, T &&arg, EXTRAS&&... extras)¶
-
int
GetSymbolPos
(const std::string &name) const¶ Return the position in the symbols vector where this name is found; else return -1.
-
int
GetIDPos
(size_t id) const¶ Convert a symbol ID into its position in the symbols[] vector.
Private Members
-
emp::vector<ParseSymbol>
symbols
¶ Set of symbols that make up this grammar.
-
size_t
cur_symbol_id
¶ Which id should the next new symbol get?
-
int
active_pos
¶ Which symbol pos is active?
-
Random-Access Set¶
This file defines a Random Access Set template.
- 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
- 2017
- Note
- Status: ALPHA
-
namespace
emp
If we are in emscripten, make sure to include the header.
This file contains extra analysis tools to use with systematics managers that have non-null DATA_TYPES.
- 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
- 2018
This file contains functions for adding additional data files to Worlds.
- 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
- 2018
-
template <typename T>
classra_set
¶ - #include <ra_set.h>
This class uses a combination of a hashtable (std::unordered_map) and emp::vector to lookup insert, lookup, and delete values in constant time, while still being able to step through all values (albeit in an arbitrary order).
- Note
- The arbitrary order of values may change if any values are deleted.
Public Types
-
template<>
usingvalue_type
= T¶
Public Functions
-
ra_set
()¶
-
size_t
size
() const¶ How many elements are in this set?
-
void
clear
()¶ Remove all values from this container.
-
void
insert
(const T &v)¶ Insert a new value into container.
-
bool
erase
(const T &v)¶ Erase a specific value from the container.
-
size_t
count
(const T &v) const¶ Count the number of times a particular value in in the container (0 or 1).
Randomness Utilites¶
Helper functions for emp::Random for common random tasks.
- 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-2017
- Note
- Status: RELEASE
-
namespace
emp
If we are in emscripten, make sure to include the header.
This file contains extra analysis tools to use with systematics managers that have non-null DATA_TYPES.
- 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
- 2018
This file contains functions for adding additional data files to Worlds.
- 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
- 2018
Functions
-
template <typename T>
voidShuffle
(Random &random, emp::vector<T> &v, size_t max_count)¶ Randomly reorder all of the elements in a vector. If max_count is provided, just make sure that the first max_count entries are randomly drawn from entire vector.
-
emp::vector<size_t>
GetPermutation
(Random &random, size_t size)¶ Return an emp::vector<int> numbered 0 through size-1 in a random order.
-
void
Choose
(Random &random, size_t N, size_t K, std::vector<size_t> &choices)¶ Choose K positions from N possibilities.
-
BitVector
RandomBitVector
(Random &random, size_t size, double p = 0.5)¶ Generate a random BitVector of the specified size.
-
emp::vector<double>
RandomDoubleVector
(Random &random, size_t size, double min, double max)¶ Generate a random double vector in the specified range.
-
emp::vector<size_t>
RandomUIntVector
(Random &random, size_t size, size_t min, size_t max)¶ Generate a random size_t vector in the specified range.
-
template <typename T>
emp::vector<T>RandomVector
(Random &random, size_t size, T min, T max)¶ Generate a random vector in the specified type and range.
Random Number Generator¶
A versatile and non-patterned pseudo-random-number generator.
- 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
- 2015-2018
- Note
- Status: RELEASE
-
namespace
emp
If we are in emscripten, make sure to include the header.
This file contains extra analysis tools to use with systematics managers that have non-null DATA_TYPES.
- 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
- 2018
This file contains functions for adding additional data files to Worlds.
- 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
- 2018
Range¶
A simple way to track value ranges.
- 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
-
namespace
emp
If we are in emscripten, make sure to include the header.
This file contains extra analysis tools to use with systematics managers that have non-null DATA_TYPES.
- 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
- 2018
This file contains functions for adding additional data files to Worlds.
- 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
- 2018
Functions
-
template <typename T>
classRange
¶ - #include <Range.h>
A range of values from a lower limit to and upper limit, of any provided type.
Public Functions
-
Range
()¶
-
Range
(T _l, T _u)¶
-
T
GetLower
() const¶
-
T
GetUpper
() const¶
-
size_t
CalcBin
(T value, size_t num_bins) const¶
-
void
SetLower
(T l)¶
-
void
SetUpper
(T u)¶
-
void
Set
(T _l, T _u)¶
-
void
SetMaxLower
()¶
-
void
SetMaxUpper
()¶
-
bool
Valid
(T value) const¶ Determine if a provided value is in the range.
-
T
Limit
(T _in) const¶ Force a value into range.
-
Regular Expressions¶
Basic regular expression handler.
A fully (well, mostly) functional regular expression processor.
- 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-2017
- Note
- Status: BETA
Special chars: ‘|’ - or ‘*’ - zero or more of previous ‘+’ - one or more of previous ‘?’ - previous is optional ‘.’ - Match any character except
Pluse the following group contents (and change may translation rules) ‘(‘ and ‘)’ - group contents ‘”’ - Ignore special characters in contents (quotes still need to be escaped) ‘[‘ and ‘]’ - character set
choose ONE character ^ as first char negates contents ; - indicates range UNLESS first or last.Additional overloads for functions in lexer_utils.h:
static NFA to_NFA(const RegEx & regex, int stop_id=1); static DFA to_DFA(const RegEx & regex);
-
namespace
emp
If we are in emscripten, make sure to include the header.
This file contains extra analysis tools to use with systematics managers that have non-null DATA_TYPES.
- 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
- 2018
This file contains functions for adding additional data files to Worlds.
- 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
- 2018
Functions
-
class
RegEx
¶ - #include <RegEx.h>
A basic regular expression handler.
Public Functions
-
RegEx
()¶
-
~RegEx
()¶
-
std::string
AsString
() const¶ Convert the RegEx to an standard string, readable from outsite this class.
-
void
AddToNFA
(NFA &nfa, size_t start, size_t stop) const¶ Add this regex to an NFA being built.
-
void
PrintInternal
()¶ For debugging: print the internal representation of the regex.
-
void
PrintNotes
()¶ For debugging: print any internal notes generated about this regex.
-
void
PrintDebug
()¶ Print general debuging information about this regex.
Private Types
-
using
opts_t
= BitSet<NUM_SYMBOLS>¶
Private Functions
-
template <typename... T>
voidError
(T&&... args)¶
-
bool
EnsureNext
(char x)¶ Make sure that there is another element in the RegEx (e.g., after an ‘|’) or else trigger and error to report the problem.
-
Ptr<re_charset>
ConstructSet
()¶ Construct a character range.
Private Members
-
bool
valid
¶ Set to false if regex cannot be processed.
-
size_t
pos
¶ Position being read in regex.
-
bool
dfa_ready
¶ Is the dfa ready? (or does it need to be generated?)
Private Static Attributes
-
struct
re_base
¶ Internal base representation of a portion of a regex.
-
struct
re_parent
: public emp::RegEx::re_base¶ Intermediate base class for RegEx components that have children (such as “and” and “or”)
Public Functions
-
re_parent
()¶
-
~re_parent
()¶
-
void
Clear
()
-
virtual void
push
(Ptr<re_base> x)
-
Ptr<re_base>
pop
()
-
size_t
GetSize
() const
-
Ptr<re_parent>
AsParent
()
-
bool
Simplify
()¶
-
virtual Ptr<re_block>
AsBlock
()
-
virtual Ptr<re_charset>
AsCharSet
()
-
virtual Ptr<re_string>
AsString
()
-
virtual void
AddToNFA
(NFA &nfa, size_t start, size_t stop) const¶
-
-
struct
re_plus
: public emp::RegEx::re_parent¶ Representations of one-or-more instances of a component. e.g., a+.
Public Functions
-
virtual void
AddToNFA
(NFA &nfa, size_t start, size_t stop) const¶
-
void
Clear
()
-
virtual void
push
(Ptr<re_base> x)
-
Ptr<re_base>
pop
()
-
size_t
GetSize
() const
-
Ptr<re_parent>
AsParent
()
-
bool
Simplify
()
-
virtual Ptr<re_block>
AsBlock
()
-
virtual Ptr<re_charset>
AsCharSet
()
-
virtual Ptr<re_string>
AsString
()
-
virtual void
-
struct
re_qm
: public emp::RegEx::re_parent¶ Representations of zero-or-one instances of a component. e.g., a?
Public Functions
-
virtual void
AddToNFA
(NFA &nfa, size_t start, size_t stop) const¶
-
void
Clear
()
-
virtual void
push
(Ptr<re_base> x)
-
Ptr<re_base>
pop
()
-
size_t
GetSize
() const
-
Ptr<re_parent>
AsParent
()
-
bool
Simplify
()
-
virtual Ptr<re_block>
AsBlock
()
-
virtual Ptr<re_charset>
AsCharSet
()
-
virtual Ptr<re_string>
AsString
()
-
virtual void
-
struct
re_star
: public emp::RegEx::re_parent¶ Representations of zero-or-more instances of a component. e.g., a*.
Public Functions
-
virtual void
AddToNFA
(NFA &nfa, size_t start, size_t stop) const¶
-
void
Clear
()
-
virtual void
push
(Ptr<re_base> x)
-
Ptr<re_base>
pop
()
-
size_t
GetSize
() const
-
Ptr<re_parent>
AsParent
()
-
bool
Simplify
()
-
virtual Ptr<re_block>
AsBlock
()
-
virtual Ptr<re_charset>
AsCharSet
()
-
virtual Ptr<re_string>
AsString
()
-
virtual void
-
Sequence Utilities¶
Functions for analyzing with generic sequence types.
A set of functions for analyzing sequences, including distance metrics (Hamming and Edit/Levenschtein) and alignment.
- 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-2017
- Note
- Status: BETA
-
namespace
emp
If we are in emscripten, make sure to include the header.
This file contains extra analysis tools to use with systematics managers that have non-null DATA_TYPES.
- 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
- 2018
This file contains functions for adding additional data files to Worlds.
- 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
- 2018
Functions
-
template <typename TYPE>
size_tcalc_hamming_distance
(const TYPE &in1, const TYPE &in2, int offset = 0)¶ Hamming distance is a simple count of substitutions needed to convert one array to another.
- Parameters
in1
: The first sequence to compare.in2
: The second sequence to compare.offset
: (optional) Position in the first sequence to start the second sequence.
-
template <typename TYPE>
size_tcalc_edit_distance
(const TYPE &in1, const TYPE &in2)¶ Edit distance is the minimum number of insertions, deletions and substitutions to convert one array to another.
-
template <typename TYPE, typename GAP_TYPE>
size_talign
(TYPE &in1, TYPE &in2, GAP_TYPE gap)¶ Use edit distance to find the minimum number of insertions, deletions and substitutions to convert one array to another, and then insert gaps into the arrays appropriately.
Serialization Macros¶
Macros for simplifying to serialization of objects.
- 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
- 2015-2017
- Note
- Status: ALPHA
Serialization Tools¶
Tools to save and load data from classes.
All of the important information about a class is stored in a DataPod, which can be used to restore the class at a later time.
- 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
- 2015-2017
- Note
- Status: ALPHA
Why is this better than other serialization techniques?
- Only one line of code is added to a custom class to make it serializable.
- Serialized objects do not need a default constructor (a DataPod constructor is added)
- Serialized objects can be const since they get rebuilt during construction.
- Synergistic interactions with other EMP classes, such as config and tuple_struct
In order to setup a target class to be able to be serialized into a pod, you must add a macro to include the needed functionality. For a basic class, use:
EMP_SETUP_DATAPOD(ClassName, var1, var2, …)
Where ClassName is the target class’ name and var1, var2, etc are the names of the member variables that also need to be stored. Note that member variables can either be either built-in types or custom types that have also had DataPods setup in them.
If the target class is a derived class, you must use either:
EMP_SETUP_DATAPOD_D(ClassName, BassClassName, var1, var2, …)
-or-
EMP_SETUP_DATAPOD_D2(ClassName, BassClass1Name, BaseClass2Name, var1, var2, …)
…depending on how many base classes it was derived from (currently max 2).
Note also that this macro must either go in the public section of the target class definition, or the target class must be made a friend to the emp::serialize::DataPod class.
-
namespace
emp
If we are in emscripten, make sure to include the header.
This file contains extra analysis tools to use with systematics managers that have non-null DATA_TYPES.
- 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
- 2018
This file contains functions for adding additional data files to Worlds.
- 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
- 2018
-
namespace
serialize
¶ Functions
-
template <typename T>
autoStoreVar
(DataPod &pod, const T &var, bool)¶ StoreVar() takes a DataPod and a variable and stores that variable to the pod. The third argument (bool vs. int) will receive a bool, and thus bool versions are preferred in the case of a tie. Specialized versions of this function can be included elsewhere, as needed, and should take a bool as the third argument.
-
template <typename T>
Set Utilities¶
Tools to save and load data from classes.
- 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: ALPHA
-
namespace
emp
If we are in emscripten, make sure to include the header.
This file contains extra analysis tools to use with systematics managers that have non-null DATA_TYPES.
- 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
- 2018
This file contains functions for adding additional data files to Worlds.
- 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
- 2018
Functions
-
template <typename T>
voidinsert
(std::set<T> &s1, const std::set<T> &s2)¶ Insert the full contents of s2 into s1.
-
template <typename T, typename H>
boolHas
(const std::set<T, H> &s, const T &val)¶ Test if an std::set has a particular element without modifying the set in any way.
-
template <typename T, typename H>
boolHas
(const std::multiset<T, H> &s, const T &val)¶ Test if an std::multiset has a particular element without modifying the set in any way.
-
template <typename T, typename H>
boolHas
(const std::unordered_set<T, H> &s, const T &val)¶ Test if an std::unordered_set has a particular element without modifying the set in any way.
-
template <typename T, typename H>
boolHas
(const std::unordered_multiset<T, H> &s, const T &val)¶ Test if an std::unordere_multiset has a particular element without modifying the set in any way.
-
template <typename T>
std::set<T>difference
(std::set<T> &s1, std::set<T> &s2)¶ Compute the set difference of.
- Parameters
s1
: ands2
: (elements that are in S1 but no S2)
-
template <typename T>
std::set<T>difference
(emp::vector<T> s1, emp::vector<T> &s2)¶ Compute the set difference of.
- Parameters
s1
: ands2
: (elements that are in S1 but no S2)
-
template <typename T>
std::set<T>difference
(std::set<T> &s1, emp::vector<T> s2)¶ Compute the set difference of.
- Parameters
s1
: ands2
: (elements that are in S1 but not S2)
-
template <typename T>
std::set<T>difference
(emp::vector<T> s1, std::set<T> &s2)¶ Compute the set difference of.
- Parameters
s1
: ands2
: (elements that are in S1 but no S2)
-
template <typename T>
std::set<T>intersection
(std::set<T> s1, std::set<T> s2)¶ Compute the set intersection of.
- Parameters
s1
: ands2
: (elements that are in both S1 and S2)
-
template <typename T>
std::set<T>intersection
(emp::vector<T> s1, emp::vector<T> s2)¶ Compute the set intersection of.
- Parameters
s1
: ands2
: (elements that are in both S1 and S2)
-
template <typename T>
std::set<T>intersection
(std::set<T> s1, emp::vector<T> s2)¶ Compute the set intersection of.
- Parameters
s1
: ands2
: (elements that are in both S1 and S2)
-
template <typename T>
std::set<T>intersection
(emp::vector<T> s1, std::set<T> s2)¶ Compute the set intersection of.
- Parameters
s1
: ands2
: (elements that are in both S1 and S2)
-
template <typename T>
std::set<T>set_union
(std::set<T> s1, std::set<T> s2)¶ Compute the set union of.
- Parameters
s1
: ands2
: (elements that are in either S1 or S2)
-
template <typename T>
std::set<T>set_union
(emp::vector<T> s1, emp::vector<T> s2)¶ Compute the set union of.
- Parameters
s1
: ands2
: (elements that are in either S1 or S2)
-
template <typename T>
std::set<T>set_union
(std::set<T> s1, emp::vector<T> s2)¶ Compute the set union of.
- Parameters
s1
: ands2
: (elements that are in either S1 or S2)
-
template <typename T>
std::set<T>set_union
(emp::vector<T> s1, std::set<T> s2)¶ Compute the set union of.
- Parameters
s1
: ands2
: (elements that are in either S1 or S2)
-
template <typename T>
std::set<T>symmetric_difference
(std::set<T> s1, std::set<T> s2)¶ Compute the set symmetric_difference of.
- Parameters
s1
: ands2
: (elements that are in either S1 or S2 but not both)
-
template <typename T>
std::set<T>symmetric_difference
(emp::vector<T> s1, emp::vector<T> s2)¶ Compute the set symmetric_difference of.
- Parameters
s1
: ands2
: (elements that are in either S1 or S2 but not both)
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-2017
- Note
- Status: BETA
-
namespace
emp
If we are in emscripten, make sure to include the header.
This file contains extra analysis tools to use with systematics managers that have non-null DATA_TYPES.
- 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
- 2018
This file contains functions for adding additional data files to Worlds.
- 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
- 2018
-
class
SolveState
¶ - #include <SolveState.h>
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.)
-
Statistics Tools¶
Functions for calculating various statistics about an ensemble.
- 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-2017
- Note
- Status: BETA
-
namespace
emp
If we are in emscripten, make sure to include the header.
This file contains extra analysis tools to use with systematics managers that have non-null DATA_TYPES.
- 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
- 2018
This file contains functions for adding additional data files to Worlds.
- 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
- 2018
Functions
-
template <typename C>
std::enable_if<!emp::is_ptr_type<typename C::value_type>::value && std::is_scalar<typename C::value_type>::value, typename C::value_type>::typeSum
(C &elements)¶ Calculate sum of the members of the container passed Only works on containers with a scalar member type
-
template <typename C>
std::enable_if<emp::is_ptr_type<typename C::value_type>::value && std::is_scalar<typename emp::remove_ptr_type<typename C::value_type>::type >::value, typename emp::remove_ptr_type<typename C::value_type>::type>::typeSum
(C &elements)¶ Calculate sum of the values pointed at by pointers in a container Only works on containers of pointers to a scalar type
-
template <typename C>
std::enable_if<!emp::is_ptr_type<typename C::value_type>::value, double>::typeShannonEntropy
(C &elements)¶ Calculate Shannon Entropy of the members of the container passed.
-
template <typename C>
std::enable_if<emp::is_ptr_type<typename C::value_type>::value, double>::typeShannonEntropy
(C &elements)¶ Calculate Shannon Entropy of the members of the container when those members are pointers.
-
template <typename C>
std::enable_if<!emp::is_ptr_type<typename C::value_type>::value && std::is_scalar<typename C::value_type>::value, double>::typeVariance
(C &elements)¶ Calculate variance of the members of the container passed Only works on containers with a scalar member type
-
template <typename C>
std::enable_if<emp::is_ptr_type<typename C::value_type>::value && std::is_scalar<typename emp::remove_ptr_type<typename C::value_type>::type >::value, double>::typeVariance
(C &elements)¶ Calculate variance of the values pointed at by members of the container passed Only works on containers with a scalar member type
-
template <typename C>
emp::sfinae_decoy<double, typename C::value_type>Mean
(C &elements)¶ Calculate the mean of the values in a container If values are pointers, they will be automatically de-referenced Values must be numeric.
-
template <typename C>
emp::sfinae_decoy<double, typename C::value_type>StandardDeviation
(C &elements)¶ Calculate the standard deviation of the values in a container If values are pointers, they will be automatically de-referenced Values must be numeric.
-
template <typename C>
std::enable_if<!emp::is_ptr_type<typename C::value_type>::value, int>::typeUniqueCount
(C &elements)¶ Count the number of unique elements in a container.
-
template <typename C>
std::enable_if<emp::is_ptr_type<typename C::value_type>::value, int>::typeUniqueCount
(C &elements)¶ Count the number of unique elements in the container of pointers. (compares objects pointed to; pointers do not have to be identical)
-
template <typename C, typename RET_TYPE, typename ARG_TYPE>
RET_TYPEMaxResult
(std::function<RET_TYPE(ARG_TYPE)> &fun, C &elements, )¶ Run the provided function on every member of a container and return the MAXIMUM result.
-
template <typename C, typename RET_TYPE, typename ARG_TYPE>
RET_TYPEMinResult
(std::function<RET_TYPE(ARG_TYPE)> &fun, C &elements, )¶ Run the provided function on every member of a container and return the MINIMUM result.
-
template <typename C, typename RET_TYPE, typename ARG_TYPE>
std::enable_if<std::is_scalar<RET_TYPE>::value, double>::typeMeanResult
(std::function<RET_TYPE(ARG_TYPE)> &fun, C &elements, )¶ Run the provided function on every member of a container and return the AVERAGE result. Function must return a scalar (i.e. numeric) type.
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-2018
- Note
- Status: RELEASE
-
namespace
emp
If we are in emscripten, make sure to include the header.
This file contains extra analysis tools to use with systematics managers that have non-null DATA_TYPES.
- 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
- 2018
This file contains functions for adding additional data files to Worlds.
- 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
- 2018
Functions
-
static 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.
-
static std::string
to_escaped_string
(char value)¶ Convert a single chararcter to one that uses a proper escape sequence (in a string) if needed.
-
static std::string
to_escaped_string
(const std::string &value)¶ Convert a full string to one that uses proper escape sequences, as needed.
-
template <typename LIT_TYPE>
std::stringto_literal
(const LIT_TYPE &value)¶ Take a value and convert it to a C++-style literal.
-
static std::string
to_literal
(const std::string &value)¶ Take a string and convert it to a C++-style literal.
-
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.
-
static 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)
-
static 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_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.
-
static 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 test_char)¶ If no functions are provided to is_valid(), always return false as base case.
-
template <typename... FUNS>
boolis_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>
static boolis_valid
(const std::string &test_str, FUNS... funs)¶ For a string to be valid, each character must pass at least one provided function.
-
static 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.
-
static 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)
-
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.
-
static void
remove_chars
(std::string &in_string, std::string chars)¶ Remove instances of characters from file.
-
static void
compress_whitespace
(std::string &in_string)¶ Every time one or more whitespace characters appear replace them with a single space.
-
static void
remove_whitespace
(std::string &in_string)¶ Remove all whitespace from anywhere within a string.
-
static void
remove_punctuation
(std::string &in_string)¶ Remove all characters from a string except letters, numbers, and whitespace.
-
static void
slice
(const std::string &in_string, emp::vector<std::string> &out_set, char delim = 'n')¶ Cut up a string based on the provided delimitor; fill them in to the provided vector.
-
static emp::vector<std::string>
slice
(const std::string &in_string, char delim = 'n')¶ Slice a string without passing in result vector (may be less efficient).
-
template <typename... ALL_TYPES>
std::stringto_string
(ALL_TYPES&&... all_values)¶ This function does its very best to convert everything it’s to a string. Takes any number of arguments and returns a single string containing all of them concatenated. Objects can be any normal (POD) data type, container, or anything that can be passed into a stringstream.
-
template <typename T>
Tfrom_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>
voidfrom_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.
-
namespace
internal
Tuple Struct¶
Tuple Utilities¶
Functions to simplify the use of std::tuple.
- 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-2017
- Note
- Status: RELEASE
-
namespace
emp
If we are in emscripten, make sure to include the header.
This file contains extra analysis tools to use with systematics managers that have non-null DATA_TYPES.
- 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
- 2018
This file contains functions for adding additional data files to Worlds.
- 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
- 2018
Functions
-
template <typename TUPLE_T>
constexpr inttuple_size
()¶ Quick way to calculate tuple size.
-
template <typename... Ts, int... Ps>
autoshuffle_tuple
(const std::tuple<Ts...> &tup, IntPack<Ps...>)¶ Reorganize the entries in tuple; the provided int pack must specify the new ordering.
-
template <typename FUN_T, typename TUPLE_T, int... N>
autoApplyTuple
(const FUN_T &fun, const TUPLE_T &tup, IntPack<N...>)¶ Apply a tuple as arguments to a function, where all argument positions in function are specified with and IntPack
-
template <typename FUN_T, typename TUPLE_T>
autoApplyTuple
(const FUN_T &fun, const TUPLE_T &tup)¶ Apply a tuple as arguments to a function, in order.
Type Tracker¶
Track class types abstractly to dynamically call correct function overloads.
- 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-2017
- Note
- Status: BETA
-
namespace
emp
If we are in emscripten, make sure to include the header.
This file contains extra analysis tools to use with systematics managers that have non-null DATA_TYPES.
- 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
- 2018
This file contains functions for adding additional data files to Worlds.
- 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
- 2018
-
struct
TrackedType
¶ - #include <TypeTracker.h>
The base class of any type to be tracked.
Subclassed by emp::TypeTracker_Class< REAL_T, ID >
-
template <typename... TYPES>
structTypeTracker
¶ - #include <TypeTracker.h>
Dynamic functions that are indexed by parameter types; calls lookup the correct function to forward arguments into.
Public Types
-
template<>
usingthis_t
= TypeTracker<TYPES...>¶
-
template<>
usingwrap_t
= TypeTracker_Class<REAL_T, get_type_index<REAL_T, TYPES...>()>¶
Public Functions
-
TypeTracker
()¶
-
TypeTracker
(const TypeTracker&)¶
-
TypeTracker
(TypeTracker&&)¶
-
TypeTracker &
operator=
(const TypeTracker&)¶
-
TypeTracker &
operator=
(TypeTracker&&)¶
-
~TypeTracker
()¶
-
template <typename REAL_T>
wrap_t<REAL_T>Wrap
(REAL_T &&val)¶ Convert an input value into a TypeTracker_Class maintaining the value (universal version)
-
template <typename REAL_T>
wrap_t<REAL_T> *New
(REAL_T &val)¶ Create an input value in a TypeTracker_Class maintaining the value (reference version)
-
template <typename REAL_T>
wrap_t<REAL_T> *New
(REAL_T &&val)¶ Create an input value in a TypeTracker_Class maintaining the value (move version)
-
template <typename TEST_T>
boolIsType
(TrackedType &tt)¶ Test if the tracked type is TEST_T.
-
template <typename TEST_T>
boolIsType
(TrackedType *tt)¶ Test if the tracked type points to TEST_T.
-
template <typename REAL_T>
REAL_TToType
(TrackedType &tt)¶ Convert the tracked type back to REAL_T. Assert that this is type safe!
-
template <typename REAL_T>
REAL_TToType
(TrackedType *tt)¶ Convert the tracked type pointer back to REAL_T. Assert that this is type safe!
-
template <typename OUT_T>
OUT_TCast
(TrackedType &tt)¶ Cast the tracked type to OUT_T. Try to do so even if NOT original type!
-
template <typename OUT_T>
OUT_TCast
(TrackedType *tt)¶ Cast the tracked type pointer to OUT_T. Try to do so even if NOT original type!
-
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... Ts>
voidRunFunction
(Ts... args)¶ Run the appropriate function based on the argument types received.
-
template <typename... Ts>
voidoperator()
(Ts... args)¶ Call TypeTracker as a function (refers call to RunFunction)
Public Members
Public Static Functions
-
static constexpr size_t
GetNumTypes
()¶ How many types are we working with?
-
static constexpr size_t
GetNumCombos
(size_t vals = 2)¶ How many combinations of V types are there?
-
static constexpr size_t
GetCumCombos
(size_t vals = 2)¶ How many combinations are the of the given number of types OR FEWER?
-
template <typename T>
static constexpr size_tGetID
()¶ Each type should have a unique ID.
-
template <typename T1, typename T2, typename... Ts>
static constexpr size_tGetID
()¶ Each set of types should have an ID unique within that number of types.
-
template <typename... Ts>
static constexpr size_tGetComboID
()¶ A ComboID should be unique across all size combinations.
-
static size_t
GetTrackedID
(const TrackedType &tt)¶ A Tracked ID is simply the unique ID of the type being tracked.
-
template <typename... Ts>
static size_tGetTrackedID
(const TrackedType &tt1, const TrackedType &tt2, const Ts&... ARGS)¶ Or set of types being tracked…
-
static size_t
GetTrackedID
(TrackedType *tt)¶ We should also about able to use a pointer to access tracked IDs.
-
template <typename... Ts>
static size_tGetTrackedID
(TrackedType *tt1, TrackedType *tt2, Ts *... ARGS)¶ A set of pointers to access tracked IDs.
-
template <typename... Ts>
static constexpr size_tGetTrackedComboID
(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<>
-
template <typename REAL_T, size_t ID>
structTypeTracker_Class
: public emp::TrackedType¶ - #include <TypeTracker.h>
The derived classes to be tracked should inherit from TypeTracker_Class<ID> where ID is the position in the type list for TypeTracker. Note: this value can be obtained dyanmically at compile type by using TypeTracker<…>::GetID<TYPE>()
Public Types
-
template<>
usingreal_t
= REAL_T¶
Public Functions
-
TypeTracker_Class
(const REAL_T &in)¶
-
TypeTracker_Class
(REAL_T &&in)¶
-
TypeTracker_Class
(const TypeTracker_Class&)¶
-
TypeTracker_Class
(TypeTracker_Class&&)¶
-
TypeTracker_Class &
operator=
(const TypeTracker_Class&)¶
-
TypeTracker_Class &
operator=
(TypeTracker_Class&&)¶
-
virtual size_t
GetTypeTrackerID
() const¶
Public Members
-
REAL_T
value
¶
-
template<>
Unit Testing¶
Macros to facilitate unit testing.
- 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
- 2015-2017
- Note
- Status: technically DEPRECATED (now using Catch, but may revert back)
Vector Utilities¶
A set of simple functions to manipulate emp::vector.
- 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
- 2017-2018
- Note
- Status: BETA
-
namespace
emp
If we are in emscripten, make sure to include the header.
This file contains extra analysis tools to use with systematics managers that have non-null DATA_TYPES.
- 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
- 2018
This file contains functions for adding additional data files to Worlds.
- 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
- 2018
Functions
-
template <typename T>
intFindValue
(const emp::vector<T> vec, const T &val, size_t start_pos = 0)¶ Return the first position of a value in a vector (or -1 if none exists)
-
template <typename T>
boolHas
(const emp::vector<T> vec, const T &val)¶ Return whether a value exists in a vector.s.
-
template <typename T>
voidPrint
(const emp::vector<T> &v, std::ostream &os = std::cout, const std::string &spacer = " ")¶ Print the contects of a vector.
-
template <typename T>
size_tFindIndex
(const T &v, const std::function<bool(typename T::value_type, typename T::value_type)> &fun)¶ Find the index with the “optimal” value (picks first in cases of a tie).
- Parameters
v
: Any object allowing indexing (e.g. vector, array, etc.)fun
: Comparison function; returns true if the first value os more optimal than second.
-
template <typename T>
size_tFindMinIndex
(const T &v)¶ Find the index with the minimal value (picks first in cases of a tie).
-
template <typename T>
size_tFindMaxIndex
(const T &v)¶ Find the index with the maximal value (picks first in cases of a tie).
-
template <typename T, typename... Ts>
voidSort
(emp::vector<T> &v, Ts... args)¶ A quick shortcut for sorting a vector.
-
template <typename T>
emp::vector<T>Slice
(emp::vector<T> vec, int start, int stop)¶ Returns a vector containing a chunk of elements from
- Parameters
vec
: starting atstart
: and going up to but not includingstop.
:
-
constexpr size_t
tree_left
(size_t id)¶ Tree manipulation in vectors.
-
constexpr size_t
tree_right
(size_t id)¶
-
constexpr size_t
tree_parent
(size_t id)¶
Getting started with Empirical development¶
Contents
This document is intended to help those just getting started with Empirical development. It details the initial one-time dependency installs and any similar routines necessary to get started with development.
Start by making your own copy of Empirical and setting yourself up for development; then, build Empirical and run the tests; and finally, claim an issue and start developing!
If you’re unfamiliar with git and branching in particular, check out the git-scm book.
One-time Preparation¶
Get a GitHub account.
(We use GitHub to manage Empirical contributions.)
Fork github.com/devosoft/Empirical.
Visit that page, and then click on the ‘fork’ button (upper right).
This makes a copy of the Empirical source code in your own GitHub account. If you have contributor permissions to the main Empirical library, this step is optional (you can instead develop on a branch within the main repo).
Clone your copy of Empirical to your local development environment.
Your clone URL should look something like this:
https://github.com/bocajnotnef/Empirical.git
and the UNIX shell command should be:
git clone https://github.com/bocajnotnef/Empirical.git
(This makes a local copy of Empirical on your development machine.)
Add a git reference to the Empirical repository:
cd Empirical git remote add upstream https://github.com/devosoft/Empirical.git cd ../
(This makes it easy for you to pull down the latest changes in the main repository.)
Install the development dependencies.
Unix users
Install the python virtualenv, pip, gcc, and g++, bison, flex
On recent Debian and Ubuntu this can be done with:
sudo apt-get install python-virtualenv python-pip gcc g++ git gcovr bison flex
OS X users and others may need to download virtualenv first:
curl -O https://pypi.python.org/packages/source/v/virtualenv/virtualenv-1.11.6.tar.gz tar xzf virtualenv* cd virtualenv-*; python2.7 virtualenv.py ../env; cd ..
Building Empirical and running the tests¶
Activate (or re-activate) the virtualenv (necessary only for building documentation):
source third-party/env/bin/activate
You can run this many times without any ill effects.
(This puts you in the development environment.)
Run the tests:
make test
Congratulations! You’re ready to develop!
Claiming an issue and starting to develop¶
Find an open issue and claim it.
Once you’ve found an issue you like, make sure that no one has been assigned to it (see “assignee”, bottom right near “notifications”). Then, add a comment “I am working on this issue.” You’ve staked your claim!
(We’re trying to avoid having multiple people working on the same issue.)
In your local copy of the source code, update your master branch from the main Empirical master branch:
git checkout master git pull upstream master
(This pulls in all of the latest changes from whatever we’ve been doing on Empirical.)
It is possible that when you do a git pull you will get a “merge conflict” – This is what happens when something changed in the branch you’re pulling in in the same place you made a change in your local copy.
Git will complain loudly about merges and tell you specifically in which files they occurred. If you open the file, you’ll see something vaguely like this in the place where the merge occurred:
<<<<<<< HEAD Changes made on the branch that is being merged into. In most cases, this is the branch that you have currently checked out ======= Changes made on the branch that is being merged in, almost certainly master. >>>>>>> abcde1234
Though there are a variety of tools to assist with resolving merge conflicts they can be quite complicated at first glance and it is usually easy enough to manually resolve the conflict.
To resolve the conflict you simply have to manually ‘meld’ the changes together and remove the merge markers.
After this you’ll have to add and commit the merge just like any other set of changes. It’s also recommended that you run tests.
Create a new branch and link it to your fork on GitHub:
git checkout -b fix/brief_issue_description git push -u origin fix/brief_issue_description
where you replace “brief_issue_description” with 2-3 words, separated by underscores, describing the issue.
(This is the set of changes you’re going to ask to be merged into Empirical.)
Make some changes and commit them.
Though this will largely be issue-dependent the basics of committing are simple. After you’ve made a cohesive set of changes, run the command git status. This will display a list of all the files git has noticed you changed. A file in the ‘untracked’ section are files that haven’t existed previously in the repository but git has noticed.
To commit changes you have to ‘stage’ them–this is done by issuing the following command:
git add path/to/file
If you have a large quantity of changes and you don’t want to add each file manually you can do
git add --patch
which will display each set of changes to you before staging them for commit.Once you have staged your changes, it’s time to make a commit:
git commit
Git will then open your default console text editor to write a commit message – this is a short (typically 1-3 sentence) description of the changes you’ve made. Please make your commit message informative but concise – these messages become part of the ‘official’ history of the project.
Once your changes have been committed, push them up to the remote branch:
git push
If this is your first commit on a new branch git will error out, telling you the remote branch doesn’t exist – This is fine, as it will also provide the command to create the branch. Copy/paste/run and you should be set.
Periodically update your branch from the main Empirical master branch:
git pull upstream master
(This pulls in all of the latest changes from whatever we’ve been doing on the upstream branch- important especially during periods of fast change or for long-running pull requests.)
Run the tests and/or build the docs before pushing to GitHub:
make doc test
Make sure they all pass!
Push your branch to your own GitHub fork:
git push origin
(This pushes all of your changes to your own fork.)
Repeat until you’re ready to merge your changes into “official” Empirical.
Set up a Pull Request asking to merge things into the central Empirical repository.
In a Web browser, go to your GitHub fork of Empirical, e.g.:
https://github.com/bocajnotnef/Empirical
and you will see a list of “recently pushed branches” just above the source code listing. On the right side of that should be a “Compare & pull request” green button. Click on it!
Now:
- add a descriptive title (“updated tests for XXX”)
- put the issue number in the comment (“fixes issue #532”)
then click “Create pull request.”
(This creates a new issue where we can all discuss your proposed changes; the Empirical team will be automatically notified and you will receive e-mail notifications as we add comments. See GitHub flow for more info.)
Paste in the committer checklist from Coding guidelines and review checklist and, after its pasted in, check off as many of the boxes as you can.
As you add new commits to address bugs or formatting issues, you can keep pushing your changes to the pull request by doing:
git push origin
If we request changes, return to the step “Make some changes and commit them” and go from there. Any additional commits you make and push to your branch will automatically be added to the pull request (which is pretty dang cool.)
After your first issue is successfully merged…¶
You’re now an experienced GitHub user! Go ahead and take some more tasks; you can broaden out beyond the low hanging fruit if you like.
Your second contribution…¶
Here are a few pointers on getting started on your second (or third, or fourth, or nth contribution).
So, assuming you’ve found an issue you’d like to work on there are a couple things to do to make sure your local copy of the repository is ready for a new issue–specifically, we need to make sure it’s in sync with the remote repository so you aren’t working on a old copy. So:
git checkout master
git fetch --all
git pull
This puts you on the latest master branch and pulls down updates from GitHub with any changes that may have been made since your last contribution (usually including the merge of your last contribution). Then we merge those changes into your local copy of the master branch.
Now, you can go back to Claiming an issue and starting to develop.
Pull request cleanup (commit squashing)¶
Submitters are invited to reduce the numbers of commits in their pull requests either via git rebase -i upstream/master or this recipe:
git pull # make sure the local is up to date
git pull upstream master # get up to date
# fix any merge conflicts
git status # sanity check
git diff upstream/master # does the diff look correct? (no merge markers)
git reset --soft upstream/master # un-commit the differences from dib/master
git status # sanity check
git commit --all # package all differences in one commit
git status # sanity check
git push # should fail
git push --force # override what's in GitHub's copy of the branch/pull request
Coding guidelines and review checklist¶
This document is for those who want to contribute code or documentation fixes to the Empirical project and describes our coding standards as well as our code review process.
This document has been adapted from the khmer project
C++ standards¶
We use C++11 features throughout the project and currently that is the de-facto standard version to use.
All code should be in header files for ease of inclusion into Emscripten projects.
Files that define a single class should be named after that class. Files that define sets of functions or multiple classes should have an all-lowercase name that describes its contents.
All files and all directories must be levelized. This is partly enforced through all files being headerfiles (and thus we cannot have circular dependencies), but for clean coding practices (and easy of unit testing) whole directories should not refer to each other bidirectionally either. See Large-Scale C++ Software Design by John Lakos for a strong pro-levelization argument.
In-code identifier formatting is always hard to settle upon. The guidelines below are for consistency.
- Variable names should be all_lowercase, with words separated by underscores
- Function names should be CamelCase() unless they are meant to mimic a function from the C++ standard library, at which point they can be all_lowercase to fit in.
- User-defined types should be CamelCase
- Constants should be ALL_UPPERCASE, with words separated by underscores
- Template parameters should be ALL_UPPERCASE.
- Typedefs should match the casing of the types they are aliasing. For example, a typedef on a template parameter might be all uppercase, while a typedef on a user-defined type should be CamelCase.
Guidelines based on Emscripten Limitations¶
- Try to avoid use of 64-bit integers (that is, the “long long” type). Emscripten has to emulate these and they can cause a notable slowdown.
- Do not rely on exceptions when possible. Emscripten is slow at dealing with them and they can slow down code even when not triggered.
- Do not write multi-threaded code that uses shared state. Javascript cannot (yet) handle such code and as such Emscripten cannot compile it. Note that Emscripten does have experimental support of pthreads.
- Obviously, do not use any architecture-specific tricks, such as assuming endianness, doing unaligned reads or writes, directly accessing registers, etc.
Please see the Emscripten doc page for a full list.
General Standards¶
All plain-text files should have line widths of 100 characters or less unless that is unsupported for the particular file format.
All contributions should have their spelling checked before being committed to the codebase.
Vim users can run:
:setlocal spell spelllang=en_us
to automagically check the spelling within the file being edited.
Checklist¶
Copy and paste the following into a pull request comment when it is ready for review:
- [ ] Is it mergeable?
- [ ] Did it pass the tests?
- [ ] Does 'make doc' succeed?
- [ ] If you added code, is it tested? Look at the output for 'make diff-cover'
- [ ] Was a spellchecker run on the source code and documentation after
changes were made?
It’s expected that before requesting a code review the author of the PR will have checked all these things on their own. It’s also expected that whomever reviews the PR will check these individual items as well. Though the CI runs most of these and will pass/fail the PR accordingly it is not infallible and the whole point of having a code review process is to have human eyes go over the changes to the codebase.
Empirical Documentation Documentation¶
This is a quick primer on how to document things within Empirical.
Empirical makes use of the Sphinx documentation system based off of XML information gathered from Doxygen via a plugin named Breathe. This means that Doxygen will automatically build documentation for anything written in a C++ source file and Sphinx will be used to organize how that documentation is displayed.
This primer will be broken up into two sections: 1) how to comment your code so that Doxygen can automatically pull it out and 2) how to structure the rst files in the doc/ directory so that Sphinx can construct the docs.
How to Comment for Doxygen Autodoc¶
Doxygen has an entire documentation section on how to comment your code. We’ll provide a trimmed version here so that you can get started quickly.
Doxygen will examine all comments to determine if they are documentation comments or just code comments. To make a documentation comment you must add either an extra * or /, depending on the kind of comment:
/** This is a documentation comment
across several lines
This comment will be associated with the function immediately following.
*/
void somefunc(sometype param)
{
}
// this is a comment that doxygen will ignore
// note how it only has two leading slashes, like a normal comment
/// This is a comment that will be included in the documentation
/// Note the extra leading slash
/// Huzzah, documentation
One thing to note, Doxygen requires a minimum of three triple slash’d lines before a block is considered documentation:
/// this line will be ignored
int somefunc() { return 5;}
///
/// This line will be included
///
void otherfunc() {;};
If you wish to make a more visible comment block, e.g. a header for a class, then you may do something like the following:
/********************************************//**
* Here is some text inside a visible block
***********************************************/
Note that Doxygen will view this as any other documentation comment and will not render it any differently than a ‘normal’ documentation comment–it is simply more visible within the source code.
How to include Doxygen’s autodocs within Sphinx files¶
Through the use of the Breathe extension it is incredibly easy to include Doxygen autodocs within a Sphinx documentation file.
Suppose we have a c++ implementation file name potato.h
that has inline comment documentation
as detailed above and that potato.h
is a component of a module named ingredients
that was just
created, and you wish to document them.
To do this you must create a file within the Empirical Library documentation source to hold the module’s documentation:
touch doc/library/ingredients.rst
Within ingredients.rst
you can make an introduction to the module, etc., and then add in the
sphinx directives to include autodocumentation. Your ingredients.rst
file should look
something like the following:
This is the ingredients documentation!
======================================
This is a very short introduction.
**potato.h**
.. doxygenfile:: potato.h
:project: Empirical
When the docs are built Sphinx will automatically pull the available documentation from Doxygen’s XML files to construct the docs.
Additional directives exist to include autodocumentaiton from different levels, the full breakdown of which is available within the Breathe Documentation.
How to add docs to the Sphinx documentation¶
Sphinx is the system used to generate the developer guide and similar reference documentation. A primer to using ReStructured Text, the markup language used by Sphinx, can be found here. You can also look at any of the .rst files in the doc/ directory to get a feel for how thinks work.
New documents must be included in the ‘toctree’ in the index.rst
file for the directory the added
file lives in. For example, if you add CowFacts.rst
to the CoolFacts/
directory you must add
CowFacts.rst
to the toctree found in CoolFacts/CowFacts.rst
:
Cool Facts
==========
A bunch of cool facts!
.. toctree ::
AnteaterFacts
BirdFacts
CowFacts
To build the documentation, you must make sure you source the python virtual environment where
Sphinx lives. If you used the install-dependencies
maketarget (recommended) then you should just
have to do source third-party/env/bin/activate
and then make doc
and the documentation will
regenerate.
Guide to Testing in Empirical¶
This document details how testing works in Empirical, both for writing and understanding tests. Empirical makes use of the Catch testing framework, the documentation of which is available here.
Running Tests¶
- In the root directory of Empirical, use the maketarget
test
, like so:: - make test
The tests will compile and execute automatically, and you should see output that looks something like this:
cd tests && make test
make[1]: Entering directory '/home/jgf/git/Empirical/tests'
g++ -std=c++11 test_driver.cc -o test.o
# Execute tests
./test.o
===============================================================================
All tests passed (562 assertions in 27 test cases)
If you wish to see detailed coverage data you can use the maketarget coverage
:
make coverage
Again, the tests will compile (this time with coverage flags) and execute, generating coverage data. This data will be analyzed and stuffed into helpful HTML files. You’ll see output that initially looks like the normal tests, followed by a lot of output, and then:
Overall coverage rate:
lines......: 81.7% (946 of 1158 lines)
functions..: 87.0% (463 of 532 functions)
The HTML info will give breakdowns on line-by-line coverage on each file. It is highly recommended that you consult these to verify that code is well covered. To view these files, open tests/html/index.html in your favorite browser.
Writing Tests¶
It is required that contributions to the Empirical library have test coverage. Though writing tests can be a complex task in some cases the Catch testing framework is extremely easy to use.
In general the best way to understand how to write tests is to look at the existing tests. I
recommend skimming through test_tools.cc
for an overview.
If you are creating a new test file you will need to include the file you’ve made in the
test_driver.cc
file. That is, suppose you create a file test_potatoes.cc
. You will then need
to edit test_driver.cc
so that it looks something like this:
#define CATCH_CONFIG_MAIN
#include "../third-party/catch/single_include/catch.hpp"
#include "test_tools.cc"
#include "test_geometry.cc"
#include "test_scholar.cc"
#include "test_potatoes.cc"
To write a test case you simply use the TEST_CASE
macro provided by Catch:
TEST_CASE("Test name goes here", "[test classification here]")
{
// body of test
}
Within a test case you can use the REQUIRE
macro like an assert, to require certain conditions
within the test:
REQUIRE(1==1); // will pass, obviously
REQUIRE(1==0); // will fail, and Catch will complain
If a REQUIRE
fails, Catch will expand it for you to show you what was compared. Supposing we
have a test case like the following:
TEST_CASE("testing tests", "[demo]")
{
bool a = false, b = true;
REQUIRE(a == b);
}
It would execute like so:
demo.cc:4: FAILED:
REQUIRE( a == b )
with expansion:
false == true
===============================================================================
test cases: 1 | 1 failed
assertions: 1 | 1 failed
This allows for easier debugging of failed tests.
Catch provides several different frameworks for constructing test cases which are detailed within their documentation.