Skip to content

Allow match_samples to work on a sparse subset of the sites #187

Closed

Description

@hyanwong

Rather like the missing data problem in #173, @awohns would like to match "special" (ancient) samples which only contain a fraction (say 40%) of the inference sites used to create the ancestors_ts (there is some discussion in #169 (comment)). At the moment we can't do this because we restore the tree_sequence_builder (in inference.py:restore_tree_sequence_builder()) using the same indexes into inference sites as used in the SampleData file.

It should be possible to restore edges using self.tree_sequence_builder.restore_edges and map onto new positions. But it may be simpler to tackle #173 directly, keep the requirement for all sites to be identical, and have the missing sites in the special samples simply marked as tskit.NULL.

Activity

  1. changed the title [-]Allow match_samples to work on a subset of the sites[/-] [+]Allow match_samples to work on a sparse subset of the sites[/+] on Sep 10, 2019
  2. hyanwong commented on Sep 10, 2019

    @hyanwong
    MemberAuthor

    So it turns out that the way to solve this is to adjust the ancestors_ts so that it contains the same sites as in the sparse samples, removing any nonsensical edges using simplify(..., reduce_to_site_topology=True), mapping the new nodes to the old ones, matching the sparse samples, and extracting the edges after matching so they can be injected into the tree sequence based on the complete samples. For reference, the code we are using is below, although the results of running it haven't been fully explored yet

    This way of doing it should, I think, be obsoleted by solving #173.

    import msprime
    import tsinfer
    import numpy as np
    
    def prune_sites(ts, keep_sites):
        # Remove sites and mutations not referenced in keep_sites
        def keep_with_offset(keep, data, offset):
            """Copied from keep_intervals"""
            # We need the astype here for 32 bit machines
            lens = np.diff(offset).astype(np.int32)
            return (
                data[np.repeat(keep, lens)],
                np.concatenate([
                    np.array([0], dtype=offset.dtype),
                    np.cumsum(lens[keep], dtype=offset.dtype)]))
        tables = ts.dump_tables()
        sites = ts.tables.sites
        mutations = ts.tables.mutations
        new_as, new_as_offset = keep_with_offset(
            keep_sites, sites.ancestral_state, sites.ancestral_state_offset)
        new_md, new_md_offset = keep_with_offset(
            keep_sites, sites.metadata, sites.metadata_offset)
        keep_mutations = keep_sites[mutations.site]
        tables.sites.set_columns( #replaces existing
            position=sites.position[keep_sites],
            ancestral_state=new_as,
            ancestral_state_offset=new_as_offset,
            metadata=new_md,
            metadata_offset=new_md_offset)
        new_ds, new_ds_offset = keep_with_offset(
            keep_mutations, mutations.derived_state, mutations.derived_state_offset)
        new_md, new_md_offset = keep_with_offset(
            keep_mutations, mutations.metadata, mutations.metadata_offset)
        site_map = np.cumsum(keep_sites, dtype=mutations.site.dtype) - 1
        parent_map = np.cumsum(keep_mutations, dtype=mutations.parent.dtype) - 1
        # parent -1 always maps to parent -1
        parent_map = np.append(parent_map, np.array([-1], dtype=mutations.parent.dtype))
        # Don't bother dealing with connected mutations as we are removing the whole site
        tables.mutations.set_columns(
            site=site_map[mutations.site[keep_mutations]],
            node=mutations.node[keep_mutations],
            derived_state=new_ds,
            derived_state_offset=new_ds_offset,
            parent=parent_map[mutations.parent[keep_mutations]],
            metadata=new_md,
            metadata_offset=new_md_offset)
        return tables.tree_sequence()
    
    # Create the ts with the minimal number of sites, shared by *all* samples
    ts_min = msprime.simulate(100, recombination_rate = 2, mutation_rate=2)
    # Add some more mutations in to create the "full" dataset, seen in the first 90 samples
    ts_max_muts = msprime.mutate(ts_min, rate=2, keep=True)
    
    full_samples = np.arange(90)
    sparse_samples = np.arange(90,100)
    
    first_90 = ts_max_muts.simplify(full_samples, filter_sites=False)
    sample_90 = tsinfer.SampleData.from_tree_sequence(first_90)
    last_10 = ts_min.simplify(sparse_samples, filter_sites=False)
    sample_10 = tsinfer.SampleData.from_tree_sequence(last_10)
    
    ancestors = tsinfer.generate_ancestors(sample_90)
    ancestors_ts = tsinfer.match_ancestors(sample_90, ancestors)
    
    first_match = tsinfer.match_samples(sample_90, ancestors_ts, simplify=False)
    
    # Try to match the sparse samples against the ancestors tree seq generated from the full set
    try:
        # This should fail with a ValueError
        second_match = tsinfer.match_samples(sample_10, ancestors_ts, simplify=False)
        assert False, "We should not get here"
    except ValueError:
        pass
        
    # Make ancestors_ts compatible by keeping only sites that are sample_data inference sites
    restricted_sites = sample_10.sites_position[:][sample_10.sites_inference[:].astype(bool)]
    keep_sites = np.isin(ancestors_ts.tables.sites.position, restricted_sites).astype(bool)  # Boolean
    pruned_ancestors_ts = prune_sites(ancestors_ts, keep_sites)
    pruned_ancestors_ts, node_map = pruned_ancestors_ts.simplify(map_nodes=True, reduce_to_site_topology=True)
    
    # NOW IT WORKS!!!
    second_match = tsinfer.match_samples(sample_10, pruned_ancestors_ts, simplify=False)
    
    # Add the new nodes, edges, etc into first_match
    tables1 = first_match.dump_tables()
    tables2 = second_match.tables
    
    # Add any new individuals
    new_ind = tables1.individuals.append_columns(
        flags=tables2.individuals.flags,
        # TO DO - add location, location_offset, metadata, and metadata_offset
    )
    
    # Add new nodes
    samplenodes2 = np.isin(np.arange(tables2.nodes.num_rows), second_match.samples())
    tables1.nodes.append_columns(
        flags=tables2.nodes.flags[:][samplenodes2],
        time=tables2.nodes.time[:][samplenodes2],
        population=tables2.nodes.population[:][samplenodes2],
        individual=None if new_ind is None else new_ind[tables2.nodes.individual[:][samplenodes2]]
        # TO DO - add metadata & metadata_offset
    )
    
    # Add new edges
    assert len(node_map) == min(second_match.samples())  # Check the new samples take indexes after the existing nodes in the map
    # Add the mapping from newly minted samples to older ones (assumes sample order is maintained)
    node_map_with_samples = np.append(
        node_map,
        np.arange(first_match.num_nodes, first_match.num_nodes + len(second_match.samples()))
    ).astype(node_map.dtype)
    
    new_edges = np.isin(tables2.edges.child[:], second_match.samples())
    tables1.edges.append_columns(
        left=tables2.edges.left[new_edges],
        right=tables2.edges.right[new_edges],
        parent=node_map_with_samples[tables2.edges.parent[new_edges]],
        child=node_map_with_samples[tables2.edges.child[new_edges]]
    )
    
    tables1.sort()
    merged_ts = tables1.tree_sequence()
    
  3. hyanwong commented on Sep 10, 2019

    @hyanwong
    MemberAuthor

    If we make this sort of functionality more generally available, I think it should be along the lines of #189, so I'm closing this issue.

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

    No labels
    No labels

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions