Python API#
Matching#
- class tsls.Index(ts, *, alleles=None)[source]#
The read-only data that the HMM needs from a tskit tree sequence: a copy of the tree sequence in the form the HMM reads, with its alleles encoded as integers. An Index does not change after it is built, so it can be shared between HMMs, including HMMs in different threads, and is then only built once.
By default the alleles are numbered at each site as tskit does: the ancestral state is 0 and derived states are numbered from 1 in order of their first appearance at the site. This default gives every site at least two allele indices.
Otherwise,
allelesgives the alleles, and every state is its index in the list of alleles of its site. It is either:one list of alleles (strings) for every site; or
a list of alleles for each site, as a sequence of sequences or a 2D array with one row for each site. Trailing empty strings in a row are padding.
The number of alleles at a site is then the length of its list, and a haplotype can have any of them at the site, whether or not they are in the tree sequence there. Every ancestral and derived state must be in its site’s list, the alleles of a site must be unique, and a site can have at most 127 alleles.
- Parameters:
ts (tskit.TreeSequence) – The tree sequence.
alleles – The alleles, as described above. The default is to number the alleles at each site as tskit does.
The attributes of an Index are:
ts: thetskit.TreeSequence.alleles: theallelesargument.num_nodes: the number of nodes.num_sites: the number of sites.num_alleles: an array of the number of alleles at each site, which sets the emission probabilities (seetsls.mismatch_odds()).
- class tsls.Hmm(ts, *, alleles=None, sparse=True, index_min_sites=None, count_distinct=False, extended_checks=False)[source]#
The Li and Stephens HMM for matching haplotypes against a tree sequence, with the Viterbi, forward and backward algorithms.
Each run takes an int8 haplotype array with one entry per site. Each entry is an allele index or
tsls.MISSING_DATA. Recombination and mismatch can each be a scalar or an array with one entry per site. Mismatch gives the probability of each particular alternative allele.Thresholds apply to one run. After normalisation,
likelihood_thresholdfloors small values (default: the smallest positive normal float64). In Viterbi,prune_thresholdsets values below this fraction of the best to the floor. The experimentalrelative_prune_thresholdapplies the same cutoff relative to the site maximum in all three algorithms. Both pruning thresholds default to zero. See The likelihood model for the effect on results.Reuse an Hmm across runs in one thread. For concurrent runs, share a
tsls.Indexand create one Hmm per thread, or usetsls.MatchingManager.- Parameters:
ts – The tree sequence to match against: a
tskit.TreeSequence, or atsls.Indexto share one between HMMs.alleles – The alleles, as in
tsls.Index. This can only be given with atskit.TreeSequence.sparse (bool) – For tuning and tests; may change. If False, Viterbi processes every site in full.
index_min_sites (int) – For tuning and tests; may change. Viterbi processes sites sparsely in trees with at least this many sites left. The default is 16.
count_distinct (bool) – For tuning and tests; may change. Record the mean number of distinct values per site in Viterbi, in
mean_num_distinct_values.extended_checks (bool) – For tests. Check the internal state as the algorithms run, which is slow.
The attributes of an Hmm are:
ts: thetskit.TreeSequence.index: thetsls.Index.total_memory: the memory held for the Viterbi traceback, in bytes. This grows to what the largest run needed, and is kept for the runs after it. The rest of the working memory is not counted: it is in proportion to the number of nodes, and does not change.mean_traceback_size: the number of nodes with a value of their own at a site in the last Viterbi run, averaged over all the sites of the tree sequence.
- viterbi(h, recombination, mismatch, start=0, end=None, *, likelihood_threshold=None, prune_threshold=None, relative_prune_threshold=None)[source]#
Run the Viterbi algorithm on a haplotype over the sites
[start, end), and return the copying path and the haplotype it gives. Among equally likely paths, which one is returned is not specified, and can change between versions of tsls.- Parameters:
- Returns:
The
tsls.ViterbiMatch.- Raises:
tsls.MatchImpossible – If no path has a likelihood above zero.
- viterbi_matrix(h, recombination, mismatch, start=0, end=None, *, likelihood_threshold=None, prune_threshold=None, relative_prune_threshold=None)[source]#
Run the Viterbi algorithm as
viterbi()does, and also return the values stored in the traceback.- Parameters:
- Returns:
The
tsls.ViterbiMatch, whosematrixis thetsls.CompressedMatrixof the values stored in the traceback.- Raises:
tsls.MatchImpossible – If no path has a likelihood above zero.
- forward_matrix(h, recombination, mismatch, *, likelihood_threshold=None, relative_prune_threshold=None)[source]#
Run the forward algorithm on a haplotype.
- Parameters:
- Returns:
The
tsls.CompressedMatrixof forward values, scaled at each site.- Raises:
tsls.MatchImpossible – If the haplotype has a likelihood of zero.
- backward_matrix(h, recombination, mismatch, normalisation_factor, *, likelihood_threshold=None, relative_prune_threshold=None)[source]#
Run the backward algorithm on a haplotype, scaled by the normalisation factors of its forward matrix. Their elementwise product gives the node posteriors when flooring and pruning do not affect the values.
- Parameters:
h – The haplotype.
recombination – The recombination probability at each site.
mismatch – The probability of each alternative allele at each site.
normalisation_factor – The
normalisation_factorarray of thetsls.CompressedMatrixthatforward_matrix()returned for the haplotype, with the same parameters.
- Returns:
The
tsls.CompressedMatrixof backward probabilities.
- class tsls.ViterbiMatch(left, right, parent, matched_haplotype, start, end, *, matrix=None, mean_traceback_size=None, mean_num_values=None, max_num_values=None, mean_num_updated=None, mean_delta_size=None, num_sparse_sites=None, mean_num_distinct_values=None)[source]#
The result of the Viterbi algorithm on a haplotype, as
tsls.Hmm.viterbi()andtsls.Hmm.viterbi_matrix()return it: the copying path, the haplotype it gives, and statistics of the run.The path covers
[x, y), where x is the position of sitestart(0 ifstartis 0) and y is the position of siteend(the sequence length ifendis the number of sites). Each breakpoint is the position of the first site copied from the next segment.The attributes of a ViterbiMatch are:
left,right,parent: arrays with one value for each segment of the path, from right to left along the sequence:parentis copied over[left, right).matched_haplotype: the haplotype of the path, withtsls.MISSING_DATAat the sites outside[start, end).start,end: the sites matched,[start, end).matrix: fromtsls.Hmm.viterbi_matrix(), thetsls.CompressedMatrixof the values stored in the traceback. Otherwise None.mean_traceback_size: the number of nodes with a value of their own at a site, averaged over all the sites of the tree sequence.
- class tsls.MatchingManager(index, *, num_threads=0, memory_limit=None)[source]#
Runs matches against a
tsls.Indexin worker threads. Each match is given atsls.Hmmthat no other match is using. The Hmms are kept between matches, so that their working memory is allocated once, and the traceback memory that they hold can be limited.def run_match(hmm, h): return hmm.viterbi(h, recombination, mismatch) with tsls.MatchingManager(index, num_threads=8) as manager: for match in manager.run(run_match, haplotypes): ...
The manager is a context manager, which calls
close()at the end of thewithblock to stop the threads and free the Hmms.With a
memory_limit, a match is not started while the Hmms hold more than the limit in total and another match is running, and an Hmm frees its traceback memory when it ends or is about to start a match over the limit. Below the limit, nothing is freed. The limit holds back new matches, and not the ones that are running, so the total can go over it while they finish. A match always starts when no other is running, so one match can take more than the limit, and a limit that is too small runs the matches one at a time. The limit applies to thetotal_memoryof eachtsls.Hmm, which is not available on Windows: there, any limit runs the matches one at a time.- Parameters:
index (tsls.Index) – The index of the tree sequence to match against.
num_threads (int) – The number of worker threads. The default is 0, which runs the matches in the calling thread.
memory_limit (int) – The limit on the traceback memory of the Hmms, in bytes. The default is no limit.
The attributes of a MatchingManager are:
index: thetsls.Index.num_threads: the number of worker threads.memory_limit: the memory limit, or None.total_memory: the sum of thetotal_memoryof its Hmms.
- close()[source]#
Stop the worker threads and free the Hmms, after the matches that are running have ended. The manager cannot be used afterwards.
- run(function, work)[source]#
Run
function(hmm, item)for each item of work, and return an iterator over the values that it returns, in the order that the matches finish. The function is called in a worker thread with atsls.Hmm, which it can run any number of times, and must not use after it returns. To tell the results apart, return the item or its key with the result.The work is any iterable. It is read in the calling thread, and at most
2 * num_threadsitems ahead of the results that have been consumed, so a generator is consumed as the matches are run.If the function or the work raises an exception, it is raised here when the matches that are running have ended: their results are lost, and the matches that have not started are not run. Closing the iterator early stops the run in the same way. The manager can be used again afterwards.
- Parameters:
function – The function to call for each item, with an Hmm and the item.
work – An iterable of the items.
- Returns:
An iterator over the values returned by the function.
- tsls.MISSING_DATA = -1#
The value of missing data in a haplotype.
Compressed matrices#
- class tsls.CompressedMatrix(ts, normalisation_factor, offsets, nodes, values, flags=None)[source]#
The values computed by the Viterbi, forward or backward algorithm:
tsls.Hmm.forward_matrix()andtsls.Hmm.backward_matrix()return one, andtsls.Hmm.viterbi_matrix()returns one as thematrixof itstsls.ViterbiMatch. At each site it stores a list of (node, value) pairs, and the value of a node in the tree is the value of its nearest ancestor (including itself) in this list.Viterbi values are scaled by the best score at each matched site.
The attributes of a CompressedMatrix are:
ts: thetskit.TreeSequence.normalisation_factor: an array of the normalisation factor of each site.offsets: an array with one more value than there are sites. The pairs of site j areoffsets[j]tooffsets[j + 1]ofnodesandvalues.nodes,values: arrays of the node and the value of each pair.flags: for Viterbi, an array that is 1 for each pair whose node uses the recombination transition at the site. For forward and backward it is None.num_sites: the number of sites.
- dump(path)[source]#
Save the matrix to a
.npzfile, whichtsls.load_compressed_matrix()loads given the same tree sequence. The contents of the file are experimental, and files may not be readable by later versions of tsls.- Parameters:
path – The path of the file.
- property log_likelihood#
Sum of the logs of the site normalisation factors. For a forward matrix, see The likelihood model for its interpretation.
- get_site(site)[source]#
Return the pairs stored for a site.
- Parameters:
site (int) – The site.
- Returns:
The
(nodes, values)tuple of arrays.
- decode(nodes=None)[source]#
Return the values of the selected nodes at every site as a dense array.
For a windowed Viterbi run, use
get_site()within the window. Decoding requires stored values at every site with active nodes.- Parameters:
nodes – The nodes. The default is every node.
- Returns:
An array with a row for each site and a column for each of the nodes. Nodes that are not in the tree at a site have the value 0.
- tsls.load_compressed_matrix(path, ts)[source]#
Load a matrix that
tsls.CompressedMatrix.dump()saved.- Parameters:
path – The path of the file.
ts (tskit.TreeSequence) – The tree sequence the matrix was computed on.
- Returns:
- Raises:
ValueError – If node count or site positions differ.
Recombination probabilities#
- tsls.recombination_probabilities(recombination_rate, positions)[source]#
Return the probability of recombination between each site and the previous one, given either a constant rate per unit of sequence length or a HapMap genetic map (see
tsls.read_genetic_map()). The genetic distance d (Morgans) between adjacent sites is converted to the probability of an odd number of crossovers using Haldane’s map function, (1 - exp(-2d)) / 2. The first site has probability 0.- Parameters:
recombination_rate – The recombination rate per unit of sequence length, or the path of a genetic map.
positions – An array of the position of each site.
- Returns:
An array of the recombination probability at each site, for the
recombinationoftsls.Hmm.
- tsls.read_genetic_map(path, positions)[source]#
Read a HapMap-format genetic map and return the genetic position (in Morgans) of each of the specified physical positions.
The file has a single header line and whitespace-separated columns: chromosome, position (bp), rate (cM/Mb) and cumulative map position (cM). Only the position and map columns are used. Genetic positions are linearly interpolated between map entries, with an implicit entry of 0 cM at position 0. Beyond the last entry the recombination rate is zero.
- Parameters:
path – The path of the genetic map.
positions – An array of physical positions.
- Returns:
An array of the genetic position of each one, in Morgans.
The likelihood model#
See The likelihood model for the model and pruning assumptions.
- tsls.switch_odds(recombination, num_nodes)[source]#
Return the switch odds q of a recombination probability r, the odds of switching to a given node rather than staying on a node: q = (r / n) / (1 - r + r / n), with n = num_nodes.
- Parameters:
recombination – The recombination probability, or an array of them.
num_nodes (int) – The number of nodes in the tree sequence.
- Returns:
The switch odds, of the same shape as
recombination.
- tsls.recombination_probability(switch_odds, num_nodes)[source]#
Return the recombination probability r that gives the switch odds q, the inverse of
tsls.switch_odds(): r = q n / (1 - q + q n), with n = num_nodes.- Parameters:
switch_odds – The switch odds, or an array of them. They must be between 0 and 1.
num_nodes (int) – The number of nodes in the tree sequence.
- Returns:
The recombination probability, of the same shape as
switch_odds.
- tsls.mismatch_odds(mismatch, num_alleles)[source]#
Return the mismatch odds e of a mismatch probability mu, the odds of mismatching rather than matching: e = mu / (1 - (A - 1) mu), where A = num_alleles.
- Parameters:
mismatch – The mismatch probability, or an array of them.
num_alleles – The number of alleles, or an array of them.
- Returns:
The mismatch odds.
- tsls.mismatch_probability(mismatch_odds, num_alleles)[source]#
Return the mismatch probability mu that gives the mismatch odds e with A = num_alleles alleles, the inverse of
tsls.mismatch_odds(): mu = e / (1 + (A - 1) e).- Parameters:
mismatch_odds – The mismatch odds, or an array of them. They must not be negative.
num_alleles – The number of alleles, or an array of them.
- Returns:
The mismatch probability.
- tsls.path_threshold(num_mismatches, mismatch, num_alleles, *, num_switches=0, recombination=None, num_nodes=None, tolerance=1e-09)[source]#
Compute a Viterbi prune threshold for a mismatch and switch budget. For constant rates this is the mismatch odds raised to num_mismatches times the switch odds raised to num_switches, reduced by tolerance. With site-specific rates the smallest odds are used for each budget. See The likelihood model for the conditions on this bound.
- Parameters:
num_mismatches (int) – The largest number of mismatches of an optimal path.
mismatch – The mismatch probability, or an array of them for each site.
num_alleles – The number of alleles, or an array of them for each site.
num_switches (int) – The largest number of switches of an optimal path.
recombination – The recombination probability, or an array of them for each site. Needed if
num_switchesis not 0.num_nodes (int) – The number of nodes in the tree sequence. Needed if
num_switchesis not 0.tolerance (float) – The relative amount to reduce the threshold by.
- Returns:
The threshold, for the
prune_thresholdoftsls.Hmm.
- tsls.lossless_threshold(recombination, num_nodes, *, tolerance=1e-09)[source]#
Return the smallest switch odds times (1 - tolerance). A node below the next site’s switch odds cannot improve on recombination at that next step. Pruning can change the stored value at the current site.
- tsls.THRESHOLD_TOLERANCE = 1e-9#
Default relative reduction applied by the pruning threshold helpers.
Exceptions#
- exception tsls.MatchImpossible#
No path through the tree sequence has a likelihood above zero for the haplotype, with the recombination and mismatch probabilities given.
- exception tsls.LibraryError#
An error in the tsls or tskit C library.