API Reference¶
Loading and saving Demes graphs¶
- demes.load(filename, *, format='yaml')[source]¶
Load a graph from a YAML or JSON file. The keywords and structure of the input are defined by the Specification.
- Parameters
filename (Union[str, os.PathLike, FileLike]) – The path to the file to be loaded, or a file-like object with a
read()
method.format (str) – The format of the input file. Either “yaml” or “json”.
- Returns
A graph.
- Return type
- demes.load_asdict(filename, *, format='yaml')[source]¶
Load a YAML or JSON file into a dictionary of nested objects. The keywords and structure of the input are defined by the Specification.
- Parameters
filename (Union[str, os.PathLike, FileLike]) – The path to the file to be loaded, or a file-like object with a
read()
method.format (str) – The format of the input file. Either “yaml” or “json”.
- Returns
A dictionary of nested objects, with the same data model as the YAML or JSON input.
- Return type
- demes.loads(string, *, format='yaml')[source]¶
Load a graph from a YAML or JSON string. The keywords and structure of the input are defined by the Specification.
- demes.loads_asdict(string, *, format='yaml')[source]¶
Load a YAML or JSON string into a dictionary of nested objects. The keywords and structure of the input are defined by the Specification.
- demes.load_all(filename)[source]¶
Generate graphs from a YAML document stream. Documents must be separated by the YAML document start indicator,
---
. The keywords and structure of each document are defined by the Specification.- Parameters
filename (Union[str, os.PathLike, FileLike]) – The path to the file to be loaded, or a file-like object with a
read()
method.- Returns
A generator of graphs.
- Return type
Generator[demes.Graph, None, None]
- demes.dump(graph, filename, *, format='yaml', simplified=True)[source]¶
Dump the specified graph to a file. The keywords and structure of the output are defined by the Specification.
- Parameters
graph (Graph) – The graph to dump.
filename (Union[str, os.PathLike, FileLike]) – Path to the output file, or a file-like object with a
write()
method.format (str) – The format of the output file. Either “yaml” or “json”.
simplified (bool) – If True, outputs a simplified graph. If False, outputs a fully-qualified graph.
- demes.dumps(graph, *, format='yaml', simplified=True)[source]¶
Dump the specified graph to a YAML or JSON string. The keywords and structure of the output are defined by the Specification.
- demes.dump_all(graphs, filename, *, simplified=True)[source]¶
Dump the specified graphs to a multi-document YAML file or output stream.
- Parameters
graphs – An iterable of graphs to dump.
filename (Union[str, os.PathLike, FileLike]) – Path to the output file, or a file-like object with a
write()
method.simplified (bool) – If True, outputs simplified graphs. If False, outputs fully-qualified graphs.
Building Demes graphs¶
- class demes.Builder(*, description=None, time_units='generations', generation_time=None, doi=None, defaults=None, metadata=None)[source]¶
The Builder provides a set of convenient methods for incrementally constructing a deme graph. The state of the graph is stored internally as a dictionary of objects following Demes’ data model, and may be converted into a fully-resolved
Graph
object using theresolve()
method.- Variables
data (dict) –
The data dictionary of the graph’s current state. The objects nested within this dictionary follow Demes’ data model, as described in the Specification.
Note
Users may freely modify the data dictionary, as long as the data model is not violated.
- add_deme(name, *, description=None, ancestors=None, proportions=None, start_time=None, epochs=None, defaults=None)[source]¶
Add a deme. Ancestor demes must be added before their children.
- Parameters
name (str) – A string identifier for the deme.
description (str) – A description of the deme. May be
None
.ancestors (list[str]) – List of deme names for the deme’s ancestors. This may be
None
, indicating the deme has no ancestors.proportions (list[float]) – If
ancestors
is notNone
, this indicates the proportions of ancestry from each ancestor. This list has the same length asancestors
, and must sum to 1.start_time (float) – The deme’s start time.
epochs (list[dict]) – List of epoch dictionaries. Each dictionary follows the data model for an epoch.
- add_migration(*, rate=None, demes=<object object>, source=<object object>, dest=<object object>, start_time=None, end_time=None)[source]¶
Add continuous symmetric migrations between all pairs of demes in a list, or alternately, add asymmetric migration from one deme to another. Source and destination demes follow the forwards-in-time convention, so that the migration rate refers to the movement of individuals from the
source
deme to thedest
deme.- Parameters
demes (list[str]) – list of deme names. Migration is symmetric between all pairs of demes in this list. If not specified, migration will be asymmetric (and
source
anddest
must be given).source (str) – The name of the source deme.
dest (str) – The name of the destination deme.
rate (float) – The rate of migration per generation.
start_time (float) – The time at which the migration rate is enabled. If
None
, the start time is defined by the earliest time at which the demes coexist.end_time (float) – The time at which the migration rate is disabled. If
None
, the end time is defined by the latest time at which the demes coexist.
- add_pulse(*, sources=None, dest=None, proportions=None, time=None)[source]¶
Add a pulse of migration at a fixed time. Source and destination demes follow the forwards-in-time convention.
- classmethod fromdict(data)[source]¶
Make a Builder object from an existing data dictionary.
- Parameters
data (MutableMapping) – The data dictionary to initialise the graph’s state. The objects nested within this dictionary must follow Demes’ data model, as described in the Specification.
- Returns
The new Builder object.
- Return type
Working with Demes graphs¶
- class demes.Graph(*, description=None, time_units, generation_time=None, doi=NOTHING, metadata=NOTHING)[source]¶
The Graph class provides a high-level API for working with a demographic model. A Graph object matches Demes’ data model, with a small number of additional redundant attributes that make the Graph a more convenient object to use when inspecting a model’s properties.
- Variables
description (str) – A human readable description of the demography. May be
None
.time_units (str) – The units of time used for the demography. This is commonly
years
orgenerations
, but can be any string. This field is intended to be useful for documenting a demography, but the actual value provided here should not be relied upon.generation_time (float) – The generation time of demes, in units given by the
time_units
parameter. Concretely, dividing all times bygeneration_time
will convert the graph to have time units in generations. Ifgeneration_time
isNone
, the units are assumed to be in generations already. See also:in_generations()
.doi (list[str]) – If the graph describes a published demography, the DOI(s) should be be given here as a list.
metadata (dict) – A dictionary of arbitrary additional data.
migrations (list[AsymmetricMigration]) – The continuous migrations for the demographic model.
pulses (list[Pulse]) – The migration pulses for the demography.
- __contains__(deme_name)[source]¶
Check if the graph contains a deme with the specified name.
graph = demes.load("gutenkunst_ooa.yaml") if "CHB" in graph: print("Deme CHB is in the graph")
- __getitem__(deme_name)[source]¶
Get the
Deme
with the specified name.graph = demes.load("gutenkunst_ooa.yaml") yri = graph["YRI"] print(yri)
- assert_close(other, *, rel_tol=1e-09, abs_tol=1e-12)[source]¶
Raises AssertionError if the object is not equal to
other
, up to a numerical tolerance. Furthermore, the following implementation details are ignored during the comparison:The graphs’
description
anddoi
attributes.The order in which
migrations
were specified.The order in which
demes
were specified.The order in which a deme’s
ancestors
were specified.
- Parameters
other (
Graph
) – The graph to compare against.rel_tol (float) – The relative tolerance permitted for numerical comparisons. See documentation for
math.isclose()
.abs_tol (float) – The absolute tolerance permitted for numerical comparisons. See documentation for
math.isclose()
.
- discrete_demographic_events()[source]¶
Classify each discrete demographic event as one of the following:
Pulse
,Split
,Branch
,Merge
, orAdmix
. If a deme has more than one ancestor, then that deme is created by a merger or an admixture event, which are differentiated by end and start times of those demes. If a deme has a single predecessor, we check whether it is created by a branch (start time != predecessor’s end time), or split.Note
By definition, the discrete demographic events do not include migrations, as they are continuous events.
- classmethod fromdict(data)[source]¶
Return a graph from a dict representation. The inverse of
asdict()
.
- isclose(other, *, rel_tol=1e-09, abs_tol=1e-12)[source]¶
Returns true if the graph and
other
implement essentially the same demographic model. Numerical values are compared using themath.isclose()
function, from which this method takes its name. Furthermore, the following implementation details are ignored during the comparison:The graphs’
description
anddoi
attributes.The order in which
migrations
were specified.The order in which
demes
were specified.The order in which a deme’s
ancestors
were specified.
- Parameters
other (
Graph
) – The graph to compare against.rel_tol (float) – The relative tolerance permitted for numerical comparisons. See documentation for
math.isclose()
.abs_tol (float) – The absolute tolerance permitted for numerical comparisons. See documentation for
math.isclose()
.
- Returns
True if the two graphs implement the same model, False otherwise.
- Return type
- migration_matrices()[source]¶
Get the migration matrices and the end times that partition them.
Returns a list of matrices, one for each time interval over which migration rates do not change, in time-descending order (from most ancient to most recent). For a migration matrix list \(M\), the migration rate is \(M[i][j][k]\) from deme \(k\) into deme \(j\) during the \(i\) ‘th time interval. The order of the demes’ indices in each matrix matches the order of demes in the graph’s deme list (I.e. deme \(j\) corresponds to
Graph.demes[j]
).There is always at least one migration matrix in the list, even when the graph defines no migrations.
A list of end times to which the matrices apply is also returned. The time intervals to which the migration rates apply are an open-closed interval
(start_time, end_time]
, where the start time of the first matrix isinf
and the start time of subsequent matrices match the end time of the previous matrix in the list.Note
The last entry of the list of end times is always
0
, even when all demes in the graph go extinct before time0
.graph = demes.load("gutenkunst_ooa.yaml") mm_list, end_times = graph.migration_matrices() start_times = [math.inf] + end_times[:-1] assert len(mm_list) == len(end_times) == len(start_times) deme_ids = {deme.name: j for j, deme in enumerate(graph.demes)} j = deme_ids["YRI"] k = deme_ids["CEU"] for mm, start_time, end_time in zip(mm_list, start_times, end_times): print( f"CEU -> YRI migration rate is {mm[j][k]} during the " f"time interval ({start_time}, {end_time}]" )
- predecessors()[source]¶
Returns the predecessors (ancestors) for all demes in the graph. If
graph
is aGraph
, a NetworkX digraph of predecessors can be obtained as follows.import networkx as nx pred = nx.from_dict_of_lists(graph.predecessors(), create_using=nx.DiGraph)
Warning
The predecessors do not include information about migrations or pulses.
- successors()[source]¶
Returns the successors (child demes) for all demes in the graph. If
graph
is aGraph
, a NetworkX digraph of successors can be obtained as follows.import networkx as nx succ = nx.from_dict_of_lists(graph.successors(), create_using=nx.DiGraph)
Warning
The successors do not include information about migrations or pulses.
- class demes.Deme(*, name, description, start_time, ancestors, proportions, epochs)[source]¶
A collection of individuals that have a common set of population parameters.
- Variables
name (str) – A concise string that identifies the deme.
description (str) – A description of the deme. May be
None
.start_time (float) – The time at which the deme begins to exist.
ancestors (list[str]) – List of deme names for the deme’s ancestors. This may be
None
, indicating the deme has no ancestors.proportions (list[float]) – If
ancestors
is notNone
, this indicates the proportions of ancestry from each ancestor. This list has the same length asancestors
, and must sum to 1.epochs (list[Epoch]) – A list of epochs, which define the population size(s) of the deme. The deme must be created with all epochs listed.
- assert_close(other, *, rel_tol=1e-09, abs_tol=1e-12)[source]¶
Raises AssertionError if the object is not equal to
other
, up to a numerical tolerance. Compares values of the following objects:name
,ancestors
,proportions
, epochs.- Parameters
other (
Deme
) – The deme to compare against.rel_tol (float) – The relative tolerance permitted for numerical comparisons. See documentation for
math.isclose()
abs_tol (float) – The absolute tolerance permitted for numerical comparisons. See documentation for
math.isclose()
.
- property end_time¶
The end time of the deme’s existence.
- isclose(other, *, rel_tol=1e-09, abs_tol=1e-12)[source]¶
Returns true if the deme is equal to the
other
deme. For more information seeassert_close()
.- Parameters
other (
Deme
) – The deme to compare against.rel_tol (float) – The relative tolerance permitted for numerical comparisons. See documentation for
math.isclose()
abs_tol (float) – The absolute tolerance permitted for numerical comparisons. See documentation for
math.isclose()
.
- Returns
True if the two demes are equivalent, False otherwise.
- Return type
- property time_span¶
The time span over which the deme exists.
- class demes.Epoch(*, start_time, end_time, start_size, end_size, size_function, selfing_rate=0, cloning_rate=0)[source]¶
Population size parameters for a deme in a specified time period. Times follow the forwards-in-time convention (time values increase from the present towards the past). The start time of the epoch is the more ancient time, and the end time is more recent, so that the start time must be greater than the end time
- Variables
start_time (float) – The start time of the epoch.
end_time (float) – The end time of the epoch (must be specified).
start_size (float) – Population size at
start_time
.end_size (float) – Population size at
end_time
. Ifstart_size != end_size
, the population size changes monotonically between the start and end times.size_function (str) –
The size change function. This is either
constant
,exponential
orlinear
, though it is possible that additional values will be added in the future.constant
: the deme’s size does not change over the epoch.exponential
: the deme’s size changes exponentially fromstart_size
toend_size
over the epoch. If \(t\) is a time within the span of the epoch, the deme size \(N\) at \(t\) can be calculated as:dt = (epoch.start_time - t) / epoch.time_span r = math.log(epoch.end_size / epoch.start_size) N = epoch.start_size * math.exp(r * dt)
linear
: the deme’s size changes linearly fromstart_size
toend_size
over the epoch. If \(t\) is a time within the span of the epoch, the deme size \(N\) at \(t\) can be calculated as:dt = (epoch.start_time - t) / epoch.time_span N = epoch.start_size + (epoch.end_size - epoch.start_size) * dt
selfing_rate (float) – The selfing rate for this epoch.
cloning_rate (float) – The cloning rate for this epoch.
- assert_close(other, *, rel_tol=1e-09, abs_tol=1e-12)[source]¶
Raises AssertionError if the object is not equal to
other
, up to a numerical tolerance. Compares values of the following attributes:start_time
,end_time
,start_size
,end_size
,size_function
,selfing_rate
,cloning_rate
.- Parameters
other (
Epoch
) – The epoch to compare against.rel_tol (float) – The relative tolerance permitted for numerical comparisons. See documentation for
math.isclose()
abs_tol (float) – The absolute tolerance permitted for numerical comparisons. See documentation for
math.isclose()
.
- isclose(other, *, rel_tol=1e-09, abs_tol=1e-12)[source]¶
Returns true if the epoch and
other
epoch implement essentially the same epoch. For more information seeassert_close()
.- Parameters
other (
Epoch
) – The epoch to compare against.rel_tol (float) – The relative tolerance permitted for numerical comparisons. See documentation for
math.isclose()
abs_tol (float) – The absolute tolerance permitted for numerical comparisons. See documentation for
math.isclose()
.
- Returns
True if the two epochs are equivalent, False otherwise.
- Return type
- property time_span¶
The time span of the epoch.
Continuous demographic events¶
- class demes.AsymmetricMigration(*, source, dest, start_time, end_time, rate)[source]¶
Parameters for continuous asymmetric migration. The source and destination demes follow the forwards-in-time convention, where migrants are born in the source deme and (potentially) have children in the dest deme.
- Variables
source (str) – The source deme for asymmetric migration.
dest (str) – The destination deme for asymmetric migration.
start_time (float) – The time at which the migration rate is activated.
end_time (float) – The time at which the migration rate is deactivated.
rate (float) – The rate of migration per generation.
- assert_close(other, *, rel_tol=1e-09, abs_tol=1e-12)[source]¶
Raises AssertionError if the object is not equal to
other
, up to a numerical tolerance. Compares values of the following attributes:source
,dest
,start_time
,end_time
,rate
.- Parameters
other (AsymmetricMigration) – The migration to compare against.
rel_tol (float) – The relative tolerance permitted for numerical comparisons. See documentation for
math.isclose()
abs_tol (float) – The absolute tolerance permitted for numerical comparisons. See documentation for
math.isclose()
.
- isclose(other, *, rel_tol=1e-09, abs_tol=1e-12)[source]¶
Returns true if the migration is equal to the
other
migration. For more information seeassert_close()
.- Parameters
other (AsymmetricMigration) – The migration to compare against.
rel_tol (float) – The relative tolerance permitted for numerical comparisons. See documentation for
math.isclose()
abs_tol (float) – The absolute tolerance permitted for numerical comparisons. See documentation for
math.isclose()
.
- Returns
True if the two epochs are equivalent, False otherwise.
- Return type
Discrete demographic events¶
- class demes.Pulse(*, sources, dest, time, proportions)[source]¶
Parameters for a pulse of migration from one deme to another. Source and destination demes follow the forwards-in-time convention, of migrations born in the source deme having children in the dest deme. If more than one source is given, migration is concurrent, so that the sum of the migrant proportions must sum to less than one.
- Variables
- assert_close(other, *, rel_tol=1e-09, abs_tol=1e-12)[source]¶
Raises AssertionError if the object is not equal to
other
, up to a numerical tolerance. Compares values of the following attributes:source
,dest
,time
,proportion
.- Parameters
other (
Pulse
) – The pulse to compare against.rel_tol (float) – The relative tolerance permitted for numerical comparisons. See documentation for
math.isclose()
abs_tol (float) – The absolute tolerance permitted for numerical comparisons. See documentation for
math.isclose()
.
- isclose(other, *, rel_tol=1e-09, abs_tol=1e-12)[source]¶
Returns true if the pulse is equal to the
other
pulse. For more information seeassert_close()
.- Parameters
other (
Pulse
) – The pulse to compare against.rel_tol (float) – The relative tolerance permitted for numerical comparisons. See documentation for
math.isclose()
abs_tol (float) – The absolute tolerance permitted for numerical comparisons. See documentation for
math.isclose()
.
- Returns
True if the two pulses are equivalent, False otherwise.
- Return type
- class demes.Split(*, parent, children, time)[source]¶
Parameters for a split event, in which a deme ends at a given time and contributes ancestry to an arbitrary number of descendant demes. Note that there could be just a single descendant deme, in which case
split
is a bit of a misnomer…- Variables
- assert_close(other, *, rel_tol=1e-09, abs_tol=1e-12)[source]¶
Raises AssertionError if the object is not equal to
other
, up to a numerical tolerance. Compares values of the following attributes:parent
,children
,time
.- Parameters
other (
Split
) – The split to compare against.rel_tol (float) – The relative tolerance permitted for numerical comparisons. See documentation for
math.isclose()
abs_tol (float) – The absolute tolerance permitted for numerical comparisons. See documentation for
math.isclose()
.
- isclose(other, *, rel_tol=1e-09, abs_tol=1e-12)[source]¶
Returns true if the split is equal to the
other
split. Compares values of the following attributes:parent
,children
,time
.- Parameters
other (
Split
) – The split to compare against.rel_tol (float) – The relative tolerance permitted for numerical comparisons. See documentation for
math.isclose()
abs_tol (float) – The absolute tolerance permitted for numerical comparisons. See documentation for
math.isclose()
.
- Returns
True if the two splits are equivalent, False otherwise.
- Return type
- class demes.Branch(*, parent, child, time)[source]¶
Parameters for a branch event, where a new deme branches off from a parental deme. The parental deme need not end at that time.
- Variables
- assert_close(other, *, rel_tol=1e-09, abs_tol=1e-12)[source]¶
Raises AssertionError if the object is not equal to
other
, up to a numerical tolerance. Compares values of the following attributes:parent
,child
,time
.- Parameters
other (
Branch
) – The branch to compare against.rel_tol (float) – The relative tolerance permitted for numerical comparisons. See documentation for
math.isclose()
abs_tol (float) – The absolute tolerance permitted for numerical comparisons. See documentation for
math.isclose()
.
- isclose(other, *, rel_tol=1e-09, abs_tol=1e-12)[source]¶
Returns true if the branch is equal to the
other
branch. For more information seeassert_close()
.- Parameters
other (
Branch
) – The branch to compare against.rel_tol (float) – The relative tolerance permitted for numerical comparisons. See documentation for
math.isclose()
abs_tol (float) – The absolute tolerance permitted for numerical comparisons. See documentation for
math.isclose()
.
- Returns
True if the two branches are equivalent, False otherwise.
- Return type
- class demes.Merge(*, parents, proportions, child, time)[source]¶
Parameters for a merge event, in which two or more demes end at some time and contribute to a descendant deme.
- Variables
- assert_close(other, *, rel_tol=1e-09, abs_tol=1e-12)[source]¶
Raises AssertionError if the object is not equal to
other
, up to a numerical tolerance. Compares values of the following attributes:parents
,proportions
,child
,time
.- Parameters
other (
Merge
) – The merge to compare against.rel_tol (float) – The relative tolerance permitted for numerical comparisons. See documentation for
math.isclose()
abs_tol (float) – The absolute tolerance permitted for numerical comparisons. See documentation for
math.isclose()
.
- isclose(other, *, rel_tol=1e-09, abs_tol=1e-12)[source]¶
Returns true if the merge is equal to the
other
merge. For more information seeassert_close()
.- Parameters
other (
Merge
) – The merge to compare against.rel_tol (float) – The relative tolerance permitted for numerical comparisons. See documentation for
math.isclose()
abs_tol (float) – The absolute tolerance permitted for numerical comparisons. See documentation for
math.isclose()
.
- Returns
True if the two merges are equivalent, False otherwise.
- Return type
- class demes.Admix(*, parents, proportions, child, time)[source]¶
Parameters for an admixture event, where two or more demes contribute ancestry to a new deme.
- Variables
- assert_close(other, *, rel_tol=1e-09, abs_tol=1e-12)[source]¶
Raises AssertionError if the object is not equal to
other
, up to a numerical tolerance. Compares values of the following attributes:parents
,proportions
,child
,time
.- Parameters
other (
Admix
) – The admixture to compare against.rel_tol (float) – The relative tolerance permitted for numerical comparisons. See documentation for
math.isclose()
abs_tol (float) – The absolute tolerance permitted for numerical comparisons. See documentation for
math.isclose()
.
- isclose(other, *, rel_tol=1e-09, abs_tol=1e-12)[source]¶
Returns true if the admixture is equal to the
other
admixture. For more information seeassert_close()
.- Parameters
other (
Admix
) – The admixture to compare against.rel_tol (float) – The relative tolerance permitted for numerical comparisons. See documentation for
math.isclose()
abs_tol (float) – The absolute tolerance permitted for numerical comparisons. See documentation for
math.isclose()
.
- Returns
True if the two admixtures are equivalent, False otherwise.
- Return type
Conversion functions¶
- demes.from_ms(command, *, N0, deme_names=None)[source]¶
Convert an ms demographic model into a demes graph.
Hudson’s ms uses coalescent units for times (\(t\)), population sizes (\(x\)), and migration rates (\(M\)). These will be converted to more familiar units using the given
N0
value (\(N_0\)) according to the following rules:\[ \begin{align}\begin{aligned}\text{time (in generations)} &= 4 N_0 t\\\text{deme size (haploid individuals)} &= N_0 x\\\text{migration rate (per generation)} &= \frac{M}{4 N_0}\end{aligned}\end{align} \]- Parameters
command (str) – The ms command line.
N0 (float) – The reference population size (\(N_0\)) used to translate from coalescent units. For a
command
that specifies a \(\theta\) value with the-t theta
option, this can be calculated as \(N_0 = \theta / (4 \mu L)\), where \(\mu\) is the per-generation mutation rate and \(L\) is the length of the sequence being simulated.deme_names (list[str]) – A list of names to use for the demes. If not specified, demes will be named deme1, deme2, etc.
- Returns
The demes graph.
- Return type
- demes.to_ms(graph, *, N0, samples=None)[source]¶
Get ms command line arguments for the graph.
The order of deme IDs matches the order of demes in the graph.
- Parameters
N0 (float) – The reference population size used to translate into coalescent units. See
from_ms()
for details.samples (list(int)) – Sampling scheme that will be used with the ‘-I’ option. This is ignored for graphs with only one deme. If not specified, the sampling configuration in the returned string will need editing prior to simulation.
- Returns
The ms command line.
- Return type