assemblytrace 1.1.0__py3-none-any.whl
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- assemblytrace/__init__.py +1 -0
- assemblytrace/__main__.py +4 -0
- assemblytrace/annotation.py +307 -0
- assemblytrace/attribute.py +1388 -0
- assemblytrace/change.py +221 -0
- assemblytrace/claims.py +612 -0
- assemblytrace/cli.py +230 -0
- assemblytrace/core.py +100 -0
- assemblytrace/curation.py +155 -0
- assemblytrace/formats.py +957 -0
- assemblytrace/identity.py +74 -0
- assemblytrace/indels.py +95 -0
- assemblytrace/inventory.py +379 -0
- assemblytrace/io_safety.py +69 -0
- assemblytrace/lift.py +467 -0
- assemblytrace/localmatch.py +51 -0
- assemblytrace/project.py +494 -0
- assemblytrace/prov.py +277 -0
- assemblytrace/provenance.py +183 -0
- assemblytrace/py.typed +0 -0
- assemblytrace/release.py +432 -0
- assemblytrace/report.py +1046 -0
- assemblytrace/scan.py +538 -0
- assemblytrace/segments.py +348 -0
- assemblytrace/seqcol.py +161 -0
- assemblytrace/shellexp.py +229 -0
- assemblytrace/sparsediff.py +905 -0
- assemblytrace/summary.py +146 -0
- assemblytrace/variant_input.py +91 -0
- assemblytrace/versions.py +583 -0
- assemblytrace-1.1.0.dist-info/METADATA +198 -0
- assemblytrace-1.1.0.dist-info/RECORD +36 -0
- assemblytrace-1.1.0.dist-info/WHEEL +5 -0
- assemblytrace-1.1.0.dist-info/entry_points.txt +2 -0
- assemblytrace-1.1.0.dist-info/licenses/LICENSE +21 -0
- assemblytrace-1.1.0.dist-info/top_level.txt +1 -0
assemblytrace/lift.py
ADDED
|
@@ -0,0 +1,467 @@
|
|
|
1
|
+
"""Exact coordinate transfer between versions.
|
|
2
|
+
|
|
3
|
+
``lift`` moves GFF3/GTF, BED and VCF records from version A to version B
|
|
4
|
+
through the event list of the pair; no alignment and no annotation transfer
|
|
5
|
+
heuristics are involved, so a feature lands exactly where its sequence went.
|
|
6
|
+
Each GFF feature receives an ``at_lift`` attribute: ``exact`` (no event in
|
|
7
|
+
the feature), ``changed_inside`` (events inside, length may differ) or the
|
|
8
|
+
record goes to the unmapped list when an end falls in a deleted span. VCF
|
|
9
|
+
records whose REF no longer matches B are kept with the filter
|
|
10
|
+
``at_ref_changed``.
|
|
11
|
+
"""
|
|
12
|
+
from __future__ import annotations
|
|
13
|
+
|
|
14
|
+
import gzip
|
|
15
|
+
import re
|
|
16
|
+
from urllib.parse import quote, unquote
|
|
17
|
+
from collections import defaultdict
|
|
18
|
+
|
|
19
|
+
import bisect
|
|
20
|
+
|
|
21
|
+
from .sparsediff import liftover, reverse_events
|
|
22
|
+
from .segments import Frames
|
|
23
|
+
|
|
24
|
+
|
|
25
|
+
def unresolved_in(pair, src):
|
|
26
|
+
"""Unresolved stretches of a stored pair in the coordinates of ``src``."""
|
|
27
|
+
fwd = pair['a'] == src
|
|
28
|
+
return [{'contig': u['contig'] if fwd else u.get('contig_b', u['contig']),
|
|
29
|
+
'ref_pos': u.get('ref_pos' if fwd else 'alt_pos', 1)} for u in pair.get('unresolved', [])]
|
|
30
|
+
|
|
31
|
+
|
|
32
|
+
def transition(pair, src, dst):
|
|
33
|
+
"""Events from ``src`` to ``dst``, the contig name map and the frames, from a stored pair.
|
|
34
|
+
|
|
35
|
+
Events are in frame coordinates (``segments``): ``pre`` maps source contigs into the frames before the
|
|
36
|
+
events (A to B) and ``post`` maps the frames back to contigs after them (B to A). Either is a
|
|
37
|
+
``Frames`` object, empty when the direction needs none.
|
|
38
|
+
"""
|
|
39
|
+
frames = Frames(pair.get('frames'))
|
|
40
|
+
walked = {e['contig']: e.get('contig_b', e['contig']) for e in pair['events']}
|
|
41
|
+
walked.update({fid: fr['contig_b'] for fid, fr in (pair.get('frames') or {}).items()})
|
|
42
|
+
if (pair['a'], pair['b']) == (src, dst):
|
|
43
|
+
events = pair['events']
|
|
44
|
+
names = dict(pair.get('crosswalk', {}))
|
|
45
|
+
names.update(walked)
|
|
46
|
+
pre, post = frames, Frames()
|
|
47
|
+
elif (pair['b'], pair['a']) == (src, dst):
|
|
48
|
+
events = reverse_events(pair['events'])
|
|
49
|
+
names = {v: k for k, v in pair.get('crosswalk', {}).items()}
|
|
50
|
+
names.update({m: fid for fid, m in walked.items()})
|
|
51
|
+
pre, post = Frames(), frames
|
|
52
|
+
else:
|
|
53
|
+
raise ValueError(f'pair {pair["a"]}-{pair["b"]} does not connect {src} and {dst}')
|
|
54
|
+
return events, names, pre, post
|
|
55
|
+
|
|
56
|
+
|
|
57
|
+
class Lifter:
|
|
58
|
+
"""Exact placement of positions and spans through an event list.
|
|
59
|
+
|
|
60
|
+
Positions inside a deleted or replaced span have no place; a span wholly
|
|
61
|
+
inside an exact inversion is mirrored onto the other strand. Source contigs
|
|
62
|
+
are mapped into the frames the diff walked first (``pre``), and frames back
|
|
63
|
+
to contigs last (``post``); a span that would cross the end of a block of a
|
|
64
|
+
frame (the origin of a rotated contig, the join of two merged contigs, the
|
|
65
|
+
break of a split one) has no single place and is unmapped.
|
|
66
|
+
"""
|
|
67
|
+
|
|
68
|
+
def __init__(self, events, names, unmatched=(), unresolved=(), pre=None, post=None):
|
|
69
|
+
by = defaultdict(list)
|
|
70
|
+
for e in events:
|
|
71
|
+
by[e['contig']].append(e)
|
|
72
|
+
self.maps = {c: liftover([e for e in evs if not e.get('inversion')] +
|
|
73
|
+
[dict(e, type='COMPLEX') for e in evs if e.get('inversion')]) for c, evs in by.items()}
|
|
74
|
+
self.inversions = {c: sorted((e['ref_pos'], e['ref_pos'] + len(e['ref']) - 1, e['alt_pos'])
|
|
75
|
+
for e in evs if e.get('inversion')) for c, evs in by.items()}
|
|
76
|
+
# closed spans of replaced bases; an insertion after base p is the half-open gap (p + 0.5)
|
|
77
|
+
self.spans = {}
|
|
78
|
+
for c, evs in by.items():
|
|
79
|
+
sp = sorted((e['ref_pos'] + 0.5, e['ref_pos'] + 0.5) if not e['ref'] else
|
|
80
|
+
(e['ref_pos'], e['ref_pos'] + len(e['ref']) - 1) for e in evs)
|
|
81
|
+
ends, m = [], float('-inf')
|
|
82
|
+
for _, t in sp:
|
|
83
|
+
m = max(m, t); ends.append(m)
|
|
84
|
+
self.spans[c] = ([s for s, _ in sp], ends)
|
|
85
|
+
self.names = names
|
|
86
|
+
self.unmatched = set(unmatched)
|
|
87
|
+
self.pre = pre if isinstance(pre, Frames) else Frames(pre)
|
|
88
|
+
self.post = post if isinstance(post, Frames) else Frames(post)
|
|
89
|
+
# the walk lost synchrony at this position (or the contig was never diffed): nothing after it can be placed
|
|
90
|
+
self.stop = {}
|
|
91
|
+
for u in unresolved:
|
|
92
|
+
self.stop[u['contig']] = min(self.stop.get(u['contig'], float('inf')), u.get('ref_pos', 1))
|
|
93
|
+
|
|
94
|
+
def targets(self, c):
|
|
95
|
+
"""Contigs of the target that positions of source contig c can land on."""
|
|
96
|
+
if c in self.unmatched:
|
|
97
|
+
return []
|
|
98
|
+
rows = self.pre.by_a.get(c)
|
|
99
|
+
fids = [c] if rows is None else sorted({r[2] for r in rows})
|
|
100
|
+
out = []
|
|
101
|
+
for f in fids:
|
|
102
|
+
if self.stop.get(f) == 1:
|
|
103
|
+
continue
|
|
104
|
+
t = self.names.get(f, f)
|
|
105
|
+
got = self.post.by_f.get(t)
|
|
106
|
+
out += [t] if got is None else sorted({r[2] for r in got[1]})
|
|
107
|
+
return sorted(set(out))
|
|
108
|
+
|
|
109
|
+
def contig(self, c):
|
|
110
|
+
"""The target contig of source contig c when there is exactly one, else None."""
|
|
111
|
+
t = self.targets(c)
|
|
112
|
+
return t[0] if len(t) == 1 else None
|
|
113
|
+
|
|
114
|
+
def span(self, c, s, e):
|
|
115
|
+
"""{'contig', 'start', 'end', 'flip', 'inverted'} for the closed span s..e of contig c, or None."""
|
|
116
|
+
if c in self.unmatched:
|
|
117
|
+
return None
|
|
118
|
+
fr = self.pre.into(c, s, e)
|
|
119
|
+
if fr is None:
|
|
120
|
+
return None
|
|
121
|
+
fc, x, y, flip = fr
|
|
122
|
+
if max(x, y) >= self.stop.get(fc, float('inf')):
|
|
123
|
+
return None
|
|
124
|
+
inverted = False
|
|
125
|
+
f = self.maps.get(fc)
|
|
126
|
+
inv = [(i0, i1, j0) for i0, i1, j0 in self.inversions.get(fc, ()) if i0 <= y and i1 >= x]
|
|
127
|
+
if inv:
|
|
128
|
+
i0, i1, j0 = inv[0]
|
|
129
|
+
if len(inv) > 1 or x < i0 or y > i1:
|
|
130
|
+
return None
|
|
131
|
+
u, v = j0 + (i1 - y), j0 + (i1 - x)
|
|
132
|
+
flip, inverted = not flip, True
|
|
133
|
+
else:
|
|
134
|
+
u, v = (x, y) if f is None else (f(x), f(y))
|
|
135
|
+
if u is None or v is None or v < u:
|
|
136
|
+
return None
|
|
137
|
+
tc = self.names.get(fc, fc)
|
|
138
|
+
back = self.post.outof(tc, u, v)
|
|
139
|
+
if back is None:
|
|
140
|
+
return None
|
|
141
|
+
tc, u, v, flip2 = back
|
|
142
|
+
return {'contig': tc, 'start': u, 'end': v, 'flip': flip != flip2, 'inverted': inverted}
|
|
143
|
+
|
|
144
|
+
def pos(self, c, p):
|
|
145
|
+
r = self.span(c, p, p)
|
|
146
|
+
return None if r is None else r['start']
|
|
147
|
+
|
|
148
|
+
def touched(self, c, start, end):
|
|
149
|
+
fr = self.pre.into(c, start, end)
|
|
150
|
+
if fr is None:
|
|
151
|
+
return True
|
|
152
|
+
fc, start, end, _ = fr
|
|
153
|
+
starts, ends = self.spans.get(fc, ((), ()))
|
|
154
|
+
i = bisect.bisect_right(starts, end)
|
|
155
|
+
return i > 0 and ends[i - 1] >= start
|
|
156
|
+
|
|
157
|
+
|
|
158
|
+
FLIP = {'+': '-', '-': '+'}
|
|
159
|
+
COMP = str.maketrans('ACGTNacgtn', 'TGCANtgcan')
|
|
160
|
+
|
|
161
|
+
|
|
162
|
+
class _BgzfText:
|
|
163
|
+
"""Text writer over pysam's BGZF so that lifted .vcf.gz/.gff3.gz can be indexed with tabix."""
|
|
164
|
+
|
|
165
|
+
def __init__(self, path):
|
|
166
|
+
import pysam
|
|
167
|
+
self.fh = pysam.BGZFile(str(path), 'wb')
|
|
168
|
+
|
|
169
|
+
def write(self, text):
|
|
170
|
+
self.fh.write(text.encode('utf-8'))
|
|
171
|
+
|
|
172
|
+
def __enter__(self):
|
|
173
|
+
return self
|
|
174
|
+
|
|
175
|
+
def __exit__(self, *exc):
|
|
176
|
+
self.fh.close()
|
|
177
|
+
|
|
178
|
+
|
|
179
|
+
def _open_text(path, mode='rt'):
|
|
180
|
+
"""Text in with universal newlines (gzip or BGZF by magic bytes); text out with LF line ends, .gz as BGZF."""
|
|
181
|
+
if 'r' in mode:
|
|
182
|
+
with open(path, 'rb') as fh:
|
|
183
|
+
gz = fh.read(2) == b'\x1f\x8b'
|
|
184
|
+
if gz:
|
|
185
|
+
return gzip.open(path, 'rt', encoding='utf-8', newline=None)
|
|
186
|
+
return open(path, 'r', encoding='utf-8', newline=None)
|
|
187
|
+
if str(path).endswith(('.gz', '.bgz')):
|
|
188
|
+
try:
|
|
189
|
+
return _BgzfText(path)
|
|
190
|
+
except ImportError:
|
|
191
|
+
raise ValueError(f'{path}: compressed output needs pysam (BGZF); write it uncompressed and run bgzip') from None
|
|
192
|
+
return open(path, 'w', encoding='utf-8', newline='\n')
|
|
193
|
+
|
|
194
|
+
|
|
195
|
+
GFF_SAFE = '.:^*$@!+_?-|'
|
|
196
|
+
|
|
197
|
+
|
|
198
|
+
def _is_gtf(path, attrs):
|
|
199
|
+
return str(path).lower().endswith(('.gtf', '.gtf.gz')) or bool(re.match(r'^\s*\w+ "', attrs or ''))
|
|
200
|
+
|
|
201
|
+
|
|
202
|
+
def _cds_key(f, gtf):
|
|
203
|
+
attrs = f[8]
|
|
204
|
+
if gtf:
|
|
205
|
+
m = re.search(r'transcript_id "([^"]+)"', attrs)
|
|
206
|
+
return m.group(1) if m else None
|
|
207
|
+
kv = dict(x.split('=', 1) for x in attrs.split(';') if '=' in x)
|
|
208
|
+
return kv.get('Parent') or kv.get('ID')
|
|
209
|
+
|
|
210
|
+
|
|
211
|
+
def _recompute_phases(rows):
|
|
212
|
+
"""Phases of the segments of one CDS after their lengths changed: the first keeps its phase."""
|
|
213
|
+
strand = rows[0][0][6]
|
|
214
|
+
order = sorted(rows, key=lambda r: int(r[0][3]), reverse=(strand == '-'))
|
|
215
|
+
if order[0][0][7] not in ('0', '1', '2'):
|
|
216
|
+
return False
|
|
217
|
+
done = int(order[0][0][7])
|
|
218
|
+
changed = False
|
|
219
|
+
total = -done
|
|
220
|
+
for i, r in enumerate(order):
|
|
221
|
+
f = r[0]
|
|
222
|
+
if i:
|
|
223
|
+
ph = str((3 - total % 3) % 3)
|
|
224
|
+
if f[7] != ph:
|
|
225
|
+
f[7] = ph; changed = True
|
|
226
|
+
total += int(f[4]) - int(f[3]) + 1
|
|
227
|
+
return changed
|
|
228
|
+
|
|
229
|
+
|
|
230
|
+
def _orf_state(rows, seqs_b):
|
|
231
|
+
"""'intact' when the lifted CDS segments, spliced in B, translate without an internal stop; else 'broken'."""
|
|
232
|
+
from .annotation import _translate
|
|
233
|
+
strand = rows[0][0][6]
|
|
234
|
+
seq = seqs_b.get(unquote(rows[0][0][0]))
|
|
235
|
+
if seq is None or strand not in ('+', '-'):
|
|
236
|
+
return None
|
|
237
|
+
order = sorted(rows, key=lambda r: int(r[0][3]), reverse=(strand == '-'))
|
|
238
|
+
nt = ''.join(seq[int(r[0][3]) - 1:int(r[0][4])] if strand == '+' else
|
|
239
|
+
seq[int(r[0][3]) - 1:int(r[0][4])].translate(COMP)[::-1] for r in order).upper()
|
|
240
|
+
ph = order[0][0][7]
|
|
241
|
+
nt = nt[int(ph):] if ph in ('0', '1', '2') else nt
|
|
242
|
+
if len(nt) % 3 or any(c not in 'ACGT' for c in nt):
|
|
243
|
+
return 'broken'
|
|
244
|
+
try:
|
|
245
|
+
prot = _translate(nt)
|
|
246
|
+
except ValueError:
|
|
247
|
+
return 'broken'
|
|
248
|
+
return 'intact' if prot and '*' not in prot else 'broken'
|
|
249
|
+
|
|
250
|
+
|
|
251
|
+
def lift_gff(src, dst, lifter: Lifter, lengths_b: dict, seqs_b=None):
|
|
252
|
+
"""GFF3 or GTF records moved exactly; a CDS loses every segment if one cannot be placed.
|
|
253
|
+
|
|
254
|
+
Seqids are percent-decoded for the lookup and escaped again on output (GFF3
|
|
255
|
+
column 1). CDS phases downstream of a length change inside the CDS are
|
|
256
|
+
recomputed so the frame stays continuous (``at_phase=recomputed``). A CDS
|
|
257
|
+
with a change inside, or carried through an inversion, is translated in the
|
|
258
|
+
target and marked ``at_orf=intact`` or ``at_orf=broken`` (an internal stop or
|
|
259
|
+
a length that is not a whole number of codons).
|
|
260
|
+
"""
|
|
261
|
+
stats = defaultdict(int)
|
|
262
|
+
unmapped, out, groups = [], [], defaultdict(list)
|
|
263
|
+
orf = {}
|
|
264
|
+
with _open_text(src) as fi:
|
|
265
|
+
lines = list(fi)
|
|
266
|
+
regions = set()
|
|
267
|
+
for line in lines:
|
|
268
|
+
if line.startswith('##FASTA') or line.startswith('>'):
|
|
269
|
+
break # target sequences are not written: no dangling ##FASTA
|
|
270
|
+
if line.startswith('##sequence-region'):
|
|
271
|
+
p = line.split()
|
|
272
|
+
for c in (lifter.targets(unquote(p[1])) if len(p) >= 2 else ()):
|
|
273
|
+
if c in lengths_b and c not in regions: # merged contigs share one target region
|
|
274
|
+
regions.add(c)
|
|
275
|
+
out.append([f'##sequence-region {quote(c, safe=GFF_SAFE)} 1 {lengths_b[c]}\n'])
|
|
276
|
+
continue
|
|
277
|
+
if line.startswith('#') or not line.strip():
|
|
278
|
+
out.append([line]); continue
|
|
279
|
+
f = line.rstrip('\n').split('\t')
|
|
280
|
+
if len(f) != 9:
|
|
281
|
+
out.append([line]); continue
|
|
282
|
+
gtf = _is_gtf(src, f[8])
|
|
283
|
+
c = unquote(f[0]); start, end = int(f[3]), int(f[4])
|
|
284
|
+
sp = lifter.span(c, start, end)
|
|
285
|
+
row = [f, line, None, gtf]
|
|
286
|
+
if sp is None:
|
|
287
|
+
row[2] = 'unmapped'
|
|
288
|
+
else:
|
|
289
|
+
row[2] = 'inverted' if sp['inverted'] else ('changed_inside' if lifter.touched(c, start, end) else 'exact')
|
|
290
|
+
f[0], f[3], f[4] = quote(sp['contig'], safe=GFF_SAFE), str(sp['start']), str(sp['end'])
|
|
291
|
+
if sp['flip']:
|
|
292
|
+
f[6] = FLIP.get(f[6], f[6])
|
|
293
|
+
if f[2] == 'CDS':
|
|
294
|
+
key = _cds_key(f, gtf)
|
|
295
|
+
if key:
|
|
296
|
+
groups[(c, key)].append(row)
|
|
297
|
+
out.append(row)
|
|
298
|
+
for rows in groups.values():
|
|
299
|
+
# a CDS whose segments land on different contigs or strands (a break or a join between them) has no place
|
|
300
|
+
if any(r[2] == 'unmapped' for r in rows) or len({(r[0][0], r[0][6]) for r in rows}) > 1:
|
|
301
|
+
for r in rows:
|
|
302
|
+
r[2] = 'unmapped'
|
|
303
|
+
elif any(r[2] in ('changed_inside', 'inverted') for r in rows):
|
|
304
|
+
if len(rows) > 1 and _recompute_phases(rows):
|
|
305
|
+
for r in rows:
|
|
306
|
+
r.append('phase')
|
|
307
|
+
state = _orf_state(rows, seqs_b) if seqs_b is not None else None
|
|
308
|
+
if state:
|
|
309
|
+
for r in rows:
|
|
310
|
+
orf[id(r)] = state
|
|
311
|
+
with _open_text(dst, 'wt') as fo:
|
|
312
|
+
for row in out:
|
|
313
|
+
if len(row) == 1:
|
|
314
|
+
fo.write(row[0]); continue
|
|
315
|
+
f, line, status, gtf = row[:4]
|
|
316
|
+
if status == 'unmapped':
|
|
317
|
+
unmapped.append(line); stats['unmapped'] += 1; continue
|
|
318
|
+
stats[status] += 1
|
|
319
|
+
attrs = f[8] if f[8] not in ('', '.') else ''
|
|
320
|
+
extra = [('at_lift', status)] + ([('at_phase', 'recomputed')] if len(row) > 4 else []) + \
|
|
321
|
+
([('at_orf', orf[id(row)])] if id(row) in orf else [])
|
|
322
|
+
if gtf:
|
|
323
|
+
f[8] = (attrs.rstrip('; ') + '; ' if attrs else '') + ' '.join(f'{k} "{v}";' for k, v in extra)
|
|
324
|
+
else:
|
|
325
|
+
f[8] = (attrs.rstrip(';') + ';' if attrs else '') + ';'.join(f'{k}={v}' for k, v in extra)
|
|
326
|
+
fo.write('\t'.join(f) + '\n')
|
|
327
|
+
return dict(stats), unmapped
|
|
328
|
+
|
|
329
|
+
|
|
330
|
+
def lift_bed(src, dst, lifter: Lifter):
|
|
331
|
+
"""BED3-12: coordinates, thickStart/thickEnd and blocks (BED12) move together; a header line is kept."""
|
|
332
|
+
stats = defaultdict(int); unmapped = []
|
|
333
|
+
with _open_text(src) as fi, _open_text(dst, 'wt') as fo:
|
|
334
|
+
for line in fi:
|
|
335
|
+
if not line.strip() or line.startswith(('#', 'track', 'browser')):
|
|
336
|
+
fo.write(line); continue
|
|
337
|
+
f = line.rstrip('\n').split('\t') if '\t' in line else line.split()
|
|
338
|
+
try:
|
|
339
|
+
c, start0, end = f[0], int(f[1]), int(f[2])
|
|
340
|
+
except (IndexError, ValueError):
|
|
341
|
+
unmapped.append(line); stats['unmapped'] += 1; continue
|
|
342
|
+
sp = lifter.span(c, start0 + 1, max(end, start0 + 1))
|
|
343
|
+
if sp is None:
|
|
344
|
+
unmapped.append(line); stats['unmapped'] += 1; continue
|
|
345
|
+
c2 = sp['contig']
|
|
346
|
+
same = lambda x: x is not None and x['contig'] == c2 and x['flip'] == sp['flip']
|
|
347
|
+
new_start = sp['start'] - 1
|
|
348
|
+
new_end = sp['end'] if end > start0 else new_start
|
|
349
|
+
try:
|
|
350
|
+
if len(f) >= 8:
|
|
351
|
+
t0, t1 = int(f[6]), int(f[7])
|
|
352
|
+
if t1 > t0:
|
|
353
|
+
th = lifter.span(c, t0 + 1, t1)
|
|
354
|
+
if not same(th):
|
|
355
|
+
raise LookupError
|
|
356
|
+
f[6], f[7] = str(th['start'] - 1), str(th['end'])
|
|
357
|
+
else: # thickStart == thickEnd: no coding part, keep at the start
|
|
358
|
+
f[6] = f[7] = str(new_start)
|
|
359
|
+
if len(f) >= 12:
|
|
360
|
+
sizes = [int(x) for x in f[10].rstrip(',').split(',') if x]
|
|
361
|
+
starts = [int(x) for x in f[11].rstrip(',').split(',') if x]
|
|
362
|
+
blocks = []
|
|
363
|
+
for st_, sz in zip(starts, sizes):
|
|
364
|
+
bl = lifter.span(c, start0 + st_ + 1, start0 + st_ + sz)
|
|
365
|
+
if not same(bl):
|
|
366
|
+
raise LookupError
|
|
367
|
+
blocks.append((bl['start'] - 1, bl['end']))
|
|
368
|
+
blocks.sort()
|
|
369
|
+
f[10] = ','.join(str(y - x) for x, y in blocks) + ','
|
|
370
|
+
f[11] = ','.join(str(x - new_start) for x, _ in blocks) + ','
|
|
371
|
+
if len(f) >= 6 and sp['flip']:
|
|
372
|
+
f[5] = FLIP.get(f[5], f[5])
|
|
373
|
+
except (LookupError, ValueError):
|
|
374
|
+
unmapped.append(line); stats['unmapped'] += 1; continue
|
|
375
|
+
stats['inverted' if sp['inverted'] else
|
|
376
|
+
'changed_inside' if lifter.touched(c, start0 + 1, max(end, start0 + 1)) else 'exact'] += 1
|
|
377
|
+
f[0], f[1], f[2] = c2, str(new_start), str(new_end)
|
|
378
|
+
fo.write('\t'.join(f) + '\n')
|
|
379
|
+
return dict(stats), unmapped
|
|
380
|
+
|
|
381
|
+
|
|
382
|
+
def lift_vcf(src, dst, lifter: Lifter, seqs_b: dict, reference=None):
|
|
383
|
+
"""VCF records moved with INFO/END; REF re-checked against B; ##contig and ##reference rewritten.
|
|
384
|
+
|
|
385
|
+
A record whose span (POS to END) contains a change keeps its alleles but is
|
|
386
|
+
flagged ``at_span_changed``, since its END or SVLEN may no longer describe B.
|
|
387
|
+
"""
|
|
388
|
+
stats = defaultdict(int); unmapped = []
|
|
389
|
+
with _open_text(src) as fi, _open_text(dst, 'wt') as fo:
|
|
390
|
+
for line in fi:
|
|
391
|
+
if line.startswith(('##contig=', '##reference=')):
|
|
392
|
+
continue
|
|
393
|
+
if line.startswith('#CHROM'):
|
|
394
|
+
if reference:
|
|
395
|
+
fo.write(f'##reference={reference}\n')
|
|
396
|
+
for c, s in seqs_b.items():
|
|
397
|
+
fo.write(f'##contig=<ID={c},length={len(s)}>\n')
|
|
398
|
+
fo.write('##FILTER=<ID=at_ref_changed,Description="REF allele differs in the target assembly version">\n')
|
|
399
|
+
fo.write('##FILTER=<ID=at_span_changed,Description="The span POS to INFO/END contains a change between the versions">\n')
|
|
400
|
+
fo.write(line); continue
|
|
401
|
+
if line.startswith('#'):
|
|
402
|
+
fo.write(line); continue
|
|
403
|
+
f = line.rstrip('\n').split('\t')
|
|
404
|
+
c, pos, ref = f[0], int(f[1]), f[3].upper()
|
|
405
|
+
sp = lifter.span(c, pos, pos + len(ref) - 1)
|
|
406
|
+
c2 = sp['contig'] if sp is not None else None
|
|
407
|
+
alts = f[4].split(',') if len(f) > 4 else []
|
|
408
|
+
if sp is not None and sp['flip']:
|
|
409
|
+
# on the other strand only same-length alleles keep their meaning (an indel's padding base moves)
|
|
410
|
+
if all(len(x) == len(ref) and re.fullmatch('[ACGTNacgtn]+', x) for x in alts):
|
|
411
|
+
f[3] = ref.translate(COMP)[::-1]
|
|
412
|
+
f[4] = ','.join(x.upper().translate(COMP)[::-1] for x in alts)
|
|
413
|
+
ref = f[3]
|
|
414
|
+
else:
|
|
415
|
+
sp = None
|
|
416
|
+
if sp is None:
|
|
417
|
+
unmapped.append(line); stats['unmapped'] += 1; continue
|
|
418
|
+
p2 = sp['start']
|
|
419
|
+
flags = []
|
|
420
|
+
m = re.search(r'(^|;)END=(\d+)', f[7]) if len(f) > 7 else None
|
|
421
|
+
if m:
|
|
422
|
+
info_end = int(m.group(2))
|
|
423
|
+
e = lifter.span(c, pos, info_end)
|
|
424
|
+
if e is None or e['flip'] or e['contig'] != c2:
|
|
425
|
+
unmapped.append(line); stats['unmapped'] += 1; continue
|
|
426
|
+
f[7] = f[7][:m.start(2)] + str(e['end']) + f[7][m.end(2):]
|
|
427
|
+
if lifter.touched(c, pos + 1, info_end):
|
|
428
|
+
flags.append('at_span_changed')
|
|
429
|
+
f[0], f[1] = c2, str(p2)
|
|
430
|
+
if seqs_b.get(c2, '')[p2 - 1:p2 - 1 + len(ref)] != ref:
|
|
431
|
+
flags.append('at_ref_changed')
|
|
432
|
+
if flags:
|
|
433
|
+
f[6] = ';'.join(flags) if f[6] in ('.', 'PASS', '') else f[6] + ';' + ';'.join(flags)
|
|
434
|
+
for x in flags:
|
|
435
|
+
stats[x.replace('at_', '')] += 1
|
|
436
|
+
else:
|
|
437
|
+
stats['exact'] += 1
|
|
438
|
+
fo.write('\t'.join(f) + '\n')
|
|
439
|
+
return dict(stats), unmapped
|
|
440
|
+
|
|
441
|
+
|
|
442
|
+
def lift_file(kind, src, dst, events, names, seqs_b: dict, unmatched=(), unresolved=(), reference=None,
|
|
443
|
+
frames=None, post=None):
|
|
444
|
+
"""Lift one file; ``frames``/``post`` are the source-side and target-side frames (see ``transition``)."""
|
|
445
|
+
lifter = Lifter(events, names, unmatched, unresolved, pre=frames, post=post)
|
|
446
|
+
if kind == 'gff':
|
|
447
|
+
return lift_gff(src, dst, lifter, {c: len(s) for c, s in seqs_b.items()}, seqs_b)
|
|
448
|
+
if kind == 'bed':
|
|
449
|
+
return lift_bed(src, dst, lifter)
|
|
450
|
+
if kind == 'vcf':
|
|
451
|
+
return lift_vcf(src, dst, lifter, seqs_b, reference)
|
|
452
|
+
raise ValueError(f'lift supports gff, bed and vcf, not {kind}')
|
|
453
|
+
|
|
454
|
+
|
|
455
|
+
def lift_pair(kind, src, dst, pair, seqs_b: dict, reference=None):
|
|
456
|
+
"""Lift a file from version A of a stored pair to version B."""
|
|
457
|
+
events, names, pre, post = transition(pair, pair['a'], pair['b'])
|
|
458
|
+
return lift_file(kind, src, dst, events, names, seqs_b, pair.get('unmatched_a', ()), pair.get('unresolved', ()),
|
|
459
|
+
reference=reference, frames=pre, post=post)
|
|
460
|
+
|
|
461
|
+
|
|
462
|
+
def kind_of(path):
|
|
463
|
+
low = str(path).lower()
|
|
464
|
+
for ext, k in (('.gff3', 'gff'), ('.gff', 'gff'), ('.gtf', 'gff'), ('.bed', 'bed'), ('.vcf', 'vcf')):
|
|
465
|
+
if low.endswith(ext) or low.endswith(ext + '.gz'):
|
|
466
|
+
return k
|
|
467
|
+
raise ValueError(f'Cannot tell the format of {path}; use .gff3, .gtf, .bed or .vcf')
|
|
@@ -0,0 +1,51 @@
|
|
|
1
|
+
"""Exact acceleration of the no-junk difflib recurrence for bounded strings.
|
|
2
|
+
|
|
3
|
+
The dynamic program, tie ordering and resulting opcodes are unchanged. NumPy
|
|
4
|
+
updates a row's matching positions in C; the standard implementation remains
|
|
5
|
+
the fallback for small regions and installations without NumPy.
|
|
6
|
+
"""
|
|
7
|
+
from difflib import Match, SequenceMatcher
|
|
8
|
+
|
|
9
|
+
|
|
10
|
+
class _ArrayMatcher(SequenceMatcher):
|
|
11
|
+
def __init__(self, a, b, np):
|
|
12
|
+
super().__init__(None, a, b, autojunk=False)
|
|
13
|
+
self._np = np
|
|
14
|
+
self._positions = {key: np.asarray(value, dtype=np.intp) for key, value in self.b2j.items()}
|
|
15
|
+
|
|
16
|
+
def find_longest_match(self, alo=0, ahi=None, blo=0, bhi=None):
|
|
17
|
+
ahi = len(self.a) if ahi is None else ahi
|
|
18
|
+
bhi = len(self.b) if bhi is None else bhi
|
|
19
|
+
if (ahi - alo) * (bhi - blo) < 65536:
|
|
20
|
+
return super().find_longest_match(alo, ahi, blo, bhi)
|
|
21
|
+
np = self._np
|
|
22
|
+
previous = np.zeros(len(self.b) + 1, dtype=np.int32)
|
|
23
|
+
current = np.zeros_like(previous)
|
|
24
|
+
best_i, best_j, best_size = alo, blo, 0
|
|
25
|
+
positions = {}
|
|
26
|
+
for key, indices in self._positions.items():
|
|
27
|
+
positions[key] = indices[indices.searchsorted(blo):indices.searchsorted(bhi)]
|
|
28
|
+
for i in range(alo, ahi):
|
|
29
|
+
current.fill(0)
|
|
30
|
+
indices = positions.get(self.a[i])
|
|
31
|
+
if indices is not None and len(indices):
|
|
32
|
+
lengths = previous[indices] + 1
|
|
33
|
+
current[indices + 1] = lengths
|
|
34
|
+
where = int(lengths.argmax())
|
|
35
|
+
size = int(lengths[where])
|
|
36
|
+
if size > best_size:
|
|
37
|
+
best_i, best_j, best_size = i - size + 1, int(indices[where]) - size + 1, size
|
|
38
|
+
previous, current = current, previous
|
|
39
|
+
return Match(best_i, best_j, best_size)
|
|
40
|
+
|
|
41
|
+
|
|
42
|
+
def local_opcodes(a, b):
|
|
43
|
+
"""Return the same opcodes as SequenceMatcher(None, a, b, autojunk=False)."""
|
|
44
|
+
if len(a) * len(b) >= 65536:
|
|
45
|
+
try:
|
|
46
|
+
import numpy as np
|
|
47
|
+
except ImportError:
|
|
48
|
+
pass
|
|
49
|
+
else:
|
|
50
|
+
return _ArrayMatcher(a, b, np).get_opcodes()
|
|
51
|
+
return SequenceMatcher(None, a, b, autojunk=False).get_opcodes()
|