Skip to content

Site method to get genotypes #605

Closed
Closed

Description

@petrelharp

Right now there doesn't seem to be an easy way to either (a) look up the genotype of a node at a particular site, or (b) get the array of genotypes, other than by iterating through the variants until you get there. Unless I'm just forgetting about the right way to do this? This is an important thing to be able to do, it seems (and would be useful to me right now, in writing tests). How about

class Site:

def genotypes(nodes=<the samples>):
   '''
   Returns a numpy array of character strings giving the alleles carried by the listed nodes at this site.
   ''' 

Alternatively, this could be a method of the tree sequence, and also take a position argument.

Activity

  1. added
    enhancement
    on May 11, 2020
  2. jeromekelleher commented on May 12, 2020

    @jeromekelleher
    Member

    This is an expensive operation as we need to have the tree built. No reason we can't offer a TreeSequence method to do it though (making it a method of Site would imply a lot of cross-linkage - the site would need to know the TreeSequence).

    Normally I imagine doing this sort of thing for every site, so sequentially going over them is a good pattern and efficient. What's your usage pattern here?

    There is a samples argument to variants all right though, which does let you decode the state of non-sample nodes as well (IIRC).

  3. petrelharp commented on May 13, 2020

    @petrelharp
    ContributorAuthor

    You're right, that my example was iterating over all the sites, in which case I could use variants. But, suppose that I want to look at the genotypes at a particular site (eg, I find the site with the largest allele freq difference between two pops); as far as I can tell we have no good way to do that.

  4. jeromekelleher commented on May 13, 2020

    @jeromekelleher
    Member

    You're right, that my example was iterating over all the sites, in which case I could use variants. But, suppose that I want to look at the genotypes at a particular site (eg, I find the site with the largest allele freq difference between two pops); as far as I can tell we have no good way to do that.

    For this example, you'd need to be iterating over the trees to get the allele frequencies. Maybe we could make it a method of the Tree? That way it's explicit what the cost is. So, Tree.decode_genotypes(samples=None), where samples can be any node.

    I don't like putting in methods that are unnecessarily inefficient. I've seen people do things like tree_list = [tree.at(site.position) for site in ts.sites()], which is horrible. I worry that we'd start seeing code like [site.genotypes() for site in ts.sites()] which would be hideously inefficient.

  5. petrelharp commented on May 13, 2020

    @petrelharp
    ContributorAuthor

    make it a method of the Tree

    Sure, why not. I was a bit worried about getting exactly the right tree due to floating-point precision or something, but I guess you could do ts.at(site.position).genotypes()? It still feels kinda wierd, though.

    I don't like putting in methods that are unnecessarily inefficient

    I worry about this, too, but I think we just have to have a method to get genotypes at a particular site out, without extracting the entire genotype matrix. If we have a big warning in the docs saying IF YOU WANT LOTS THEN USE GENOTYPE_MATRIX...

  6. jeromekelleher commented on May 13, 2020

    @jeromekelleher
    Member

    I was a bit worried about getting exactly the right tree due to floating-point precision or something, but I guess you could do ts.at(site.position).genotypes()? It still feels kinda wierd, though.

    Most of the time you'd be doing

    for tree in ts.trees():
        for site in tree.sites():
              if some condition:
                    genotypes = tree.decode_genotypes(site)

    right?

    Otherwise, the first thing you'd think of is

    for site in ts.sites()
         if some_condition:
             genotypes = site.genotypes()

    which would look the same to most users. We should make it easy to write efficient code, and part of that is not giving unnecessary choices.

    (Come to think of it, if we had this method, we could get rid of the vargen_t infrastructure in C, which would be a major bonus!)

  7. petrelharp commented on May 24, 2020

    @petrelharp
    ContributorAuthor

    Note: as pointed out elsewhere, the samples argument of ts.variants() doesn't have to be just samples, so that this works:

    ts = msprime.simulate(5, mutation_rate=0.5, random_seed=2)
    
    for var in ts.variants(
            samples=range(ts.num_nodes),
            impute_missing_data=True):
        print(var.genotypes)
    

    ... so, all that's needed to do what I'm suggesting here would be a method to get a particular variant: e.g., ts.variant(k, ...).

  8. petrelharp commented on May 24, 2020

    @petrelharp
    ContributorAuthor

    Another thought: we've got methods that tell you a number of things about individual nodes in a particular tree, like children or mrca; it seems natural to also want to know the genotypes of individual nodes in a similar way; this can't currently be a method of the tree because it depends on which site you're at, though. It's not that hard to do yourself, but a bit tricky due to multiple mutations:

    ts = msprime.simulate(5, mutation_rate=0.5, random_seed=2)
    t = ts.first()
    
    def node_genotype(ts, site, u):
      t = ts.at(site.position)
      mut_nodes = set([m.node for m in site.mutations])
      while u != tskit.NULL and u not in mut_nodes:
        u = t.parent(u)
      if u == tskit.NULL:
        geno = site.ancestral_state
      else:
        # we want the last one
        m_genos = [m.derived_state for m in site.mutations if m.node == u]
        geno = m_genos[-1]
      return geno
    
  9. jeromekelleher commented on May 24, 2020

    @jeromekelleher
    Member

    What's wrong with tree.genotypes(site, samples=None)?

    Fundamentally it is a method of the tree. Maybe you want to provide a shortcut API for a site, but it should be implemented like

    def site_genotypes(self, site, samples=None):
        tree = self.at(site.position)
        return tree.genotypes(site, samples)
  10. jeromekelleher commented on May 24, 2020

    @jeromekelleher
    Member

    But, you don't just want the genotypes, you need the full variant object because you also need to know the alleles. So, something like Tree.variant(site, samples=None) and TreeSequence.variant(site=None, position=None, samples=None), where site and position are mutually exclusive options.

  11. petrelharp commented on May 24, 2020

    @petrelharp
    ContributorAuthor

    That also works!

  12. petrelharp commented on Sep 2, 2020

    @petrelharp
    ContributorAuthor

    Two small notes on this topic:

    1. We might also want a time argument, now that mutations have times, with the interpretation that you're getting the genotype of the ancestor of the nodes in question at the time provided.

    2. I'd implemented something like this in pyslim

  13. added
    Python API
    on Sep 29, 2020
  14. bhaller commented on Jan 24, 2021

    @bhaller

    (Come to think of it, if we had this method, we could get rid of the vargen_t infrastructure in C, which would be a major bonus!)

    I'm not really following the details of this proposal, but I just wanted to say: SLiM uses vargen_t in three different spots; it's incredibly useful. So if you guys get rid of it, I hope it gets replaced by something new in the C API that is as efficient/useful. SLiM needs something like it to exist, and if whatever replaces it doesn't provide essentially the same functionality that vargen_t provides now, that will generate a tremendous amount of work for us on the SLiM side. A lot of the most complex core code in SLiM related to treeseq – reading in a tree sequence from a .trees file and creating the corresponding SLiM objects, and doing a "crosscheck" between the tree-sequence tables and SLiM's internal state – relies heavily on vargen_t. So I'm a bit alarmed to read that you're thinking of having it go away. :-> I just want to make sure this is understood. @jeromekelleher @petrelharp

  15. jeromekelleher commented on Jan 25, 2021

    @jeromekelleher
    Member

    No worries @bhaller, we'll definitely keep all the functionality 😄

    Decoding genotypes is a fundamental operation, so it'll always be supported and will be as efficient as we can possible make it. The only difference will be how it's done, so the proposal is that rather than

    tsk_vargen_t vargen;
    tsk_variant_t *var;
    
    ret = tsk_vargen_init(&vargen, ts, NULL, 0, NULL, 0);
    check(ret)
    for (j = 0; j < tsk_treeseq_get_num_sites(ts); j++) {
        ret = tsk_vargen_next(&vargen, &variant);
        check(ret);
    }

    We'd have something like

    tsk_tree_t t;
    tsk_variant var;   
    
    ret = tsk_tree_init(&t, ts, 0);
    check(ret);
            
    for (t_ret = tsk_tree_first(&t); t_ret == 1; t_ret = tsk_tree_next(&t)) {
          /* might not be exactly this, but something similar */
          for (j = 0; j < t.sites_length; j++) {
              ret = tsk_tree_get_variant(&t, t.sites[j], &variant, /* more args */);
              check(ret);
         }
    }  
    check(t_ret);

    So, it's a little bit more code from the client side, but it's a lot more flexible. In particular, it means that you don't have to decode all genotypes, you can just get the sites you're interested in.

    There might be an argument for keeping the vargen_t as a convenience, since we can clearly implement it simply enough as calls to tsk_tree_get_variant. We'll probably be keeping it for a bit after implementing tsk_tree_get_variant just to avoid breaking too much of the test suite, anyway. I'm sure we could be convinced to keep it longer term too, if enough people wanted it.

  16. bhaller commented on Jan 25, 2021

    @bhaller

    No worries @bhaller, we'll definitely keep all the functionality 😄

    Decoding genotypes is a fundamental operation, so it'll always be supported and will be as efficient as we can possible make it. The only difference will be how it's done...

    I see. Thanks for the explanation, I appreciate it and I am relieved. :-> And yes, that proposed scheme certainly looks more flexible!

  17. hyanwong commented on Jul 14, 2021

    @hyanwong
    Member

    Just another datapoint: I've just found a use-case when I have a tree in the middle of the genome, that I've identified previously because it's "special" in some way, and I want to plot out the variation on the tips of the tree (in this case I'm investigating how we allocate mutations parsimoniously over the tree). So Tree.variant(site, samples=None) is exactly what I need.

  18. added this to the C API 1.0.0 milestone on Jul 14, 2021
  19. jeromekelleher commented on Jul 14, 2021

    @jeromekelleher
    Member

    Added this to the C API 1.0 milestone, as this is fundamentally a C level change. I think we should drop the vargen for 1.0 and use tsk_tree_get_variant instead.

  20. jeromekelleher commented on Sep 10, 2021

    @jeromekelleher
    Member

    See also #463

  21. benjeffery commented on Mar 15, 2022

    @benjeffery
    Member

    I'm thinking through a concrete implementation of this now. The current underlying C function has the signature:

    tsk_tree_get_variant(tsk_tree_t *self, const tsk_site_t *site, tsk_variant_t *variant, tsk_flags_t options)

    where variant is already initialised with the samples and alleles that are wanted. The samples and alleles are not specified on every call to tree_get_variant as then the variant would be initialised for every site. As this involves a couple of mallocs, copies, and map building this would be very inefficient.

    Above the following is suggested:

    for tree in ts.trees():
        for site in tree.sites():
              if some condition:
                    genotypes = tree.decode_genotypes(site)

    Due to the need for the variant in C to have state how about something like this:

    decoder = ts.VariantDecoder(samples, alleles, options)
    for tree in ts.trees():
        for site in tree.sites():
              if some condition:
                    genotypes = decoder(tree,site)

    The other alternative is to move the state into Tree and add samples and alleles as options to its constructor, however, I think this would be confusing as one would then expect Tree.samples to give the specified samples.

  22. hyanwong commented on Mar 15, 2022

    @hyanwong
    Member

    What if the alleles are different between sites? Does this all become very inefficient then?

  23. jeromekelleher commented on Mar 15, 2022

    @jeromekelleher
    Member

    How about we put the state in the Variant object like we do in C? It's usually a good idea for the high-level design to reflect to the low-level requirements. We'd have to replumb things a bit so that the current Variant object is a facade for the low-level variant_t. That's probably what we want to do ultimately anyway.

    How about we do something like this:

    def variants(self):
        variant = Variant(self)
        for tree in self.trees():
             for site in tree.sites():
                   variant.decode(tree, site)
                   yield variant

    The Tree.get_variant method then could be a convenience which creates a new variant each time its called. We'd document that this is inefficient if you do lots of sites, and you should create a variant and call decode on it if you want to do lots of this.

  24. benjeffery commented on Mar 15, 2022

    @benjeffery
    Member

    Cool, that's basically what I'm working towards, but with Variant keeping its name instead of being called a decoder. I think this all makes sense!

  25. benjeffery commented on Mar 16, 2022

    @benjeffery
    Member

    A quick update here, @jeromekelleher and I thrashed out some ideas about how this should work over a whiteboard and eventually decided that the tree should be internal to the Variant class which should use seek to get to the tree required, as seek will only get faster (as we add things like random access). #2160 is a start in this direction.

    So the implementation of the variants method becomes:

    def variants(self, return_copy=True):
        variant = Variant(self)
          for site_id in range(ts.num_sites):
               variant.decode(site_id)
               yield variant.copy() if return_copy else variant

    IMG_20220316_135254_HDR

  26. benjeffery commented on Apr 6, 2022

    @benjeffery
    Member

    Closing this as the remaining work is in #2176

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    Python APIenhancement

    Type

    No type

    Projects

    No projects

      Milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions