Comments (9)
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.
Here's an implementation or three:
-
count_alleles
is the nice way to do it usingmut.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 inget_derived_state()
). -
count_alleles_no_parent
does it by iterating upt he tree to, er, findmut.parent
. This doesn't work if there's more than one mutation per node (and, I think can't work under the current scheme). -
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.
Note that these do not depend on getting the mutations in any particular order, which is nice.
from tskit.
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.
from tskit.
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.
from tskit.
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.
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)
- Mention that node and individual flags are bitwise HOT 3
- Python 3.12 support HOT 1
- tmrca error when common ancestor does not exist HOT 2
- leaks when loading tree sequence in SLiM HOT 26
- Warning for `draw_svg` plot uses `logging` module instead of `warnings` HOT 2
- Topology counter not aligning with coalescent expectation HOT 10
- Add RateMap.zip(other1, other2,...) method HOT 6
- Add IO methods for RateMap
- Reinstate check for chromosome name in read_hapmap
- “Edit on GitHub” link missing from tskit docs
- Can I get a list of descendants of a branch (edge)? HOT 11
- extend edges misses some extendable edges
- Sample_sets incorrect in genetic_relatedness_matrix HOT 7
- Document genetic_relatedness_matrix
- Document divergence_matrix
- More flexible interpretation of mutation rate when getting emission probability when using `_tskit.lshmm` HOT 4
- C API for numpy 2.0 HOT 4
- Numpy 2.0 Python HOT 5
- Add support for MRCA based IBD HOT 2
- Documentation for IBD segments
Recommend Projects
-
React
A declarative, efficient, and flexible JavaScript library for building user interfaces.
-
Vue.js
🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.
-
Typescript
TypeScript is a superset of JavaScript that compiles to clean JavaScript output.
-
TensorFlow
An Open Source Machine Learning Framework for Everyone
-
Django
The Web framework for perfectionists with deadlines.
-
Laravel
A PHP framework for web artisans
-
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.
-
Visualization
Some thing interesting about visualization, use data art
-
Game
Some thing interesting about game, make everyone happy.
Recommend Org
-
Facebook
We are working to build community through open source technology. NB: members must have two-factor auth.
-
Microsoft
Open source projects and samples from Microsoft.
-
Google
Google ❤️ Open Source for everyone.
-
Alibaba
Alibaba Open Source for everyone
-
D3
Data-Driven Documents codes.
-
Tencent
China tencent open source team.
from tskit.