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.
@@ -0,0 +1,905 @@
1
+ """Alignment-free diff of near-identical sequences and discriminating k-mers.
2
+
3
+ Assembly versions produced by polishing or manual curation differ at a few
4
+ hundred to a few thousand sites in genomes of tens of megabases. Whole-genome
5
+ alignment is unnecessary for such pairs: the walk compares the sequences in
6
+ large blocks, resolves a divergent stretch locally and resynchronises on the
7
+ next shared anchor (an exact 40-mer). Memory stays linear in the anchor
8
+ search window, not in the genome, and no external aligner is needed on any
9
+ platform.
10
+
11
+ A stretch with no shared anchor within the window (a rebuilt satellite or rDNA
12
+ array, a large insertion) is crossed by probing anchors further ahead that
13
+ occur once in each sequence near the probe; the stretch between the last
14
+ anchor and the next one becomes a single replacement event marked
15
+ ``stretch``, so the events still turn the first sequence into the second
16
+ exactly. Only when no such anchor exists is the rest of the contig reported
17
+ unresolved.
18
+
19
+ Events use the AssemblyTrace coordinate convention: SNV and DEL positions are
20
+ 1-based in the first sequence; INS positions name the base after which the
21
+ insertion occurs (0 = before the first base). ``alt_pos`` is the matching
22
+ 1-based coordinate in the second sequence (for DEL, the base before the
23
+ deleted span). Indels are left-aligned.
24
+ """
25
+ from __future__ import annotations
26
+
27
+ import bisect
28
+ from .localmatch import local_opcodes
29
+
30
+ from .core import _TRANS
31
+
32
+ K_DEFAULT = 31
33
+ ANCHOR = 40 # exact match length that re-synchronises the walk
34
+ NEAR = 512 # cheap search radius before indexing
35
+ WINDOW = 1 << 17 # indexed search radius; beyond it the stretch is unresolved
36
+ LOCAL = 4096 # difflib is used only for divergent stretches up to this size
37
+
38
+
39
+ def common_prefix(a: str, b: str) -> int:
40
+ n = min(len(a), len(b))
41
+ lo = 0
42
+ chunk = 1 << 20
43
+ while chunk >= 16:
44
+ while lo + chunk <= n and a[lo:lo + chunk] == b[lo:lo + chunk]:
45
+ lo += chunk
46
+ chunk >>= 2
47
+ while lo < n and a[lo] == b[lo]:
48
+ lo += 1
49
+ return lo
50
+
51
+
52
+ def _match_len(a: str, i: int, b: str, j: int, n: int) -> int:
53
+ """Length of the common prefix of a[i:i+n] and b[j:j+n], copying only the probed blocks."""
54
+ lo, step = 0, 64
55
+ while lo < n:
56
+ s = min(step, n - lo)
57
+ if a[i + lo:i + lo + s] != b[j + lo:j + lo + s]:
58
+ break
59
+ lo += s
60
+ step = min(step * 2, 1 << 20)
61
+ else:
62
+ return n
63
+ hi = lo + s
64
+ while hi - lo > 16:
65
+ mid = (lo + hi) // 2
66
+ if a[i + lo:i + mid] == b[j + lo:j + mid]:
67
+ lo = mid
68
+ else:
69
+ hi = mid
70
+ while lo < hi and a[i + lo] == b[j + lo]:
71
+ lo += 1
72
+ return lo
73
+
74
+
75
+ def common_suffix(a: str, b: str, limit: int) -> int:
76
+ n = min(len(a), len(b), limit)
77
+ lo = 0
78
+ chunk = 1 << 20
79
+ while chunk >= 16:
80
+ while lo + chunk <= n and a[len(a) - lo - chunk:len(a) - lo] == b[len(b) - lo - chunk:len(b) - lo]:
81
+ lo += chunk
82
+ chunk >>= 2
83
+ while lo < n and a[len(a) - lo - 1] == b[len(b) - lo - 1]:
84
+ lo += 1
85
+ return lo
86
+
87
+
88
+ def _spans(e):
89
+ """0-based half-open spans of an event in a and in b."""
90
+ if e['type'] == 'INS':
91
+ sa = e['ref_pos']; sb = e['alt_pos'] - 1
92
+ elif e['type'] == 'DEL':
93
+ sa = e['ref_pos'] - 1; sb = e['alt_pos']
94
+ else:
95
+ sa = e['ref_pos'] - 1; sb = e['alt_pos'] - 1
96
+ return sa, sa + len(e['ref']), sb, sb + len(e['alt'])
97
+
98
+
99
+ def _event(contig, sa, sb, ref, alt):
100
+ if not ref:
101
+ return {'contig': contig, 'type': 'INS', 'ref_pos': sa, 'alt_pos': sb + 1, 'ref': '', 'alt': alt}
102
+ if not alt:
103
+ return {'contig': contig, 'type': 'DEL', 'ref_pos': sa + 1, 'alt_pos': sb, 'ref': ref, 'alt': ''}
104
+ kind = 'SNV' if len(ref) == len(alt) == 1 else 'COMPLEX'
105
+ return {'contig': contig, 'type': kind, 'ref_pos': sa + 1, 'alt_pos': sb + 1, 'ref': ref, 'alt': alt}
106
+
107
+
108
+ def _emit(events, contig, kind, a_pos, b_pos, ref, alt):
109
+ """Append an event; one touching the previous one where either is an indel is merged with it.
110
+
111
+ Two touching edits with an empty side (an insertion next to a deletion, two
112
+ deletions in a row after left alignment) would leave the order of their
113
+ reversal undefined, so they become one event.
114
+ """
115
+ e = {'contig': contig, 'type': kind, 'ref_pos': a_pos, 'alt_pos': b_pos, 'ref': ref, 'alt': alt}
116
+ if events and events[-1]['contig'] == contig:
117
+ last = events[-1]
118
+ la0, la1, lb0, lb1 = _spans(last)
119
+ ea0, ea1, eb0, eb1 = _spans(e)
120
+ indel = last['type'] in ('INS', 'DEL') or kind in ('INS', 'DEL')
121
+ if indel and ea0 == la1 and eb0 == lb1:
122
+ events[-1] = _event(contig, la0, lb0, last['ref'] + ref, last['alt'] + alt)
123
+ return
124
+ events.append(e)
125
+
126
+
127
+ def _bound(events, contig):
128
+ """End, in a and in b, of the last event of this contig: left alignment must not cross it."""
129
+ if events and events[-1]['contig'] == contig:
130
+ _, ea, _, eb = _spans(events[-1])
131
+ return ea, eb
132
+ return 0, 0
133
+
134
+
135
+ def _left_align(a, b, i, j, ref, alt, bound=(0, 0)):
136
+ """Shift an indel left through a repeat; i, j are 0-based starts in a and b; never past ``bound``."""
137
+ if ref and alt:
138
+ return i, j, ref, alt
139
+ allele = ref or alt
140
+ while i > bound[0] and j > bound[1] and a[i - 1] == b[j - 1] == allele[-1]:
141
+ i -= 1; j -= 1
142
+ allele = allele[-1] + allele[:-1]
143
+ return (i, j, allele, '') if ref else (i, j, '', allele)
144
+
145
+
146
+ def _local_events(events, contig, a, b, i, ia, j, jb):
147
+ """Events for the divergent stretch a[i:ia] versus b[j:jb]."""
148
+ ra, rb = a[i:ia], b[j:jb]
149
+ p = common_prefix(ra, rb)
150
+ ra, rb, i, j = ra[p:], rb[p:], i + p, j + p
151
+ s = common_suffix(ra, rb, min(len(ra), len(rb)))
152
+ if s:
153
+ ra, rb = ra[:-s], rb[:-s]
154
+ if not ra and not rb:
155
+ return
156
+ if len(ra) + len(rb) > LOCAL:
157
+ if not ra: # pure insertion: after base i of a
158
+ _emit(events, contig, 'INS', i, j + 1, '', rb)
159
+ elif not rb: # pure deletion: alt_pos is the base before the gap in b
160
+ _emit(events, contig, 'DEL', i + 1, j, ra, '')
161
+ else:
162
+ e = _as_inversion(_event(contig, i, j, ra, rb), a, b, events, contig)
163
+ if e.get('inversion'):
164
+ events.append(e)
165
+ else:
166
+ _emit(events, contig, 'COMPLEX', i + 1, j + 1, ra, rb)
167
+ return
168
+ ops = local_opcodes(ra, rb) if (ra and rb) else \
169
+ [('replace', 0, len(ra), 0, len(rb))]
170
+ for tag, i1, i2, j1, j2 in ops:
171
+ if tag == 'equal':
172
+ continue
173
+ ref, alt = ra[i1:i2], rb[j1:j2]
174
+ q = common_prefix(ref, alt)
175
+ ref, alt, x, y = ref[q:], alt[q:], i + i1 + q, j + j1 + q
176
+ t = common_suffix(ref, alt, min(len(ref), len(alt)))
177
+ if t:
178
+ ref, alt = ref[:-t], alt[:-t]
179
+ if not ref and not alt:
180
+ continue
181
+ if len(ref) == len(alt):
182
+ for off, (u, v) in enumerate(zip(ref, alt)):
183
+ if u != v:
184
+ _emit(events, contig, 'SNV', x + off + 1, y + off + 1, u, v)
185
+ elif not ref or not alt:
186
+ x, y, ref, alt = _left_align(a, b, x, y, ref, alt, _bound(events, contig))
187
+ if not ref:
188
+ _emit(events, contig, 'INS', x, y + 1, '', alt)
189
+ else:
190
+ _emit(events, contig, 'DEL', x + 1, y, ref, '')
191
+ else:
192
+ _emit(events, contig, 'COMPLEX', x + 1, y + 1, ref, alt)
193
+
194
+
195
+ MIN_INVERSION = 50 # shortest replaced span tested for being an exact inversion
196
+ INVERSION_FLANK = 64 # bases of identical flank an inversion may extend over (trimmed as common prefix/suffix)
197
+ STRETCH_MAX = 1 << 24 # beyond this many bases, a remainder without anchor is reported unresolved, not replaced
198
+ STRETCH_SHARE = 0.5 # nor when it is most of the contig (two unrelated sequences), unless it is an exact inversion
199
+
200
+
201
+ def _as_inversion(e, a, b, events, contig):
202
+ """The event re-expressed as an exact inversion when B's allele is A's reverse complement.
203
+
204
+ The walk trims bases the two sides share at either end, and an inverted
205
+ segment and its reverse complement often share a few; the test therefore
206
+ extends the replaced span over up to INVERSION_FLANK identical bases on
207
+ each side (never into the previous event). The extended event replaces the
208
+ same bases by the same bases, so B is rebuilt exactly as before; lift can
209
+ then carry features inside it, mirrored onto the other strand.
210
+ """
211
+ ref, alt = e['ref'], e['alt']
212
+ if len(ref) != len(alt) or len(ref) < MIN_INVERSION:
213
+ return e
214
+ sa = e['ref_pos'] - 1; sb = e['alt_pos'] - 1; ea = sa + len(ref); eb = sb + len(alt)
215
+ bound_a, bound_b = _bound(events, contig)
216
+ for p in range(0, INVERSION_FLANK + 1):
217
+ if p and (sa - p < bound_a or sb - p < bound_b or a[sa - p] != b[sb - p]):
218
+ break
219
+ for q in range(0, INVERSION_FLANK + 1):
220
+ if q and (ea + q > len(a) or eb + q > len(b) or a[ea + q - 1] != b[eb + q - 1]):
221
+ break
222
+ x0, x1, y0 = sa - p, ea + q, sb - p
223
+ if b[y0] != a[x1 - 1].translate(_TRANS) or b[y0 + (x1 - x0) - 1] != a[x0].translate(_TRANS):
224
+ continue
225
+ seg = a[x0:x1]
226
+ if seg.translate(_TRANS)[::-1] == b[y0:y0 + (x1 - x0)]:
227
+ out = _event(contig, x0, y0, seg, b[y0:y0 + (x1 - x0)])
228
+ out['inversion'] = True
229
+ if e.get('stretch'):
230
+ out['stretch'] = True
231
+ return out
232
+ return e
233
+
234
+
235
+ TRUST = 512 # an anchor whose exact match runs this far is not second-guessed
236
+ RESCUE = 32768 # radius, in both sequences, searched for an anchor with a longer exact match
237
+ RESCUE_SKIP = 256 # a rescue is an indel: at most this many bases skipped on its shorter side
238
+ MATCH_CAP = 1 << 14 # exact matches are measured up to this length
239
+ MAX_HITS = 64 # anchor k-mers with more copies in the radius are skipped there
240
+
241
+
242
+ def _rescue(a, b, i, j, end_a, end_b, q0):
243
+ """Anchor within RESCUE whose exact match is longest, if it is far longer than q0.
244
+
245
+ Inside a tandem array, one unit inserted or deleted lets every unit be
246
+ aligned with its neighbour at a small cost per unit: the cheapest anchor
247
+ then follows the old diagonal and turns the indel into the differences
248
+ between units, thousands of them along the array. Only the true diagonal
249
+ is followed by a long exact match, so where the cheapest anchor's match
250
+ is short, an anchor nearby with a match several times longer is taken.
251
+ The jump must be an indel: on its shorter side it skips at most
252
+ RESCUE_SKIP bases, else a stretch of ordinary small differences would be
253
+ jumped over and reported as one replacement.
254
+ """
255
+ hi_a, hi_b = min(end_a, i + RESCUE + ANCHOR), min(end_b, j + RESCUE + ANCHOR)
256
+ index = {}
257
+ for t in range(i, hi_a - ANCHOR + 1):
258
+ index.setdefault(a[t:t + ANCHOR], []).append(t)
259
+ best, seen = None, set()
260
+ for d in range(j, hi_b - ANCHOR + 1):
261
+ hits = index.get(b[d:d + ANCHOR])
262
+ if not hits or len(hits) > MAX_HITS:
263
+ continue
264
+ for pos in hits:
265
+ k = pos - d
266
+ if k in seen or min(pos - i, d - j) > RESCUE_SKIP:
267
+ continue
268
+ seen.add(k)
269
+ q = ANCHOR + _match_len(a, pos + ANCHOR, b, d + ANCHOR, min(MATCH_CAP, end_a - pos, end_b - d) - ANCHOR)
270
+ cost = (d - j) + abs(pos - (i + d - j))
271
+ if best is None or q > best[0] or (q == best[0] and cost < best[1]):
272
+ best = (q, cost, pos, d)
273
+ if best is not None and best[0] >= max(TRUST, 4 * q0):
274
+ return best[2], best[3]
275
+ return None
276
+
277
+
278
+ RESYNC_STEPS = 32 # probes between two distances when narrowing down where the sequences agree again
279
+ RESYNC_SHIFTS = 8 # probe k-mers tried at each distance (a repeated or N-containing one is skipped)
280
+
281
+
282
+ def _unique_pair(a, b, p, lo_a, hi_a, lo_b, hi_b):
283
+ """(p, position in b) when the ANCHOR-mer at a[p] occurs once in a[lo_a:hi_a] and once in b[lo_b:hi_b]."""
284
+ kmer = a[p:p + ANCHOR]
285
+ if len(kmer) < ANCHOR or 'N' in kmer:
286
+ return None
287
+ if a.find(kmer, lo_a, hi_a) != p or a.find(kmer, p + 1, hi_a) != -1:
288
+ return None
289
+ q = b.find(kmer, lo_b, hi_b)
290
+ if q == -1 or b.find(kmer, q + 1, hi_b) != -1:
291
+ return None
292
+ return p, q
293
+
294
+
295
+ def _probe(a, b, i, j, end_a, end_b, d):
296
+ """A unique shared anchor about d bases past (i, j), searched over d + WINDOW either way in b."""
297
+ reach = d + WINDOW
298
+ for t in range(RESYNC_SHIFTS):
299
+ p = i + d + t * 997
300
+ if p + ANCHOR > end_a:
301
+ return None
302
+ hit = _unique_pair(a, b, p, max(i, p - reach), min(end_a, p + reach),
303
+ max(j, j + d - reach), min(end_b, j + d + reach + ANCHOR))
304
+ if hit:
305
+ return hit
306
+ return None
307
+
308
+
309
+ def _resync(a, b, i, j, end_a, end_b):
310
+ """The nearest anchor past a stretch with no shared anchor within WINDOW, or None.
311
+
312
+ Anchors are probed at distances doubling from WINDOW; once one is found, the
313
+ gap to the last distance without one is searched in RESYNC_STEPS steps, so the
314
+ replaced stretch is at most a few percent longer than the divergence.
315
+ """
316
+ prev, d, hit = 0, WINDOW, None
317
+ while i + d + ANCHOR <= end_a:
318
+ hit = _probe(a, b, i, j, end_a, end_b, d)
319
+ if hit:
320
+ break
321
+ prev, d = d, d * 2
322
+ else:
323
+ hit = _probe(a, b, i, j, end_a, end_b, max(0, end_a - i - ANCHOR - RESYNC_SHIFTS * 997))
324
+ if hit is None:
325
+ return None
326
+ d = hit[0] - i
327
+ step = max(ANCHOR, (d - prev) // RESYNC_STEPS)
328
+ for x in range(prev + step, d, step):
329
+ near = _probe(a, b, i, j, end_a, end_b, x)
330
+ if near and near[0] < hit[0] and near[1] >= j:
331
+ return near
332
+ return hit
333
+
334
+
335
+ def _back_match(a, i, ia, b, j, jb):
336
+ """Length of the common suffix of a[i:ia] and b[j:jb]."""
337
+ n = min(ia - i, jb - j)
338
+ lo, step = 0, 64
339
+ while lo < n:
340
+ s_ = min(step, n - lo)
341
+ if a[ia - lo - s_:ia - lo] != b[jb - lo - s_:jb - lo]:
342
+ break
343
+ lo += s_
344
+ step = min(step * 2, 1 << 20)
345
+ else:
346
+ return n
347
+ while lo < n and a[ia - lo - 1] == b[jb - lo - 1]:
348
+ lo += 1
349
+ return lo
350
+
351
+
352
+ def _anchor(a, b, i, j, end_a, end_b):
353
+ """Next shared ANCHOR-mer after a divergence, chosen to minimise the implied edit.
354
+
355
+ A candidate is a position d >= j in b whose ANCHOR-mer occurs in a at pos >= i.
356
+ Its cost is (d - j) + |pos - diag|, where diag = i + (d - j) is the position the
357
+ anchor would have without any indel: skipping bases of b plus the length of the
358
+ implied indel. The search stops once d - j alone exceeds the best cost, so the
359
+ anchor is the cheapest one; an occurrence of the same k-mer in a repeat copy far
360
+ off the diagonal is never preferred to a nearby one. Near the diagonal, substring
361
+ search is used; for indels longer than NEAR, an index of a WINDOW of a.
362
+ Where the cheapest anchor's exact match is short and its k-mer has
363
+ another copy within RESCUE (a repeat), an anchor nearby with a far longer
364
+ match is preferred (``_rescue``).
365
+ """
366
+ first = _cheapest(a, b, i, j, end_a, end_b)
367
+ if first is None:
368
+ return None
369
+ n = min(MATCH_CAP, end_a - first[0], end_b - first[1])
370
+ q0 = _match_len(a, first[0], b, first[1], n)
371
+ if q0 >= min(TRUST, n):
372
+ return first
373
+ probe = b[first[1]:first[1] + ANCHOR] # only an anchor with another copy nearby is ambiguous
374
+ lo = max(0, first[0] - RESCUE)
375
+ if a.find(probe, lo, first[0] + ANCHOR - 1) == -1 and a.find(probe, first[0] + 1, first[0] + RESCUE + ANCHOR) == -1:
376
+ return first
377
+ return _rescue(a, b, i, j, end_a, end_b, q0) or first
378
+
379
+
380
+ def _cheapest(a, b, i, j, end_a, end_b):
381
+ """Cheapest anchor (pos in a, d in b)."""
382
+ best = None
383
+ for d in range(j, min(end_b, j + NEAR) - ANCHOR + 1):
384
+ if best is not None and d - j >= best[0]:
385
+ break
386
+ probe = b[d:d + ANCHOR]
387
+ diag = i + (d - j)
388
+ tol = NEAR if best is None else best[0] - (d - j)
389
+ lo, hi = max(i, diag - tol), min(end_a, diag + tol + ANCHOR)
390
+ pos = a.find(probe, lo, hi)
391
+ while pos != -1:
392
+ cost = (d - j) + abs(pos - diag)
393
+ if best is None or cost < best[0]:
394
+ best = (cost, pos, d)
395
+ if pos >= diag:
396
+ break
397
+ pos = a.find(probe, pos + 1, hi)
398
+ if best is not None:
399
+ return best[1], best[2]
400
+ hi_a = min(end_a, i + WINDOW)
401
+ index = {}
402
+ seg = a[i:hi_a]
403
+ for t in range(len(seg) - ANCHOR + 1):
404
+ index.setdefault(seg[t:t + ANCHOR], []).append(t + i)
405
+ for d in range(j, min(end_b, j + WINDOW) - ANCHOR + 1):
406
+ if best is not None and d - j >= best[0]:
407
+ break
408
+ hits = index.get(b[d:d + ANCHOR])
409
+ if hits:
410
+ diag = i + (d - j)
411
+ pos = min(hits, key=lambda x: abs(x - diag))
412
+ cost = (d - j) + abs(pos - diag)
413
+ if best is None or cost < best[0]:
414
+ best = (cost, pos, d)
415
+ return None if best is None else (best[1], best[2])
416
+
417
+
418
+ def diff_sequences(a: str, b: str, contig: str = '') -> dict:
419
+ """Return events turning ``a`` into ``b`` plus an unresolved record if any."""
420
+ a, b = a.upper(), b.upper()
421
+ events = []
422
+ if a == b:
423
+ return {'events': events, 'unresolved': None, 'compared_bases': len(a)}
424
+ p = common_prefix(a, b)
425
+ s = common_suffix(a, b, min(len(a), len(b)) - p)
426
+ i, j = p, p
427
+ end_a, end_b = len(a) - s, len(b) - s
428
+ unresolved = None
429
+ while i < end_a or j < end_b:
430
+ if i >= end_a or j >= end_b:
431
+ _local_events(events, contig, a, b, i, end_a, j, end_b)
432
+ break
433
+ hit = _anchor(a, b, i, j, end_a, end_b)
434
+ if hit is None:
435
+ if (end_a - i) + (end_b - j) <= LOCAL:
436
+ _local_events(events, contig, a, b, i, end_a, j, end_b)
437
+ break
438
+ far = _resync(a, b, i, j, end_a, end_b)
439
+ if far is None:
440
+ # No shared anchor before the common suffix: the rest up to it is one replacement, which
441
+ # still rebuilds B exactly (an inversion, a novel or rebuilt sequence at the end of a contig).
442
+ rest = (end_a - i) + (end_b - j)
443
+ e = _event(contig, i, j, a[i:end_a], b[j:end_b]) if rest <= STRETCH_MAX else None
444
+ if e is not None:
445
+ e['stretch'] = True
446
+ e = _as_inversion(e, a, b, events, contig)
447
+ if e is not None and (e.get('inversion') or rest <= STRETCH_SHARE * (len(a) + len(b))):
448
+ events.append(e)
449
+ break
450
+ unresolved = {'contig': contig, 'ref_pos': i + 1, 'alt_pos': j + 1,
451
+ 'reason': 'divergence_exceeds_window',
452
+ 'remaining_a': end_a - i, 'remaining_b': end_b - j}
453
+ break
454
+ ia, jb = far
455
+ back = _back_match(a, i, ia, b, j, jb) # the replacement ends where the sequences start to agree
456
+ if ia - back > i or jb - back > j:
457
+ e = _event(contig, i, j, a[i:ia - back], b[j:jb - back])
458
+ e['stretch'] = True
459
+ events.append(_as_inversion(e, a, b, events, contig))
460
+ i, j = ia, jb
461
+ continue
462
+ ia, jb = hit
463
+ _local_events(events, contig, a, b, i, ia, j, jb)
464
+ q = _match_len(a, ia, b, jb, min(end_a - ia, end_b - jb))
465
+ i, j = ia + q, jb + q
466
+ return {'events': _refine(events, a, b, contig), 'unresolved': unresolved, 'compared_bases': len(a)}
467
+
468
+
469
+ # ------------------------------------------------------------------ parsimony of clustered events
470
+
471
+ REFINE_TRIGGER = 50 # a cluster is re-aligned when one of its events replaces at least this many bases
472
+ REFINE_GAP = 2000 # events closer than this form one cluster
473
+ REFINE_MAX = 20000 # largest cluster span (each side) re-aligned
474
+ REFINE_BAND = 48 # band of the alignment around the diagonal shift
475
+ REFINE_IDENTITY = 0.8 # a re-alignment matching fewer of the span's bases is of unrelated sequence (random: about 0.6)
476
+
477
+
478
+ GAP_OPEN, GAP_EXTEND = 4.0, 0.1 # affine costs used to choose between descriptions of one span
479
+
480
+
481
+ def _cost(e):
482
+ return max(len(e['ref']), len(e['alt']), 1)
483
+
484
+
485
+ def _affine(e):
486
+ """Affine cost of an event: mismatched bases, plus a gap opened for any length difference."""
487
+ r, a = len(e['ref']), len(e['alt'])
488
+ d = abs(r - a)
489
+ return min(r, a) + (GAP_OPEN + GAP_EXTEND * d if d else 0.0)
490
+
491
+
492
+ REFINE_CELLS = 4_000_000 # largest alignment matrix (band cells) computed
493
+
494
+
495
+ def _banded_ops(x, y, band):
496
+ """Affine-gap edit script of x into y (list of '=', 'X', 'I', 'D') and its cost, or None.
497
+
498
+ Gotoh's three-state recursion (mismatch 1, gap GAP_OPEN + GAP_EXTEND per base) within a band around the
499
+ diagonal shift; a gap is opened once and extended, so an insertion in a repeat stays one event rather than
500
+ interleaved single bases. Directions are kept as bytes. None when the band would exceed REFINE_CELLS or
501
+ the path leaves it.
502
+ """
503
+ n, m = len(x), len(y)
504
+ k = m - n
505
+ lo, hi = min(0, k) - band, max(0, k) + band
506
+ width = hi - lo + 1
507
+ if (n + 1) * width > REFINE_CELLS:
508
+ return None
509
+ INF = float('inf')
510
+ go, ge = GAP_OPEN + GAP_EXTEND, GAP_EXTEND
511
+ # state 0: last op diagonal; 1: deletion (x consumed); 2: insertion (y consumed)
512
+ M = [INF] * width; D = [INF] * width; I = [INF] * width
513
+ t0 = -lo
514
+ if 0 <= t0 < width:
515
+ M[t0] = 0.0
516
+ for t in range(t0 + 1, width): # row 0: insertions only
517
+ j = t + lo
518
+ if 0 < j <= m:
519
+ I[t] = GAP_OPEN + GAP_EXTEND * j
520
+ tb = [(bytearray(width), bytearray(width), bytearray(width))]
521
+ for i in range(1, n + 1):
522
+ M2 = [INF] * width; D2 = [INF] * width; I2 = [INF] * width
523
+ bm, bd, bi = bytearray(width), bytearray(width), bytearray(width)
524
+ xi = x[i - 1]
525
+ for t in range(width):
526
+ j = i + lo + t
527
+ if j < 0 or j > m:
528
+ continue
529
+ if j >= 1: # diagonal from (i-1, j-1): offset t in the previous row
530
+ pm, pd, pi = M[t], D[t], I[t]
531
+ best, src = pm, 0
532
+ if pd < best:
533
+ best, src = pd, 1
534
+ if pi < best:
535
+ best, src = pi, 2
536
+ if best < INF:
537
+ M2[t] = best + (xi != y[j - 1]); bm[t] = src
538
+ if t + 1 < width: # deletion from (i-1, j): offset t + 1
539
+ om, od, oi = M[t + 1] + go, D[t + 1] + ge, I[t + 1] + go
540
+ best, src = om, 0
541
+ if od < best:
542
+ best, src = od, 1
543
+ if oi < best:
544
+ best, src = oi, 2
545
+ D2[t] = best; bd[t] = src
546
+ if t >= 1 and j >= 1: # insertion from (i, j-1): offset t - 1, this row
547
+ om, od, oi = M2[t - 1] + go, D2[t - 1] + go, I2[t - 1] + ge
548
+ best, src = om, 0
549
+ if od < best:
550
+ best, src = od, 1
551
+ if oi < best:
552
+ best, src = oi, 2
553
+ I2[t] = best; bi[t] = src
554
+ tb.append((bm, bd, bi)); M, D, I = M2, D2, I2
555
+ tm = m - n - lo
556
+ if not (0 <= tm < width):
557
+ return None
558
+ ends = (M[tm], D[tm], I[tm])
559
+ cost = min(ends)
560
+ if cost == INF:
561
+ return None
562
+ state = ends.index(cost)
563
+ ops, i, j = [], n, m
564
+ while i > 0 or j > 0:
565
+ t = j - i - lo
566
+ if i == 0:
567
+ ops.append('I'); j -= 1; continue
568
+ bm, bd, bi = tb[i]
569
+ if state == 0:
570
+ if j == 0:
571
+ return None
572
+ ops.append('=' if x[i - 1] == y[j - 1] else 'X'); state = bm[t]; i -= 1; j -= 1
573
+ elif state == 1:
574
+ ops.append('D'); state = bd[t]; i -= 1
575
+ else:
576
+ if j == 0:
577
+ return None
578
+ ops.append('I'); state = bi[t]; j -= 1
579
+ return ops[::-1], cost
580
+
581
+
582
+ def _refine(events, a, b, contig):
583
+ """Clusters of nearby events re-aligned by banded edit distance when that costs fewer edited bases.
584
+
585
+ The anchored walk can describe a small change inside a tandem array as a
586
+ whole unit moved plus a replacement (both exact, but hundreds of bases
587
+ where two or three changed). A cluster of events within REFINE_GAP of each
588
+ other that holds an event of at least REFINE_TRIGGER bases (not a stretch or
589
+ an inversion) is re-aligned over its span; the new events are kept only if
590
+ they edit fewer bases, cost less under affine gap costs (open 4, extend 0.1
591
+ per base: a unit inserted in a divergent satellite stays one gap) and
592
+ rebuild the span exactly. An insertion and a deletion of about the same size within
593
+ REFINE_MAX of each other form one cluster: between them the walk followed
594
+ another copy of a repeat.
595
+ """
596
+ if not any(_cost(e) >= REFINE_TRIGGER and not e.get('stretch') and not e.get('inversion') for e in events):
597
+ return events
598
+ # an insertion and deletions of about the same total size a few kb apart (net change of opposite sign): between them
599
+ # the walk followed another copy of a repeat, so everything between them is one cluster
600
+ net = [len(e['alt']) - len(e['ref']) for e in events]
601
+ spans = [_spans(e) for e in events]
602
+ joined = [False] * len(events) # joined[k]: event k belongs with event k - 1
603
+ for i, d in enumerate(net):
604
+ if abs(d) < REFINE_TRIGGER or events[i].get('stretch') or events[i].get('inversion'):
605
+ continue
606
+ pos, neg = max(d, 0), max(-d, 0)
607
+ for j in range(i + 1, len(events)):
608
+ if spans[j][0] - spans[i][1] > REFINE_MAX or events[j].get('stretch') or events[j].get('inversion'):
609
+ break
610
+ pos += max(net[j], 0); neg += max(-net[j], 0)
611
+ # the opposite change, in one or several events: insertions and deletions nearly cancel
612
+ if net[j] * d < 0 and min(pos, neg) >= REFINE_TRIGGER and abs(pos - neg) <= 0.2 * max(pos, neg):
613
+ for k in range(i + 1, j + 1):
614
+ joined[k] = True
615
+ break
616
+ # windows: each costly event, or each insertion-deletion detour with everything between, plus neighbouring
617
+ # events within REFINE_GAP; all other events are left as they are
618
+ core = [_cost(e) >= REFINE_TRIGGER and not e.get('stretch') and not e.get('inversion') for e in events]
619
+ groups, k = [], 0
620
+ while k < len(events):
621
+ if not core[k]:
622
+ k += 1; continue
623
+ lo_, hi_ = k, k
624
+ while hi_ + 1 < len(events) and joined[hi_ + 1]:
625
+ hi_ += 1
626
+ groups.append([lo_, hi_]); k = hi_ + 1
627
+ for g in groups:
628
+ while g[0] > 0 and spans[g[0]][0] - spans[g[0] - 1][1] <= REFINE_GAP and not events[g[0] - 1].get('stretch') \
629
+ and not events[g[0] - 1].get('inversion') and spans[g[1]][1] - spans[g[0] - 1][0] <= REFINE_MAX:
630
+ g[0] -= 1
631
+ while g[1] + 1 < len(events) and spans[g[1] + 1][0] - spans[g[1]][1] <= REFINE_GAP \
632
+ and not events[g[1] + 1].get('stretch') and not events[g[1] + 1].get('inversion') \
633
+ and spans[g[1] + 1][1] - spans[g[0]][0] <= REFINE_MAX:
634
+ g[1] += 1
635
+ merged = []
636
+ for g in groups:
637
+ if merged and g[0] <= merged[-1][1] + 1:
638
+ merged[-1][1] = max(merged[-1][1], g[1])
639
+ else:
640
+ merged.append(list(g))
641
+ clusters, k = [], 0
642
+ for lo_, hi_ in merged:
643
+ clusters += [[(*spans[t], events[t])] for t in range(k, lo_)]
644
+ clusters.append([(*spans[t], events[t]) for t in range(lo_, hi_ + 1)])
645
+ k = hi_ + 1
646
+ clusters += [[(*spans[t], events[t])] for t in range(k, len(events))]
647
+ out = []
648
+ for cl in clusters:
649
+ evs = [x[4] for x in cl]
650
+ if not any(_cost(e) >= REFINE_TRIGGER and not e.get('stretch') and not e.get('inversion') for e in evs):
651
+ out.extend(evs); continue
652
+ sa, sb = cl[0][0], cl[0][2]
653
+ ea, eb = max(x[1] for x in cl), max(x[3] for x in cl)
654
+ if ea - sa > REFINE_MAX or eb - sb > REFINE_MAX:
655
+ out.extend(evs); continue
656
+ x, y = a[sa:ea], b[sb:eb]
657
+ res = _banded_ops(x, y, REFINE_BAND)
658
+ # an alignment that matches few bases describes unrelated sequence, not edits: the span stays replaced
659
+ if res is None or res[1] >= sum(_affine(e) for e in evs) or \
660
+ res[0].count('=') < REFINE_IDENTITY * max(len(x), len(y)):
661
+ out.extend(evs); continue
662
+ new = list(out)
663
+ i = j = 0
664
+ ops = res[0]
665
+ t = 0
666
+ while t < len(ops):
667
+ o = ops[t]
668
+ if o == '=':
669
+ i += 1; j += 1; t += 1; continue
670
+ if o == 'X':
671
+ _emit(new, contig, 'SNV', sa + i + 1, sb + j + 1, x[i], y[j]); i += 1; j += 1; t += 1; continue
672
+ u = t
673
+ while u < len(ops) and ops[u] == o:
674
+ u += 1
675
+ n_ = u - t
676
+ if o == 'D':
677
+ bd = _bound(new, contig)
678
+ xi, yj, ref, alt = _left_align(a, b, sa + i, sb + j, x[i:i + n_], '', (max(bd[0], sa), max(bd[1], sb)))
679
+ _emit(new, contig, 'DEL', xi + 1, yj, ref, '')
680
+ i += n_
681
+ else:
682
+ bd = _bound(new, contig)
683
+ xi, yj, ref, alt = _left_align(a, b, sa + i, sb + j, '', y[j:j + n_], (max(bd[0], sa), max(bd[1], sb)))
684
+ _emit(new, contig, 'INS', xi, yj + 1, '', alt)
685
+ j += n_
686
+ t = u
687
+ added = new[len(out):]
688
+ # the re-aligned events must rebuild the span exactly
689
+ span = list(x)
690
+ for e in sorted(added, key=lambda e: e['ref_pos'] + (0.5 if not e['ref'] else 0), reverse=True):
691
+ if e['ref']:
692
+ k = e['ref_pos'] - 1 - sa
693
+ if k < 0 or ''.join(span[k:k + len(e['ref'])]) != e['ref']:
694
+ span = None; break
695
+ span[k:k + len(e['ref'])] = list(e['alt'])
696
+ else:
697
+ k = e['ref_pos'] - sa
698
+ if k < 0:
699
+ span = None; break
700
+ span[k:k] = list(e['alt'])
701
+ # a unit inserted in a divergent satellite is one change even when scattered edits cost fewer bases:
702
+ # the re-alignment is kept only if it does not split the cluster into more events than one extra
703
+ # kept only when cheaper under affine gap costs too: a unit inserted in a divergent satellite stays one
704
+ # gap rather than scattered edits that cost fewer bases
705
+ if span is None or ''.join(span) != y or len(new) < len(out) or new[:len(out)] != out \
706
+ or sum(_affine(e) for e in added) >= sum(_affine(e) for e in evs):
707
+ out.extend(evs)
708
+ else:
709
+ out = new
710
+ return out
711
+
712
+
713
+ # ------------------------------------------------------------------ orientation of circular or reversed contigs
714
+
715
+ PROBES = 24 # anchor probes used to tell a rotated or reversed contig from a colinear one
716
+ COLINEAR_WINDOW = 20000
717
+
718
+
719
+ def rc(seq: str) -> str:
720
+ return seq.translate(_TRANS)[::-1]
721
+
722
+
723
+ def orient(seq: str, t) -> str:
724
+ """A contig in the frame of its partner: reverse complemented if ``t['strand']`` is '-', then rotated."""
725
+ if not t:
726
+ return seq
727
+ s = rc(seq) if t['strand'] == '-' else seq
728
+ off = t['offset'] % len(s) if s else 0
729
+ return s[off:] + s[:off]
730
+
731
+
732
+ def to_frame(p: int, t) -> int:
733
+ """1-based position of A in the oriented frame."""
734
+ if not t:
735
+ return p
736
+ n = t['length']
737
+ q = n - p + 1 if t['strand'] == '-' else p
738
+ return (q - 1 - t['offset']) % n + 1
739
+
740
+
741
+ def from_frame(q: int, t) -> int:
742
+ """1-based position of the oriented frame in A."""
743
+ if not t:
744
+ return q
745
+ n = t['length']
746
+ r = (q - 1 + t['offset']) % n + 1
747
+ return n - r + 1 if t['strand'] == '-' else r
748
+
749
+
750
+ def _unique_find(hay: str, needle: str) -> int:
751
+ i = hay.find(needle)
752
+ return i if i != -1 and hay.find(needle, i + 1) == -1 else -1
753
+
754
+
755
+ def detect_orientation(a: str, b: str):
756
+ """{'strand', 'offset', 'length'} when B is A rotated and/or reverse complemented (with edits), else None.
757
+
758
+ A colinear pair is recognised cheaply: an anchor near A's start lies near B's
759
+ start and one near A's end near B's end. Otherwise PROBES anchors spread over
760
+ A that occur once in A are looked up in B on both strands; the strand with
761
+ most unique hits is taken, and the rotation is the offset that the hits share
762
+ (circular difference of positions, within 1% of the length), refined by
763
+ locating B's first unique anchor in A. Fewer than half of the probes hitting
764
+ one strand means the contigs are not two orientations of one sequence.
765
+ """
766
+ n = len(a)
767
+ if n < 4 * ANCHOR or not b:
768
+ return None
769
+
770
+ def near(seq_a, x, lo, hi):
771
+ km = seq_a[x:x + ANCHOR]
772
+ return 'N' not in km and b.find(km, max(0, lo), min(len(b), hi)) != -1
773
+ if any(near(a, x, 0, x + COLINEAR_WINDOW) for x in (0, 200, 1000, 3000) if x + ANCHOR <= n) and \
774
+ any(near(a, n - ANCHOR - x, len(b) - x - COLINEAR_WINDOW, len(b)) for x in (0, 200, 1000, 3000) if n - ANCHOR - x >= 0):
775
+ return None
776
+ best = None
777
+ for strand in ('+', '-'):
778
+ s = a if strand == '+' else rc(a)
779
+ hits = []
780
+ for t in range(PROBES):
781
+ p = (n - ANCHOR) * t // PROBES
782
+ for shift in range(0, 2000, 97):
783
+ km = s[p + shift:p + shift + ANCHOR]
784
+ if len(km) < ANCHOR or 'N' in km or _unique_find(s, km) == -1:
785
+ continue
786
+ h = _unique_find(b, km)
787
+ if h != -1:
788
+ hits.append((p + shift, h))
789
+ break
790
+ if best is None or len(hits) > len(best[1]):
791
+ best = (strand, hits, s)
792
+ strand, hits, s = best
793
+ if len(hits) < PROBES // 2:
794
+ return None
795
+ offs = sorted((p - h) % n for p, h in hits)
796
+ tol = max(ANCHOR, n // 100)
797
+ cluster = max((sum(1 for y in offs if min(abs(y - x), n - abs(y - x)) <= tol), x) for x in offs)
798
+ if cluster[0] < len(hits) // 2:
799
+ return None
800
+ off = cluster[1]
801
+ for x in range(0, min(len(b) - ANCHOR, 5000)):
802
+ km = b[x:x + ANCHOR]
803
+ if 'N' in km:
804
+ continue
805
+ y = _unique_find(s, km)
806
+ if y != -1:
807
+ cand = (y - x) % n
808
+ if min(abs(cand - off), n - abs(cand - off)) <= tol:
809
+ off = cand
810
+ break
811
+ if strand == '+' and min(off, n - off) <= COLINEAR_WINDOW:
812
+ return None
813
+ return {'strand': strand, 'offset': int(off), 'length': n}
814
+
815
+
816
+ def liftover(events):
817
+ """Map 1-based positions in A to positions in B through the event list.
818
+
819
+ The returned function gives None for a position inside a deleted or
820
+ replaced span; positions after an event are shifted by the cumulative
821
+ indel size.
822
+ """
823
+ shifts = []
824
+ for e in events:
825
+ if e['type'] == 'INS':
826
+ shifts.append((e['ref_pos'], 0, len(e['alt'])))
827
+ elif e['type'] == 'DEL':
828
+ shifts.append((e['ref_pos'], len(e['ref']), -len(e['ref'])))
829
+ elif e['type'] == 'COMPLEX':
830
+ shifts.append((e['ref_pos'], len(e['ref']), len(e['alt']) - len(e['ref'])))
831
+ shifts.sort()
832
+ thresholds, cumulative = [], [0]
833
+ for start, span, d in shifts:
834
+ thresholds.append(start if span == 0 else start + span - 1)
835
+ cumulative.append(cumulative[-1] + d)
836
+
837
+ def pos_b(pos_a: int):
838
+ i = bisect.bisect_left(thresholds, pos_a) # shifts wholly before pos_a
839
+ if i < len(shifts):
840
+ start, span, _ = shifts[i]
841
+ if span and start <= pos_a: # inside a deleted or replaced span
842
+ return None
843
+ return pos_a + cumulative[i]
844
+ return pos_b
845
+
846
+
847
+ def reverse_events(events):
848
+ """Events turning B into A, in the same coordinate convention."""
849
+ swap = {'INS': 'DEL', 'DEL': 'INS'}
850
+ out = []
851
+ for e in events:
852
+ r = {'contig': e.get('contig_b', e['contig']), 'contig_b': e['contig'], 'type': swap.get(e['type'], e['type']),
853
+ 'ref_pos': e['alt_pos'], 'alt_pos': e['ref_pos'], 'ref': e['alt'], 'alt': e['ref']}
854
+ for flag in ('stretch', 'inversion'):
855
+ if e.get(flag):
856
+ r[flag] = True
857
+ out.append(r)
858
+ return out
859
+
860
+
861
+ def canonical(kmer: str) -> str:
862
+ rc = kmer.translate(_TRANS)[::-1]
863
+ return kmer if kmer <= rc else rc
864
+
865
+
866
+ def event_kmers(seq: str, pos: int, span: int, k: int = K_DEFAULT) -> set:
867
+ """Canonical k-mers overlapping a 1-based span of ``span`` bases.
868
+
869
+ ``span`` of 0 means the junction after base ``pos`` (0 = before the first
870
+ base): every k-mer that straddles that junction is returned.
871
+ """
872
+ if span:
873
+ first = pos - 1
874
+ last = first + span - 1
875
+ lo, hi = max(0, last - k + 1), min(len(seq) - k, first)
876
+ else:
877
+ lo, hi = max(0, pos - k + 1), min(len(seq) - k, pos - 1)
878
+ out = set()
879
+ for start in range(lo, hi + 1):
880
+ kmer = seq[start:start + k]
881
+ if len(kmer) == k and 'N' not in kmer:
882
+ out.add(canonical(kmer))
883
+ return out
884
+
885
+
886
+ def discriminating_kmers(a: str, b: str, events, k: int = K_DEFAULT) -> list:
887
+ """Per event, the canonical k-mers specific to A and to B at that site."""
888
+ a, b = a.upper(), b.upper()
889
+ out = []
890
+ for idx, e in enumerate(events):
891
+ if e.get('stretch'): # a replaced stretch is not a site: no panel
892
+ out.append({'event': idx, 'kmers_a': [], 'kmers_b': []})
893
+ continue
894
+ if e['type'] == 'INS':
895
+ ka = event_kmers(a, e['ref_pos'], 0, k)
896
+ kb = event_kmers(b, e['alt_pos'], len(e['alt']), k)
897
+ elif e['type'] == 'DEL':
898
+ ka = event_kmers(a, e['ref_pos'], len(e['ref']), k)
899
+ kb = event_kmers(b, e['alt_pos'], 0, k)
900
+ else:
901
+ ka = event_kmers(a, e['ref_pos'], len(e['ref']), k)
902
+ kb = event_kmers(b, e['alt_pos'], len(e['alt']), k)
903
+ shared = ka & kb
904
+ out.append({'event': idx, 'kmers_a': sorted(ka - shared), 'kmers_b': sorted(kb - shared)})
905
+ return out