Beispiel #1
0
def _simple_mutation_generator(rate, sequence_length, rng):
    """
    Factory function used to create a low-level mutation generator that
    produces binary infinite sites mutations suitable for use in
    msprime.simulate() and the mspms CLI.
    """
    # Add a ``discrete`` parameter and pass to the MutationGenerator
    # constructor.
    if rate is None:
        return None
    rate_map = MutationMap(position=[0, sequence_length], rate=[rate, 0])
    return _msprime.MutationGenerator(rng, rate_map._ll_map, BinaryMutations())
Beispiel #2
0
def mutate(tree_sequence,
           rate=None,
           random_seed=None,
           model=None,
           keep=False,
           start_time=None,
           end_time=None):
    """
    Simulates mutations on the specified ancestry and returns the resulting
    :class:`tskit.TreeSequence`. Mutations are generated at the specified rate in
    measured generations. Mutations are generated under the infinite sites
    model, and so the rate of new mutations is per unit of sequence length per
    generation.

    If a random seed is specified, this is used to seed the random number
    generator. If the same seed is specified and all other parameters are equal
    then the same mutations will be generated. If no random seed is specified
    then one is generated automatically.

    If the ``model`` parameter is specified, this determines the model under
    which mutations are generated. Currently only the :class:`.InfiniteSites`
    mutation model is supported. This parameter is useful if you wish to obtain
    sequences with letters from the nucleotide alphabet rather than the default
    0/1 states. By default mutations from the infinite sites model with a binary
    alphabet are generated.

    By default, sites and mutations in the parameter tree sequence are
    discarded. If the ``keep`` parameter is true, however, *additional*
    mutations are simulated. Under the infinite sites mutation model, all new
    mutations generated will occur at distinct positions from each other and
    from any existing mutations (by rejection sampling).

    The time interval over which mutations can occur may be controlled
    using the ``start_time`` and ``end_time`` parameters. The ``start_time``
    defines the lower bound (in time-ago) on this interval and ``max_time``
    the upper bound. Note that we may have mutations associated with
    nodes with time <= ``start_time`` since mutations store the node at the
    bottom (i.e., towards the leaves) of the branch that they occur on.

    :param tskit.TreeSequence tree_sequence: The tree sequence onto which we
        wish to throw mutations.
    :param float rate: The rate of mutation per generation. (Default: 0).
    :param int random_seed: The random seed. If this is `None`, a
        random seed will be automatically generated. Valid random
        seeds must be between 1 and :math:`2^{32} - 1`.
    :param MutationModel model: The mutation model to use when generating
        mutations. If not specified or None, the :class:`.InfiniteSites`
        mutation model is used.
    :param bool keep: Whether to keep existing mutations (default: False).
    :param float start_time: The minimum time at which a mutation can
        occur. (Default: no restriction.)
    :param float end_time: The maximum time at which a mutation can occur
        (Default: no restriction).
    :return: The :class:`tskit.TreeSequence` object  resulting from overlaying
        mutations on the input tree sequence.
    :rtype: :class:`tskit.TreeSequence`
    """
    try:
        tables = tree_sequence.tables
    except AttributeError:
        raise ValueError("First argument must be a TreeSequence instance.")
    if random_seed is None:
        random_seed = simulations._get_random_seed()
    random_seed = int(random_seed)

    rng = _msprime.RandomGenerator(random_seed)
    if model is None:
        model = InfiniteSites()
    try:
        alphabet = model.alphabet
    except AttributeError:
        raise TypeError("model must be an InfiniteSites instance")
    if rate is None:
        rate = 0
    rate = float(rate)
    keep = bool(keep)

    parameters = {
        "command": "mutate",
        "rate": rate,
        "random_seed": random_seed,
        "keep": keep
    }

    if start_time is None:
        start_time = -sys.float_info.max
    else:
        start_time = float(start_time)
        parameters["start_time"] = start_time

    if end_time is None:
        end_time = sys.float_info.max
    else:
        end_time = float(end_time)
        parameters["end_time"] = end_time
    # TODO Add a JSON representation of the model to the provenance.
    provenance_dict = provenance.get_provenance_dict(parameters)

    if start_time > end_time:
        raise ValueError("start_time must be <= end_time")

    mutation_generator = _msprime.MutationGenerator(rng,
                                                    rate,
                                                    alphabet=alphabet,
                                                    start_time=start_time,
                                                    end_time=end_time)
    lwt = _msprime.LightweightTableCollection()
    lwt.fromdict(tables.asdict())
    mutation_generator.generate(lwt, keep=keep)

    tables = tskit.TableCollection.fromdict(lwt.asdict())
    tables.provenances.add_row(json.dumps(provenance_dict))
    return tables.tree_sequence()
Beispiel #3
0
def mutate(
    tree_sequence,
    rate=None,
    random_seed=None,
    model=None,
    keep=False,
    start_time=None,
    end_time=None,
    discrete=False,
):
    """
    Simulates mutations on the specified ancestry and returns the resulting
    :class:`tskit.TreeSequence`. Mutations are generated at the specified rate in
    measured generations. Mutations are generated under the infinite sites
    model, and so the rate of new mutations is per unit of sequence length per
    generation.

    If a random seed is specified, this is used to seed the random number
    generator. If the same seed is specified and all other parameters are equal
    then the same mutations will be generated. If no random seed is specified
    then one is generated automatically.

    If the ``model`` parameter is specified, this determines the model under
    which mutations are generated. Currently only the :class:`.InfiniteSites`
    mutation model is supported. This parameter is useful if you wish to obtain
    sequences with letters from the nucleotide alphabet rather than the default
    0/1 states. By default mutations from the infinite sites model with a binary
    alphabet are generated.

    By default, sites and mutations in the parameter tree sequence are
    discarded. If the ``keep`` parameter is true, however, *additional*
    mutations are simulated. Under the infinite sites mutation model, all new
    mutations generated will occur at distinct positions from each other and
    from any existing mutations (by rejection sampling).

    The time interval over which mutations can occur may be controlled
    using the ``start_time`` and ``end_time`` parameters. The ``start_time``
    defines the lower bound (in time-ago) on this interval and ``max_time``
    the upper bound. Note that we may have mutations associated with
    nodes with time <= ``start_time`` since mutations store the node at the
    bottom (i.e., towards the leaves) of the branch that they occur on.

    :param tskit.TreeSequence tree_sequence: The tree sequence onto which we
        wish to throw mutations.
    :param float rate: The rate of mutation per generation, as either a
        single number (for a uniform rate) or as a
        :class:`.MutationMap`. (Default: 0).
    :param int random_seed: The random seed. If this is `None`, a
        random seed will be automatically generated. Valid random
        seeds must be between 1 and :math:`2^{32} - 1`.
    :param MutationModel model: The mutation model to use when generating
        mutations. If not specified or None, the :class:`.BinaryMutations`
        mutation model is used.
    :param bool keep: Whether to keep existing mutations (default: False).
    :param float start_time: The minimum time ago at which a mutation can
        occur. (Default: no restriction.)
    :param float end_time: The maximum time ago at which a mutation can occur
        (Default: no restriction).
    :param bool discrete: Whether to generate mutations at only integer positions
        along the genome.  Default is False, which produces infinite-sites
        mutations at floating-point positions.
    :return: The :class:`tskit.TreeSequence` object  resulting from overlaying
        mutations on the input tree sequence.
    :rtype: :class:`tskit.TreeSequence`
    """
    try:
        tables = tree_sequence.tables
    except AttributeError:
        raise ValueError("First argument must be a TreeSequence instance.")
    seed = random_seed
    if random_seed is None:
        seed = core.get_random_seed()
    else:
        seed = int(seed)

    if rate is None:
        rate = 0
    try:
        rate = float(rate)
        rate_map = MutationMap(position=[0.0, tree_sequence.sequence_length],
                               rate=[rate, 0.0])
    except TypeError:
        rate_map = rate
    if not isinstance(rate_map, MutationMap):
        raise TypeError("rate must be a float or a MutationMap")

    if start_time is None:
        start_time = -sys.float_info.max
    else:
        start_time = float(start_time)
    if end_time is None:
        end_time = sys.float_info.max
    else:
        end_time = float(end_time)
    if start_time > end_time:
        raise ValueError("start_time must be <= end_time")
    keep = bool(keep)
    discrete = bool(discrete)

    if model is None:
        model = BinaryMutations()
    if not isinstance(model, MutationModel):
        raise TypeError("model must be a MutationModel")

    argspec = inspect.getargvalues(inspect.currentframe())
    parameters = {
        "command": "mutate",
        **{arg: argspec.locals[arg]
           for arg in argspec.args},
    }
    parameters["random_seed"] = seed
    encoded_provenance = provenance.json_encode_provenance(
        provenance.get_provenance_dict(parameters))

    rng = _msprime.RandomGenerator(seed)
    mutation_generator = _msprime.MutationGenerator(random_generator=rng,
                                                    rate_map=rate_map._ll_map,
                                                    model=model)
    lwt = _msprime.LightweightTableCollection()
    lwt.fromdict(tables.asdict())
    mutation_generator.generate(lwt,
                                keep=keep,
                                start_time=start_time,
                                end_time=end_time,
                                discrete=discrete)

    tables = tskit.TableCollection.fromdict(lwt.asdict())
    tables.provenances.add_row(encoded_provenance)
    return tables.tree_sequence()