Code Monkey home page Code Monkey logo

Comments (9)

jeromekelleher avatar jeromekelleher commented on August 12, 2024

This looks good and efficient to me, thanks @petrelharp. I'm a bit slow this morning though, and not quite sure I get it. Would you mind sketching out a Python version here so we can see how useful the parent mutation is (and what would be the cost of not having it)?

from tskit.

petrelharp avatar petrelharp commented on August 12, 2024

Here's an implementation or three:

  1. count_alleles is the nice way to do it using mut.parent. There is awkwardness from not having figured out the right way to grab a mutation given its ID (this is what needs to happen in get_derived_state()).

  2. count_alleles_no_parent does it by iterating upt he tree to, er, find mut.parent. This doesn't work if there's more than one mutation per node (and, I think can't work under the current scheme).

  3. hap_counter is used to check the others above actually work. They seem to.

import msprime
from tests.tsutil import jukes_cantor

from collections import Counter


def count_alleles(tree, site):
    n = tree.num_tracked_samples()
    U = {site.ancestral_state: n}
    for mut in site.mutations:
        if mut.derived_state not in U:
            U[mut.derived_state] = 0
        U[mut.derived_state] += tree.num_tracked_samples(mut.node)
        parent_state = get_derived_state(site, mut.parent)
        if parent_state not in U:
            U[parent_state] = 0
        U[parent_state] -= tree.num_tracked_samples(mut.node)
    zeros = [a for a in U if U[a] == 0]
    for a in zeros:
        del U[a]
    return U


def get_derived_state(site, mut_id):
    """
    Find the derived state of the mutation with id `mut_id` at site `site`.
    """
    if mut_id == msprime.NULL_NODE:
        state = site.ancestral_state
    else:
        for m in site.mutations:
            if m.id == mut_id:
                state = m.derived_state
    return state

def count_alleles_no_parent(tree, site):
    n = tree.num_tracked_samples()
    U = {site.ancestral_state: n}
    mut_nodes = [mut.node for mut in site.mutations]
    # this version can't handle more than one mut per node
    assert len(mut_nodes) == len(set(mut_nodes))
    for mut in site.mutations:
        if mut.derived_state not in U:
            U[mut.derived_state] = 0
        U[mut.derived_state] += tree.num_tracked_samples(mut.node)
        p = tree.parent(mut.node)
        while ((p != msprime.NULL_NODE) and (p not in mut_nodes)):
            p = tree.parent(p)
        if p == msprime.NULL_NODE:
            parent_state = site.ancestral_state
        else:
            parent_state = site.mutations[mut_nodes.index(p)].derived_state
        if parent_state not in U:
            U[parent_state] = 0
        U[parent_state] -= tree.num_tracked_samples(mut.node)
    zeros = [a for a in U if U[a] == 0]
    for a in zeros:
        del U[a]
    return U


class AlleleCounter(object):

    def __init__(self, ts, samples, with_parent=True):
        self.trees = ts.trees(tracked_samples=samples, sample_counts=True)
        if with_parent:
            self.ac_fun = count_alleles
        else:
            self.ac_fun = count_alleles_no_parent

    def __iter__(self):
        """
        Returns a generator of dictionaries of the form
           allele : number of tracked samples in tree with that allele
        ... one for each site.  Should not contain zeros.
        """
        for t in self.trees:
            for s in t.sites():
                if len(s.mutations) > 0:
                    yield self.ac_fun(t, s)


def hap_counter(ts, samples):
    """
    Quick version for testing.
    """
    haps = list(ts.haplotypes())
    for k in range(ts.num_sites):
        yield Counter(haps[j][k] for j in samples)


ts0 = msprime.simulate(10, recombination_rate=2)
ts = jukes_cantor(ts0, num_sites=10, multiple_per_node=False, mu=1.0)

samples = list(range(4))
ac = AlleleCounter(ts, samples)
ac_np = AlleleCounter(ts, samples)
hc = hap_counter(ts, samples)

for x, xp, y in zip(ac, ac_np, hc):
    print("---------")
    print("AC", x)
    # print("HC", y)
    assert sum(x.values()) == len(samples)
    assert set(x) == set(xp)
    assert set(x) == set(y)
    for a in x:
        assert x[a] == y[a]
        assert x[a] == xp[a]

from tskit.

petrelharp avatar petrelharp commented on August 12, 2024

Note that these do not depend on getting the mutations in any particular order, which is nice.

from tskit.

jeromekelleher avatar jeromekelleher commented on August 12, 2024

OK, very elegant! So, practical upshot for now is that we keep parent and fix it in as part of the upcoming release of the tables API.

The second upshot I guess is how to we use this and provide an useful and efficient interface? Do we include count_alleles as an option to the variants iterator and add this map to the returned variant objects, or do we add a different interface? Can we put this off until after 0.5.0?

from tskit.

petrelharp avatar petrelharp commented on August 12, 2024

from tskit.

jeromekelleher avatar jeromekelleher commented on August 12, 2024

OK. But we can put it off until post 0.5.0 right? I'd rather not rush any new API additions unless they're essential.

from tskit.

petrelharp avatar petrelharp commented on August 12, 2024

from tskit.

jeromekelleher avatar jeromekelleher commented on August 12, 2024

What are your thoughts on this now @petrelharp --- we've done the allele counting under the hood in C. Do we want to expose an interface to this?

from tskit.

petrelharp avatar petrelharp commented on August 12, 2024

I was proposing this for use in computing statistics, in C really. I think we do not need a python interface. The only use I can think of would be to provide a python iterator over allele frequencies, but this is easy using the variants iterator and kinda niche. I'll close this.

from tskit.

Related Issues (20)

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.