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 resolved and validated demographic model.

Return type

demes.Graph

demes.load_asdict(filename, *, format='yaml')[source]#

Load a YAML or JSON file into a dictionary of nested objects.

The input is not resolved, and is not validated. The returned object may be converted into a Builder using Builder.fromdict() or converted into a Graph using Graph.fromdict().

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

dict

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.

Parameters
  • string (str) – The string to be loaded.

  • format (str) – The format of the input string. Either “yaml” or “json”.

Returns

A resolved and validated demographic model.

Return type

demes.Graph

demes.loads_asdict(string, *, format='yaml')[source]#

Load a YAML or JSON string into a dictionary of nested objects.

The input is not resolved, and is not validated. The returned object may be converted into a Builder using Builder.fromdict() or converted into a Graph using Graph.fromdict().

Parameters
  • string (str) – The string to be loaded.

  • format (str) – The format of the input string. Either “yaml” or “json”.

Returns

A dictionary of nested objects, with the same data model as the YAML or JSON input string.

Return type

dict

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 resolved and validated demographic models.

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 (demes.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, the output file follows the Human Data Model, which has many fields omitted and is thus more compact. If False, the output file is fully-resolved and follows the Machine Data Model.

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.

Parameters
  • graph (demes.Graph) – The graph to dump.

  • format (str) – The format of the output file. Either “yaml” or “json”.

  • simplified (bool) – If True, returns a string following the Human Data Model, which has many fields omitted and is thus more compact. If False, returns a string that is fully-resolved following the Machine Data Model.

Returns

The YAML or JSON string.

Return type

str

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, the output file follows the Human Data Model, which has many fields omitted and is thus more compact. If False, the output file is fully-resolved and follows the Machine Data Model.

Building Demes graphs#

class demes.Builder(*, description=None, time_units='generations', generation_time=None, doi=None, defaults=None, metadata=None)[source]#

The Builder class provides a set of convenient methods for incrementally constructing a demographic model.

The state of the demographic model is stored internally as a dictionary of objects following Demes’ Human Data Model. The content of this dictionary is not resolved and is not verified. The Builder object may be converted into a resolved and validated Graph object using the resolve() method.

Variables

data (dict) –

The data dictionary of the demographic model’s current state. The objects nested within this dictionary should follow Demes’ data model, as described in the Human Data Model schema.

Note

Users may freely modify the data dictionary, such as temporarily adding or deleting fields, as long as the Human Data Model is not violated when the resolve() method is called.

__init__(*, description=None, time_units='generations', generation_time=None, doi=None, defaults=None, metadata=None)[source]#
Parameters
  • description (str) – A human readable description of the demography.

  • time_units (str) – The units of time used for the demography. This is commonly years or generations, but can be any string.

  • generation_time (float) – The generation time of demes, in units given by the time_units parameter.

  • doi (list[str]) – If the graph describes a published demography, the DOI(s) should be be given here as a list.

  • defaults (dict) – A dictionary of default values, following the Human Data Model schema for defaults.

  • metadata (dict) – A dictionary of arbitrary additional data.

add_deme(name, *, description=None, ancestors=None, proportions=None, start_time=None, epochs=None, defaults=None)[source]#

Append a deme to the “demes” list field of the data dictionary.

If the data dictionary doesn’t contain the “demes” field, it will be added.

Parameters
  • name (str) – A string identifier for the deme.

  • description (str) – A description of the deme.

  • ancestors (list[str]) – List of deme names for the deme’s ancestors.

  • proportions (list[float]) – The proportions of ancestry from each ancestor. This list has the same length as ancestors, and must sum to 1.

  • start_time (float) – The deme’s start time.

  • epochs (list[dict]) – List of epoch dictionaries. Each dictionary follows the Human Data Model schema for an epoch object.

  • defaults (dict) – A dictionary of default deme values, following the Human Data Model schema for deme defaults.

add_migration(*, rate=None, demes=<object object>, source=<object object>, dest=<object object>, start_time=None, end_time=None)[source]#

Append a period of continuous migration to the “migrations” list field of the data dictionary.

If the data dictionary doesn’t contain the “migrations” field, it will be added. Continuous migrations may be either symmetric or asymmetric. For symmetric migrations, a list of deme names must be provided in the demes field, and the source and dest fields must not be used. For asymmetric migrations, the source and dest fields must be provided and the demes field must not be used. Source and destination demes refer to individuals migrating forwards in time.

Parameters
  • demes (list[str]) – List of deme names. If specified, migration is symmetric between all pairs of demes in this list.

  • source (str) – The name of the source deme. If specified, migration is asymmetric from this deme.

  • dest (str) – The name of the destination deme. If specified, migration is asymmetric into this deme.

  • rate (float) – The rate of migration per generation.

  • start_time (float) – The time at which the migration rate is enabled.

  • end_time (float) – The time at which the migration rate is disabled.

add_pulse(*, sources=None, dest=None, proportions=None, time=None)[source]#

Append a pulse of migration at a fixed time to the “pulses” list field of the data dictionary.

If the data dictionary doesn’t contain the “pulses” field, it will be added. Source and destination demes refer to individuals migrating forwards in time.

Parameters
  • sources (list(str)) – A list of names of the source deme(s).

  • dest (str) – The name of the destination deme.

  • proportion (list(float)) – At the instant after migration, this is the expected proportion(s) of individuals in the destination deme made up of individuals from the source deme(s).

  • time (float) – The time at which migrations occur.

classmethod fromdict(data)[source]#

Make a Builder object from an existing data dictionary.

Parameters

data (MutableMapping) – The data dictionary to initialise the Builder’s state. The objects nested within this dictionary should follow Demes’ Human Data Model, but see the note for Builder.data.

Returns

The new Builder object.

Return type

Builder

resolve()[source]#

Resolve the Builder’s data dictionary into a Graph.

Returns

The fully-resolved Graph.

Return type

Graph

Working with Demes graphs#

class demes.Graph(*, description='', time_units, generation_time=None, doi=NOTHING, metadata=NOTHING)[source]#

The Graph class is a resolved and validated representation of a demographic model.

A Graph object matches Demes’ Machine 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. Graph objects are not intended to be constructed directly—demographic models should instead be loaded from a YAML document, or constructed programmatically using the Builder API.

A demographic model can be thought of as an acyclic directed graph, where each deme is a vertex and each ancestor/descendant relationship is a directed edge. See the predecessors() and successors() methods for conversion to the NetworkX graphical representation.

Variables
  • description (str) – A human readable description of the demography.

  • time_units (str) – The units of time used for the demography. This is commonly years or generations, 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 by generation_time will convert the graph to have time units in generations. See also: in_generations().

  • doi (list[str]) – A list of publications that describe the demographic model.

  • metadata (dict) – A dictionary of arbitrary additional data.

  • demes (list[Deme]) – The demes in the demographic model.

  • migrations (list[AsymmetricMigration]) – The continuous asymmetric migrations for the demographic model.

  • pulses (list[Pulse]) – The instantaneous pulse migrations for the demographic model.

__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")
Parameters

deme_name (str) – The name of the deme.

Return type

bool

Returns

True if the deme is in the graph, False otherwise.

__getitem__(deme_name)[source]#

Get the Deme with the specified name.

graph = demes.load("gutenkunst_ooa.yaml")
yri = graph["YRI"]
print(yri)
Parameters

deme_name (str) – The name of the deme.

Return type

Deme

Returns

The deme.

asdict(keep_empty_fields=True)[source]#

Return a fully-resolved dict representation of the graph.

Returns

A data dictionary following the Machine Data Model.

Return type

dict

asdict_simplified()[source]#

Return a simplified dict representation of the graph.

Returns

A data dictionary following the Human Data Model.

Return type

dict

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 and doi 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, or Admix. 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.

Returns

A dictionary of lists of discrete demographic events. The following keys are defined: “pulses”, “splits”, “branches”, “mergers”, “admixtures”, and their values are the corresponding lists of Pulse, Split, Branch, Merge, and Admix objects.

Return type

dict[str, list]

classmethod fromdict(data)[source]#

Return a graph from a data dictionary.

Parameters

data (dict) – A data dictionary following either the Human Data Model or the Machine Data Model.

Returns

A resolved and validated demographic model.

Return type

Graph

in_generations()[source]#

Return a copy of the graph with times in units of generations.

Returns

A demographic model with time_units in “generations”.

Return type

Graph

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 the math.isclose() function, from which this method takes its name. Furthermore, the following implementation details are ignored during the comparison:

  • The graphs’ description and doi 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

bool

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 is inf 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 time 0.

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}]"
    )
Returns

A 2-tuple of (mm_list, end_times), where mm_list is a list of migration matrices, and end_times are a list of end times for each matrix.

Return type

tuple[list[list[list[float]]], list[float]]

predecessors()[source]#

Returns the predecessors (ancestors) for all demes in the graph. If graph is a Graph, 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.

Returns

A NetworkX compatible dict-of-lists graph of the demes’ predecessors.

Return type

dict[str, list[str]]

successors()[source]#

Returns the successors (child demes) for all demes in the graph. If graph is a Graph, 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.

Returns

A NetworkX compatible dict-of-lists graph of the demes’ successors.

Return type

dict[str, list[str]]

class demes.Deme(*, name, description='', start_time, ancestors, proportions, epochs)[source]#

A collection of individuals that have a common set of population parameters.

Deme objects are not intended to be constructed directly.

Variables
  • name (str) – A concise string that identifies the deme.

  • description (str) – A description of the deme.

  • start_time (float) – The time at which the deme begins to exist.

  • ancestors (list[str]) – List of deme names for the deme’s ancestors.

  • proportions (list[float]) – The proportions of ancestry from each ancestor, ordered to correspond with the same order as the ancestors list. If there are one or more ancestors, the proportions sum to 1.

  • epochs (list[Epoch]) – A list of epochs that span the time interval over which the deme exists. Epoch time intervals are non-overlapping, completely cover the deme’s existence time interval, and are listed in time-descending order (from the past towards the present).

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.

Return type

float

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 see assert_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

bool

size_at(time)[source]#

Get the size of the deme at a given time.

If the deme doesn’t exist at the given time, the value 0 is returned. If the given time is infinity and the deme has an infinite start_time, the deme’s first epoch’s start_size is returned.

Parameters

time (float) – The time at which the size should be calculated.

Returns

The deme size.

Return type

float

property time_span#

The time span over which the deme exists.

Return type

float

class demes.Epoch(*, start_time, end_time, start_size, end_size, size_function, selfing_rate=0, cloning_rate=0)[source]#

Population parameters for a deme in a specified time interval.

An epoch spans the open-closed time interval (start_time, end_time], where start_time is the more ancient time, and end_time is more recent. Time values increase from the present towards the past, and start_time is strictly greater than end_time.

Epoch objects are not intended to be constructed directly.

Variables
  • start_time (float) – The start time of the epoch. This value is greater than zero and may be infinity.

  • end_time (float) – The end time of the epoch. This value is greater than or equal to zero and finite.

  • start_size (float) – Population size at start_time.

  • end_size (float) – Population size at end_time. If start_size != end_size, the population size changes between the start and end times according to the size_function.

  • size_function (str) –

    The size change function. This is either constant, exponential or linear, 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 from start_size to end_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 from start_size to end_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 see assert_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

bool

property time_span#

The time span of the epoch.

Return type

float

Continuous demographic events#

class demes.AsymmetricMigration(*, source, dest, start_time, end_time, rate)[source]#

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.

AsymmetricMigration objects are not intended to be constructed directly.

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 see assert_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

bool

Discrete demographic events#

class demes.Pulse(*, sources, dest, time, proportions)[source]#

An instantaneous pulse of migration from one deme to another.

Source and destination demes follow the forwards-in-time convention, where migrants are born in a source deme and (potentially) have children in the dest deme. If more than one source is given, migration is concurrent, and the sum of the migrant proportions sums to less than or equal to one.

Pulse objects are not intended to be constructed directly.

Variables
  • sources (list(str)) – The source deme(s).

  • dest (str) – The destination deme.

  • time (float) – The time of migration.

  • proportions (list(float)) – Immediately following migration, the proportion(s) of individuals in the destination deme made up of migrant individuals or having parents from the source deme(s).

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 see assert_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

bool

class demes.Split(*, parent, children, time)[source]#

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.

Split objects are not intended to be constructed directly.

Variables
  • parent (str) – The parental deme.

  • children (list[str]) – A list of descendant demes.

  • time (float) – The split time.

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

bool

class demes.Branch(*, parent, child, time)[source]#

A branch event, where a new deme branches off from a parental deme. The parental deme need not end at that time.

Branch objects are not intended to be constructed directly.

Variables
  • parent (str) – The parental deme.

  • child (str) – The descendant deme.

  • time (float) – The branch time.

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 see assert_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

bool

class demes.Merge(*, parents, proportions, child, time)[source]#

A merge event, in which two or more demes end at some time and contribute to a descendant deme.

Merge objects are not intended to be constructed directly.

Variables
  • parents (list[str]) – A list of parental demes.

  • proportions (list[float]) – A list of ancestry proportions, in order of parents.

  • child (str) – The descendant deme.

  • time (float) – The merge time.

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 see assert_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

bool

class demes.Admix(*, parents, proportions, child, time)[source]#

An admixture event, where two or more demes contribute ancestry to a new deme.

Admix objects are not intended to be constructed directly.

Variables
  • parents (list[str]) – A list of source demes.

  • proportions (list[float]) – A list of ancestry proportions, in order of parents.

  • child (str) – The admixed deme.

  • time (float) – The admixture time.

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 see assert_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

bool

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 (diploid individuals)} &= N_0 x\\\text{migration rate (per generation)} &= \frac{M}{4 N_0}\end{aligned}\end{align} \]

See also

The demes ms command line interface.

Warning

Several programs exist that implement an ms or ms-like command line interface. But discrepancies do exist between ms and its clones for some command line arguments, and such discrepancies alter the interpretation of the demographic model. This function implements the behaviour as described in Hudson’s ms manual. Command lines constructed for use with other programs may work as desired, but users are cautioned to carefully check the appropriate documentation to identify where discrepancies may exist.

The ms manual may be obtained from http://home.uchicago.edu/~rhudson1/source/mksamples.html

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.Graph

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.

See also

The --ms option of the demes parse command line interface.

Parameters
  • N0 (float) – The reference population size used to translate into coalescent units. See from_ms() for details.

  • samples (list(int)) – A list of haploid sample numbers, one for each deme, in the same order as the order of demes in the graph. The parameter is ignored for demographic models with only one deme. The given sampling scheme will be used with the -I argument. If not specified, the sampling configuration in the returned string will need editing prior to use.

Returns

The ms command line.

Return type

str