/
lca_utils.py
254 lines (192 loc) · 7.34 KB
/
lca_utils.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
"""
Utility functions for lowest-common-ancestor analysis tools.
"""
from os.path import exists
from collections import namedtuple, defaultdict, Counter
from .lca_db import LCA_Database, load_single_database, load_databases
__all__ = ['taxlist', 'zip_lineage', 'build_tree', 'find_lca',
'load_single_database', 'load_databases', 'gather_assignments',
'count_lca_for_assignments', 'LineagePair', 'display_lineage',
'make_lineage', 'pop_to_rank', 'is_lineage_match']
try: # py2/py3 compat
from itertools import zip_longest
except ImportError:
from itertools import izip_longest as zip_longest
from sourmash.logging import notify, error, debug
# type to store an element in a taxonomic lineage
LineagePair = namedtuple('LineagePair', ['rank', 'name'])
def check_files_exist(*files):
ret = True
not_found = []
for f in files:
if not exists(f):
not_found.append(f)
ret = False
if len(not_found):
error('Error! Could not find the following files.'
' Make sure the file paths are specified correctly.\n{}'.format('\n'.join(not_found)))
return ret
# ordered list of taxonomic ranks
def taxlist(include_strain=True):
"""
Provide an ordered list of taxonomic ranks.
"""
for k in ['superkingdom', 'phylum', 'class', 'order', 'family', 'genus',
'species']:
yield k
if include_strain:
yield 'strain'
# produce an ordered list of tax names from lineage
def zip_lineage(lineage, include_strain=True, truncate_empty=False):
"""
Given an iterable of LineagePair objects, return list of lineage names.
This utility function handles species/strain and empty lineage entries
gracefully.
>>> x = [ LineagePair('superkingdom', 'a'), LineagePair('phylum', 'b') ]
>>> zip_lineage(x)
['a', 'b', '', '', '', '', '', '']
>>> x = [ LineagePair('superkingdom', 'a'), LineagePair(None, ''), LineagePair('class', 'c') ]
>>> zip_lineage(x)
['a', '', 'c', '', '', '', '', '']
"""
empty = LineagePair(None, '')
pairs = zip_longest(taxlist(include_strain=include_strain),
lineage, fillvalue=empty)
pairs = list(pairs)
# eliminate empty if so requested
if truncate_empty:
last_lineage_tup = pairs[-1][1]
while pairs and last_lineage_tup == empty:
pairs.pop(-1)
if pairs:
last_lineage_tup = pairs[-1][1]
row = []
for taxrank, lineage_tup in pairs:
# validate non-empty tax, e.g. superkingdom/phylum/class in order.
if lineage_tup != empty and lineage_tup.rank != taxrank:
raise ValueError('incomplete lineage at {} - is {} instead'.format(taxrank, lineage_tup.rank))
row.append(lineage_tup.name)
return row
def display_lineage(lineage, include_strain=True, truncate_empty=True):
return ";".join(zip_lineage(lineage,
include_strain=include_strain,
truncate_empty=truncate_empty))
# filter function toreplace blank/na/null with 'unassigned'
filter_null = lambda x: 'unassigned' if x.strip() in \
('[Blank]', 'na', 'null', '') else x
null_names = set(['[Blank]', 'na', 'null'])
def make_lineage(lineage_str):
"Turn a ; or ,-separated set of lineages into a tuple of LineagePair objs."
lin = lineage_str.split(';')
if len(lin) == 1:
lin = lineage.split(',')
lin = [ LineagePair(rank, n) for (rank, n) in zip(taxlist(), lin) ]
lin = tuple(lin)
return lin
def build_tree(assignments, initial=None):
"""
Builds a tree of dictionaries from lists of LineagePair objects
in 'assignments'. This tree can then be used to find lowest common
ancestor agreements/confusion.
"""
if initial is None:
tree = {}
else:
tree = initial
if not assignments:
raise ValueError("empty assignment passed to build_tree")
for assignment in assignments:
node = tree
for lineage_tup in assignment:
if lineage_tup.name:
child = node.get(lineage_tup, {})
node[lineage_tup] = child
# shift -> down in tree
node = child
return tree
def find_lca(tree):
"""
Given a tree produced by 'find_tree', find the first node with multiple
children, OR the only leaf in the tree. Return (lineage_tup, reason),
where 'reason' is the number of children of the returned node, i.e.
0 if it's a leaf and > 1 if it's an internal node.
"""
node = tree
lineage = []
while 1:
if len(node) == 1: # descend to only child; track path
lineage_tup = next(iter(node.keys()))
lineage.append(lineage_tup)
node = node[lineage_tup]
elif len(node) == 0: # at leaf; end
return tuple(lineage), 0
else: # len(node) > 1 => confusion!!
return tuple(lineage), len(node)
def gather_assignments(hashvals, dblist):
"""
Gather assignments from across all the databases for all the hashvals.
Ignores counts of the hashvals.
"""
assignments = defaultdict(set)
for hashval in hashvals:
for lca_db in dblist:
lineages = lca_db.get_lineage_assignments(hashval)
if lineages:
assignments[hashval].update(lineages)
return assignments
def count_lca_for_assignments(assignments, hashval_counts=None):
"""
For each hashval, count the LCA across its assignments.
If hashval_counts is not None, it must be a dictionary that maps
{ hashval: hashval_count }; this is then used to weight the counts.
"""
counts = Counter()
for hashval in assignments:
# for each list of tuple_info [(rank, name), ...] build
# a tree that lets us discover lowest-common-ancestor.
lineages = assignments[hashval]
tree = build_tree(lineages)
# now find either a leaf or the first node with multiple
# children; that's our lowest-common-ancestor node.
lca, reason = find_lca(tree)
if hashval_counts:
counts[lca] += hashval_counts[hashval]
else:
counts[lca] += 1
return counts
def is_lineage_match(lin_a, lin_b, rank):
"""
check to see if two lineages are a match down to given rank.
"""
for a, b in zip(lin_a, lin_b):
assert a.rank == b.rank
if a.rank == rank:
if a == b:
return 1
if a != b:
return 0
return 0
def pop_to_rank(lin, rank):
"Remove lineage tuples from given lineage `lin` until `rank` is reached."
lin = list(lin)
txl = taxlist()
before_rank = []
for txl_rank in txl:
if txl_rank != rank:
before_rank.append(txl_rank)
else:
break
# are we already above rank?
if lin and lin[-1].rank in before_rank:
return tuple(lin)
while lin and lin[-1].rank != rank:
lin.pop()
return tuple(lin)
def make_lineage(lineage):
"Turn a ; or ,-separated set of lineages into a tuple of LineagePair objs."
lin = lineage.split(';')
if len(lin) == 1:
lin = lineage.split(',')
lin = [ LineagePair(rank, n) for (rank, n) in zip(taxlist(), lin) ]
lin = tuple(lin)
return lin