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,1388 @@
1
+ """Attribute every version-bound artefact to the assembly version it was made from.
2
+
3
+ Provenance evidence must depend on the reference, not on the sample. Reads
4
+ carry the sample's true alleles whichever version they were aligned to, so
5
+ read sequences never enter attribution.
6
+
7
+ Evidence items are grouped by the mechanism that produced them inside one
8
+ file, because the ways a file comes to point at the wrong version act on the
9
+ whole file, not on single items: a caller given another FASTA, calls against
10
+ two versions concatenated, a header copied or rewritten, MD tags regenerated
11
+ against another reference, an annotation lifted from elsewhere. Items within a
12
+ group are therefore not independent evidence.
13
+
14
+ group items item e group d
15
+ header names, exact lengths, M5 and sequence digests 0.01* 0.01
16
+ coordinates names and coordinate bounds only 0.05 0.05
17
+ ref_alleles VCF REF alleles at sites where versions differ 0.01 0.01
18
+ md_bases reference bases implied by BAM MD tags 0.02 0.05
19
+ proteins proteins, CDS or protein MD5s against the
20
+ translations of their CDS under each version 0.01 0.02
21
+ metrics summary statistics of one report 0.05 0.10
22
+ cds_frame gene models intact under a version (quality,
23
+ not provenance; skipped for transferred models) 0.05 0.30
24
+ label a version's file name in a command or header 0.20 0.30
25
+ (* 0.001 for M5 and sequence digests)
26
+
27
+ Within a group, item i names the set S_i of versions consistent with it, and
28
+ L_g(v) = prod_i (1 - e_i)^[v in S_i] e_i^[v not in S_i]. With probability d the
29
+ whole group reflects some other listed version (or none), so the group
30
+ likelihood is P_g(v) = (1 - d) L_g(v) + d sum_u prior(u) L_g(u). The prior is
31
+ uniform over content classes and split equally among the renamed or reordered
32
+ copies inside a class; the same weights govern the misleading-group mixture.
33
+ Thus adding equivalent copies does not change the mixture's class weights.
34
+ Groups multiply. Version selection and the reported version Bayes factor use
35
+ likelihoods, not posterior odds. Content-class results marginalize over member
36
+ versions and are reported separately from resolution of a particular version.
37
+
38
+ Each group is also checked against its own best version: if the number of
39
+ items inconsistent with it is improbable under the item error (binomial tail
40
+ below 0.001 with at least 3 such items), no listed version explains that
41
+ group, and the file is reported as inconsistent with every version (a file
42
+ made from a version not in the project, or mixed from several). Groups that
43
+ favour versions of different content classes with a group log10 Bayes factor
44
+ of 1 or more are reported as conflicting evidence. Otherwise the best version is labelled on
45
+ Jeffreys' (1961) scale of the Bayes factor against the runner-up: decisive
46
+ (log10 >= 2), very strong (>= 1.5), strong (>= 1), substantial (>= 0.5),
47
+ weak. Posteriors are among the listed versions only and conditional on the
48
+ model; they say nothing about versions that are absent from the project.
49
+ """
50
+ from __future__ import annotations
51
+
52
+ import math
53
+ import random
54
+ import re
55
+ from collections import Counter, defaultdict
56
+ from pathlib import Path, PurePosixPath
57
+
58
+ from .core import _contigs, _open, _TRANS
59
+ from .annotation import parse_gff, _translate, _proteins, _without_terminal_stop
60
+
61
+ # A protein is the translation of a gene model moved exactly into a version, so in a file made from a listed version
62
+ # every protein fits that version. On the development data (234 protein files of 26 real projects and 1,416 of
63
+ # synthetic seeds 31 to 50, freeze 8) 1 of 3,697,504 proteins fit no version (95% upper bound 1.3e-6); 1e-5 keeps the
64
+ # same margin as MD. At 0.01, the 14 to 27 proteins of a missing version of the same layout among about 1,800 passed.
65
+ PROTEIN_ERROR = 1e-5
66
+ # Share of complete gene models, away from changed sites, that read as no open frame on the assembly they were
67
+ # predicted on (unflagged pseudogenes, models a predictor closed early). Census pilot (protocol 4.9): 2 of 198,474
68
+ # models in 20 published annotations, at most 1 in 5,572 (1.8e-4) in one file; 0.002 is ten times that file's rate.
69
+ FRAME_FIT_ERROR = 0.002
70
+ GROUPS = {
71
+ 'header': (0.01, 0.01),
72
+ 'coordinates': (0.05, 0.05),
73
+ 'ref_alleles': (0.01, 0.01),
74
+ 'md_bases': (0.02, 0.05),
75
+ 'proteins': (PROTEIN_ERROR, 0.02),
76
+ 'metrics': (0.05, 0.10),
77
+ 'cds_frame': (0.05, 0.30),
78
+ 'cds_fit': (FRAME_FIT_ERROR, 0.01),
79
+ 'label': (0.20, 0.30),
80
+ 'sequences': (0.001, 0.01),
81
+ 'digests': (0.001, 0.01),
82
+ }
83
+ DIGEST_ERROR = 0.001
84
+ STRONG_GROUPS = ('header', 'coordinates', 'ref_alleles', 'md_bases', 'proteins', 'digests')
85
+ # Groups that read the bases of the reference itself. Names, lengths, coordinate bounds, summary statistics and
86
+ # file names fit any version of equal layout, listed or not (polishing rounds often keep every length), and intact
87
+ # reading frames fit any version without a frame-breaking difference, so without one of these groups no
88
+ # attribution is reported as confident.
89
+ CONTENT_GROUPS = ('ref_alleles', 'md_bases', 'proteins', 'sequences', 'digests')
90
+ CAPPED_STATUS = 'substantial'
91
+ # A version that is not listed is seen only where the file tests a base at which it differs, so a confident label
92
+ # also needs the file to test the reference at enough places (VCF records, MD sites and reads, genes), unless it
93
+ # carries digests of whole sequences, which test every base.
94
+ WHOLE_SEQUENCE_GROUPS = ('digests', 'sequences')
95
+ MIN_CONTENT_OBSERVATIONS = 50
96
+ JEFFREYS = ((2.0, 'decisive'), (1.5, 'very_strong'), (1.0, 'strong'), (0.5, 'substantial'))
97
+ ATTRIBUTED = ('decisive', 'very_strong', 'strong', 'substantial', 'weak')
98
+ CONFIDENT = ('decisive', 'very_strong', 'strong')
99
+ FIT_P, FIT_MIN = 1e-3, 3
100
+ CONFLICT_LOG10 = 1.0
101
+ MAX_PROTEIN_CHECKS = 2000
102
+ MAX_FIT_CHECKS = 20000 # sequences away from changed sites checked for fit
103
+ FRAME_SAMPLE = 300 # genes used to tell the numbering of gene models
104
+ LINK_MIN_FIT = 0.8 # share of checked sequences a GFF must reproduce to be taken as their annotation
105
+ LINK_MIN_CHECKED = 10
106
+ MAX_MD_SITES = 300
107
+ MD_READS = 20000
108
+ MD_WINDOWS = 5000 # places over the reference where reads are sampled
109
+ MD_READS_PER_PLACE = 3
110
+ MD_BASES = 2_000_000 # aligned bases checked at most
111
+ # MD restates the reference: a read fits no listed version only if the file was made from another one. On the
112
+ # development projects (PRJEB51164, NanoVarBench, freeze-3 isolates) 0 of 1,913,427 reads of files made from a
113
+ # listed version fit no version (95% upper bound 1.6e-6); 1e-5 keeps a sixfold margin. At 0.001, thousands of
114
+ # sampled reads tolerated a dozen that fit nothing, so a file from a missing version of the same layout passed.
115
+ MD_READ_ERROR = 1e-5
116
+ NOT_VERSION_BOUND = ('fastq', 'reads_fasta', 'ubam', 'raw_signal')
117
+ TABLE_SUFFIXES = ('.txt', '.tsv', '.csv', '.tab', '.stats', '.summary', '.out', '.txt.gz', '.tsv.gz')
118
+ LIFT_ATTRIBUTES = ('valid_ORF', 'partial_mapping', 'extra_copy_number', 'copy_num_ID', 'sequence_ID',
119
+ 'low_identity', 'matches_ref_protein', 'mutation')
120
+ FASTA_EXTENSIONS = ('.fasta', '.fa', '.fna', '.fas', '.fsa')
121
+ IUPAC_FIRST = {'R': 'A', 'Y': 'C', 'S': 'C', 'W': 'A', 'K': 'G', 'M': 'A', 'B': 'C', 'D': 'A', 'H': 'A', 'V': 'A'}
122
+ LN10 = math.log(10)
123
+
124
+
125
+ def _lse(xs):
126
+ m = max(xs)
127
+ if m == float('-inf'):
128
+ return m
129
+ return m + math.log(sum(math.exp(x - m) for x in xs))
130
+
131
+
132
+ def binom_sf(k: int, n: int, p: float) -> float:
133
+ """P(X >= k) for X ~ Binomial(n, p), summed in log space."""
134
+ if k <= 0:
135
+ return 1.0
136
+ if k > n:
137
+ return 0.0
138
+ lp, lq = math.log(p), math.log1p(-p)
139
+ terms = [math.lgamma(n + 1) - math.lgamma(j + 1) - math.lgamma(n - j + 1) + j * lp + (n - j) * lq
140
+ for j in range(k, n + 1)]
141
+ return min(1.0, math.exp(_lse(terms)))
142
+
143
+
144
+ def jeffreys(log10_bf):
145
+ for cut, label in JEFFREYS:
146
+ if log10_bf >= cut:
147
+ return label
148
+ return 'weak'
149
+
150
+
151
+ class Evidence:
152
+ """Evidence items of one artefact, grouped by the mechanism that produced them."""
153
+
154
+ def __init__(self, versions):
155
+ self.versions = [v['id'] for v in versions]
156
+ self.content = {v['id']: v.get('content_class') or v['id'] for v in versions}
157
+ size = Counter(self.content.values())
158
+ self.classes = {}
159
+ for v in self.versions:
160
+ self.classes.setdefault(self.content[v], []).append(v)
161
+ self.log_prior = {v: -math.log(len(size) * size[self.content[v]]) for v in self.versions}
162
+ self.items = defaultdict(list)
163
+ self.observed = Counter()
164
+
165
+ def add(self, group: str, consistent, error: float = None):
166
+ e = GROUPS[group][0] if error is None else error
167
+ self.items[group].append((frozenset(consistent), e))
168
+ self.observed[group] += 1
169
+
170
+ def observe(self, group: str, n: int = 1):
171
+ """Observations that every listed version fits: no item, but each tested the reference at one more place."""
172
+ self.observed[group] += n
173
+
174
+ def __bool__(self):
175
+ return any(self.items.values())
176
+
177
+ def _group(self, g):
178
+ items, d = self.items[g], GROUPS[g][1]
179
+ ll = {v: sum(math.log1p(-e) if v in c else math.log(e) for c, e in items) for v in self.versions}
180
+ if len(self.versions) > 1:
181
+ mix = _lse([ll[v] + self.log_prior[v] for v in self.versions])
182
+ lp = {v: _lse([math.log1p(-d) + ll[v], math.log(d) + mix]) for v in self.versions}
183
+ else:
184
+ lp = dict(ll)
185
+ ranked = sorted(self.versions, key=lambda v: (-lp[v], int(v[1:]) if v[1:].isdigit() else 0))
186
+ own = ranked[0]
187
+ n = len(items)
188
+ k = sum(own not in c for c, _ in items)
189
+ ebar = sum(e for _, e in items) / n
190
+ # the fit test counts every observation: those that every version fits carry no item, but each was a chance
191
+ # for the best version to fail
192
+ n_obs = max(n, self.observed[g])
193
+ # Conflicts concern different sequence contents. An equally supported
194
+ # renamed copy must not hide a group's preference over another class.
195
+ runner = next((v for v in ranked if self.content[v] != self.content[own]), None)
196
+ lbf = (lp[own] - lp[runner]) / LN10 if runner is not None else None
197
+ support = Counter(v for c, _ in items for v in c)
198
+ return {'items': n, 'observations': n_obs, 'best': own, 'inconsistent_with_best': k,
199
+ 'discordance': round(k / n_obs, 4), 'fit_p': binom_sf(k, n_obs, ebar),
200
+ 'log10_bayes_factor': None if lbf is None else round(lbf, 3),
201
+ 'compared_version': runner, 'bayes_factor_scope': 'versions_from_distinct_content_classes',
202
+ 'matching_no_version': sum(1 for c, _ in items if not c),
203
+ 'consistent': {v: support.get(v, 0) for v in self.versions}, 'log_likelihood': lp}
204
+
205
+ def summary(self) -> dict:
206
+ if not self.versions:
207
+ return {'status': 'no_evidence', 'best': None, 'posterior': {}, 'log10_bayes_factor': None,
208
+ 'evidence_counts': {}, 'support': {}, 'groups': {}, 'reason': 'no_candidate_versions',
209
+ 'content_class_attribution': {'status': 'no_evidence', 'best': None, 'posterior': {},
210
+ 'log10_bayes_factor': None}}
211
+ groups = {g: self._group(g) for g in sorted(self.items) if self.items[g]}
212
+ if not groups:
213
+ return {'status': 'no_evidence', 'best': None, 'posterior': {}, 'log10_bayes_factor': None,
214
+ 'evidence_counts': {}, 'support': {}, 'groups': {},
215
+ 'content_class_attribution': {'status': 'no_evidence', 'best': None, 'posterior': {},
216
+ 'log10_bayes_factor': None}}
217
+ total = {v: sum(r['log_likelihood'][v] for r in groups.values()) for v in self.versions}
218
+ post_log = {v: total[v] + self.log_prior[v] for v in self.versions}
219
+ z = _lse(list(post_log.values()))
220
+ post = {v: math.exp(post_log[v] - z) for v in self.versions}
221
+ # A posterior-odds contrast also contains the prior odds. In particular,
222
+ # a version in a large class has a smaller prior than a singleton class;
223
+ # that is not evidence against it and must not create a confident label.
224
+ ranked = sorted(self.versions, key=lambda v: -total[v])
225
+ best = ranked[0]
226
+ lbf = (total[best] - total[ranked[1]]) / LN10 if len(ranked) > 1 else None
227
+ ties = [v for v in ranked if abs(total[v] - total[best]) < 1e-9]
228
+ class_ll = {c: _lse([total[v] for v in members]) - math.log(len(members))
229
+ for c, members in self.classes.items()}
230
+ class_ranked = sorted(self.classes, key=lambda c: -class_ll[c])
231
+ class_leading = class_ranked[0]
232
+ class_lbf = (class_ll[class_leading] - class_ll[class_ranked[1]]) / LN10 if len(class_ranked) > 1 else None
233
+ class_ties = [c for c in class_ranked if abs(class_ll[c] - class_ll[class_leading]) < 1e-9]
234
+ class_status = 'undecided' if len(class_ties) > 1 else jeffreys(class_lbf) if class_lbf is not None else 'decisive'
235
+ class_best = class_ties if len(class_ties) > 1 else class_leading
236
+ strong = [g for g in groups if g in STRONG_GROUPS]
237
+ misfit = {g: r for g, r in groups.items()
238
+ if r['inconsistent_with_best'] >= FIT_MIN and r['fit_p'] < FIT_P}
239
+ conflict = sorted(g for g, r in groups.items()
240
+ if (r['log10_bayes_factor'] or 0) >= CONFLICT_LOG10
241
+ and self.content[r['best']] != self.content[best])
242
+ closest = None
243
+ if strong and all(groups[g]['matching_no_version'] == groups[g]['items'] for g in strong):
244
+ status, best_out = 'matches_no_version', None
245
+ elif misfit:
246
+ status, best_out = 'inconsistent_with_every_version', None
247
+ g, r = max(misfit.items(), key=lambda x: x[1]['items'])
248
+ closest = {'group': g, 'version': r['best'], 'inconsistent': r['inconsistent_with_best'], 'items': r['items']}
249
+ elif conflict:
250
+ status, best_out = 'conflicting_evidence', None
251
+ elif len(ties) > 1:
252
+ status, best_out = 'undecided', ties
253
+ else:
254
+ status, best_out = (jeffreys(lbf) if lbf is not None else 'decisive'), best
255
+ if status in ('matches_no_version', 'inconsistent_with_every_version', 'conflicting_evidence'):
256
+ class_status, class_best = status, None
257
+ content_obs = sum(self.observed[g] for g in CONTENT_GROUPS)
258
+ whole = any(g in WHOLE_SEQUENCE_GROUPS for g in groups)
259
+ basis = ('content' if whole or content_obs >= MIN_CONTENT_OBSERVATIONS else 'content_sparse') \
260
+ if any(g in CONTENT_GROUPS for g in groups) else 'layout_only'
261
+ capped_from = None
262
+ if status in CONFIDENT and basis != 'content':
263
+ capped_from, status = status, CAPPED_STATUS
264
+ class_capped_from = None
265
+ if class_status in CONFIDENT and basis != 'content':
266
+ class_capped_from, class_status = class_status, CAPPED_STATUS
267
+ for r in groups.values():
268
+ r['log_likelihood'] = {v: round(x, 6) for v, x in r['log_likelihood'].items()}
269
+ return {'status': status, 'best': best_out, 'leading': best, 'posterior': post,
270
+ 'log10_bayes_factor': None if lbf is None else round(lbf, 3),
271
+ 'bayes_factor_scope': 'versions',
272
+ 'log_likelihood': {v: round(x, 6) for v, x in total.items()},
273
+ 'content_class_attribution': {
274
+ 'status': class_status, 'best': class_best, 'leading': class_leading,
275
+ 'posterior': {c: sum(post[v] for v in members) for c, members in self.classes.items()},
276
+ 'log_likelihood': {c: round(x, 6) for c, x in class_ll.items()},
277
+ 'log10_bayes_factor': None if class_lbf is None else round(class_lbf, 3),
278
+ 'bayes_factor_scope': 'content_classes', 'capped_from': class_capped_from},
279
+ 'closest': closest, 'conflicting_groups': conflict,
280
+ 'evidence_counts': {g: r['items'] for g, r in groups.items()},
281
+ 'discordance': {g: r['discordance'] for g, r in groups.items() if r['discordance']},
282
+ 'support': {g: {v: c for v, c in r['consistent'].items() if c} for g, r in groups.items()},
283
+ 'groups': groups, 'basis': basis, 'capped_from': capped_from, 'content_observations': content_obs,
284
+ 'scope': 'likelihood-based version selection; posterior among the listed versions, under the model'}
285
+
286
+
287
+ # ---------------------------------------------------------------- helpers
288
+
289
+ def coordinate_versions(names, lengths, versions) -> set:
290
+ """Versions whose contig names and lengths contain the header's."""
291
+ out = set()
292
+ if not names:
293
+ return out
294
+ pairs = set(zip(names, lengths))
295
+ for v in versions:
296
+ if pairs <= set(zip(v['names'], v['lengths'])):
297
+ out.add(v['id'])
298
+ return out
299
+
300
+
301
+ def _version_seqs(versions):
302
+ cache = {}
303
+
304
+ def get(vid):
305
+ if vid not in cache:
306
+ v = next(x for x in versions if x['id'] == vid)
307
+ cache[vid] = {h.split()[0]: s.upper() for h, s in _contigs(v['representative'])}
308
+ return cache[vid]
309
+ return get
310
+
311
+
312
+ def _stem(name):
313
+ n = name.lower()
314
+ if n.endswith('.gz'):
315
+ name, n = name[:-3], n[:-3]
316
+ for ext in FASTA_EXTENSIONS:
317
+ if n.endswith(ext):
318
+ return name[:-len(ext)]
319
+ return name
320
+
321
+
322
+ def label_versions(text, versions, *, stems=False) -> set:
323
+ """Versions one of whose file names occurs as a path token of ``text`` (basename, or stem for reports)."""
324
+ if not text:
325
+ return set()
326
+ tokens = {PurePosixPath(t.replace('\\', '/')).name for t in re.split(r'[\s=,;:\'"<>|()]+', text) if t}
327
+ tokens.discard('')
328
+ hits = set()
329
+ for v in versions:
330
+ for f in v['files']:
331
+ base = PurePosixPath(f).name
332
+ if base in tokens or (stems and _stem(base) in tokens):
333
+ hits.add(v['id'])
334
+ return hits
335
+
336
+
337
+ def _label_evidence(text, versions, ev, all_ids, *, stems=False):
338
+ hits = label_versions(text, versions, stems=stems)
339
+ if hits and hits != all_ids:
340
+ ev.add('label', hits)
341
+ return hits
342
+
343
+
344
+ def _ref_matches(ref, asm):
345
+ """A VCF REF allele against assembly bases; ambiguity codes reduce to their first base (VCF 4.3 1.6.1)."""
346
+ if len(ref) != len(asm):
347
+ return False
348
+ return all(r == a or IUPAC_FIRST.get(a) == r for r, a in zip(ref, asm))
349
+
350
+
351
+ # ---------------------------------------------------------------- coordinate systems (all formats)
352
+
353
+ def side_evidence(s, versions, ev, all_ids) -> dict:
354
+ """Names, exact lengths, coordinate bounds, sequence digests, MD5s and labels of one side."""
355
+ out = {}
356
+ if s.get('names'):
357
+ ok = set()
358
+ for v in versions:
359
+ have = dict(zip(v['names'], v['lengths']))
360
+ name = lambda n: n if n in have or '|' not in n else n.rsplit('|', 1)[-1] # gnl|db|id, lcl|id
361
+ if all(name(n) in have for n in s['names']) \
362
+ and all(have[name(n)] == l for n, l in s.get('lengths', {}).items() if name(n) in have) \
363
+ and all(have[name(n)] >= p for n, p in s.get('max_pos', {}).items() if name(n) in have):
364
+ ok.add(v['id'])
365
+ if ok != all_ids:
366
+ ev.add('header' if s.get('lengths') else 'coordinates', ok)
367
+ out['coordinate_versions'] = sorted(ok)
368
+ if s.get('digests'):
369
+ want = set(s['digests'].values())
370
+ ok = {v['id'] for v in versions if want <= set(v['sequence_digests'])}
371
+ if ok != all_ids:
372
+ ev.add('digests', ok)
373
+ out['sequence_versions'] = sorted(ok)
374
+ if s.get('md5'):
375
+ ok = set()
376
+ for v in versions:
377
+ table = dict(zip(v['names'], v.get('md5', [])))
378
+ if all(table.get(n) == d.lower() for n, d in s['md5'].items()):
379
+ ok.add(v['id'])
380
+ if ok != all_ids:
381
+ ev.add('digests', ok)
382
+ out['md5_versions'] = sorted(ok)
383
+ if s.get('labels'):
384
+ out['label_versions'] = sorted(_label_evidence(' '.join(s['labels']), versions, ev, all_ids))
385
+ return out
386
+
387
+
388
+ def kmer_total_evidence(totals, versions, ev, all_ids) -> dict:
389
+ """Per-scaffold k-mer totals (Merqury): a version fits when one k makes length - k + 1 equal every total."""
390
+ ok = set()
391
+ for v in versions:
392
+ have = dict(zip(v['names'], v['lengths']))
393
+ ks = {have[n] - t + 1 for n, t in totals.items() if n in have}
394
+ if len(ks) == 1 and all(n in have for n in totals) and 11 <= next(iter(ks)) <= 63:
395
+ ok.add(v['id'])
396
+ if ok != all_ids:
397
+ ev.add('header', ok)
398
+ return {'versions': sorted(ok), 'scaffolds': len(totals)}
399
+
400
+
401
+ def table_side(path, versions):
402
+ """A side for an arbitrary table whose rows name contigs, with an exact length column if any."""
403
+ from .formats import sniff_table, side
404
+ all_names = set()
405
+ for v in versions:
406
+ all_names.update(v['names'])
407
+ found = sniff_table(path, all_names)
408
+ if not found:
409
+ return None
410
+ lengths = {}
411
+ for col in found['numeric_columns']:
412
+ for v in versions:
413
+ have = dict(zip(v['names'], v['lengths']))
414
+ if col and all(have.get(n) == x for n, x in col.items()):
415
+ lengths = col; break
416
+ if lengths:
417
+ break
418
+ return side(found['names'], lengths)
419
+
420
+
421
+ # ---------------------------------------------------------------- alignments
422
+
423
+ def alignment_evidence(path, kind, header, versions, graph, ev, seqs, all_ids) -> dict:
424
+ out = {}
425
+ names, lengths = header.get('names', []), header.get('lengths', [])
426
+ coords = coordinate_versions(names, lengths, versions)
427
+ if names and coords != all_ids:
428
+ ev.add('header', coords)
429
+ out['coordinate_versions'] = sorted(coords)
430
+ m5 = header.get('m5') or {}
431
+ if m5:
432
+ ok = set()
433
+ for v in versions:
434
+ table = dict(zip(v['names'], v.get('md5', [])))
435
+ if all(table.get(n) == d.lower() for n, d in m5.items()):
436
+ ok.add(v['id'])
437
+ if ok != all_ids:
438
+ ev.add('digests', ok)
439
+ out['m5_versions'] = sorted(ok)
440
+ out['label_versions'] = sorted(_label_evidence(' '.join(header.get('programs', [])), versions, ev, all_ids))
441
+ # MD tags restate the reference bases: they are read against every version that has the header's contig
442
+ # names, whatever the lengths say, so a file whose layout fits one listed version is still checked for
443
+ # reads that fit none (a version of equal layout that is not in the project).
444
+ named = {v['id'] for v in versions if names and set(names) <= set(v['names'])}
445
+ if kind == 'bam' and named:
446
+ out['md'] = md_evidence(path, kind, versions, graph, sorted(named), ev, seqs)
447
+ elif len(coords) > 1 and kind == 'cram':
448
+ out['md'] = {'status': 'not_evaluated',
449
+ 'reason': 'CRAM MD tags are regenerated on decoding from the reference the header names'}
450
+ return out
451
+
452
+
453
+ def _same_coordinate(events):
454
+ """f(contig, pos): whether a 1-based position of A keeps its number in B (no net indel before it, not in an indel)."""
455
+ import bisect
456
+ by = defaultdict(list)
457
+ for e in events:
458
+ d = len(e['alt']) - len(e['ref'])
459
+ if d:
460
+ first = e['ref_pos'] + 1 if not e['ref'] else e['ref_pos'] + len(e['ref']) # first position after it
461
+ inside = (e['ref_pos'], e['ref_pos'] + len(e['ref']) - 1) if e['ref'] else None
462
+ by[e['contig']].append((first, d, inside))
463
+ tables = {}
464
+ for c, rows in by.items():
465
+ rows.sort()
466
+ cum, run = [], 0
467
+ for _, d, _ in rows:
468
+ run += d; cum.append(run)
469
+ tables[c] = ([r[0] for r in rows], cum, [r[2] for r in rows if r[2]])
470
+
471
+ def same(contig, pos):
472
+ t = tables.get(contig)
473
+ if t is None:
474
+ return True
475
+ firsts, cum, spans = t
476
+ i = bisect.bisect_right(firsts, pos) - 1
477
+ if i >= 0 and cum[i] != 0:
478
+ return False
479
+ return not any(lo <= pos <= hi for lo, hi in spans)
480
+ return same
481
+
482
+
483
+ MD_WINDOW = 20000 # bases after an indel searched for coordinates whose bases differ between candidates
484
+ MD_PER_CHANGE = 50 # at most this many such coordinates per change
485
+
486
+
487
+ def _shared_coordinates(graph, candidates, seqs=None):
488
+ """Coordinates at which the candidates' reference bases differ, with per-candidate checks.
489
+
490
+ MD tags give the reference base at a coordinate number, so any coordinate
491
+ whose base differs between candidates is evidence, whether or not an
492
+ indel shifted the numbering there: substituted bases, and the bases after
493
+ an indel, where numbering is shifted; inside a repeat the shifted bases
494
+ often agree, so the search runs on, up to MD_WINDOW, until it finds
495
+ MD_PER_CHANGE differing ones (versions of equal
496
+ length that differ by an indel pair are separated only there). Uses the
497
+ pairwise events of the graph from the first candidate to every other
498
+ (pair (r, c), or (c, r) reversed). Returns (r, {c: same-coordinate
499
+ function}, sites), or (r, None, []) when a pair is missing. Without
500
+ ``seqs`` only substituted bases at unshifted coordinates are returned.
501
+ """
502
+ from .sparsediff import reverse_events
503
+ ref = candidates[0]
504
+ same, events_of, oriented = {}, {}, set()
505
+ for c in candidates[1:]:
506
+ p = next((x for x in graph['pairs'] if (x['a'], x['b']) == (ref, c)), None)
507
+ if p is not None:
508
+ events = p['events']
509
+ else:
510
+ q = next((x for x in graph['pairs'] if (x['a'], x['b']) == (c, ref)), None)
511
+ if q is None:
512
+ return ref, None, []
513
+ p = q
514
+ events = reverse_events(q['events'])
515
+ fr = p.get('frames') or {} # contigs in frames (turned, merged, split): their events are in frame coordinates
516
+ turned = set(fr) | {b[0] for f_ in fr.values() for b in f_['blocks']} | {f_['contig_b'] for f_ in fr.values()}
517
+ oriented |= turned
518
+ events = [e for e in events if e['contig'] not in turned] # their positions are in an oriented frame
519
+ f = _same_coordinate(events)
520
+ same[c] = (lambda f_, t_: lambda contig, pos: contig not in t_ and f_(contig, pos))(f, turned)
521
+ events_of[c] = events + [{'contig': n, 'ref_pos': 1, 'ref': '', 'alt': 'N'} for n in sorted(turned)]
522
+ sites = set()
523
+ for c, events in events_of.items():
524
+ for e in events:
525
+ if seqs is None:
526
+ if e['ref'] and len(e['ref']) == len(e['alt']):
527
+ for j, (x, y) in enumerate(zip(e['ref'], e['alt'])):
528
+ q_ = e['ref_pos'] + j
529
+ if x != y and all(f(e['contig'], q_) for f in same.values()):
530
+ sites.add((e['contig'], q_))
531
+ continue
532
+ start = max(1, e['ref_pos'])
533
+ if len(e['ref']) == len(e['alt']):
534
+ end = start + len(e['ref'])
535
+ else: # numbering is shifted after an indel
536
+ end = start + MD_WINDOW + max(len(e['ref']), len(e['alt']))
537
+ cs = [seqs(v).get(e['contig'], '') for v in candidates]
538
+ end = min([end] + [len(sq) + 1 for sq in cs])
539
+ found = 0
540
+ for lo in range(start, end, 256):
541
+ hi = min(end, lo + 256)
542
+ if all(sq[lo - 1:hi - 1] == cs[0][lo - 1:hi - 1] for sq in cs[1:]):
543
+ continue
544
+ for q_ in range(lo, hi):
545
+ if len({sq[q_ - 1] for sq in cs}) > 1:
546
+ sites.add((e['contig'], q_)); found += 1
547
+ if found >= MD_PER_CHANGE:
548
+ break
549
+ if found >= MD_PER_CHANGE:
550
+ break
551
+ return ref, same, sorted(sites)
552
+
553
+
554
+ def md_evidence(path, kind, versions, graph, candidates, ev, seqs):
555
+ """Reference bases implied by MD tags, at sites where candidate versions differ and over sampled reads.
556
+
557
+ Used for BAM when names and lengths do not separate the candidates. MD tags
558
+ restate the reference given to the aligner or to samtools calmd, so they form
559
+ one group. Sites are coordinates whose bases differ between candidates
560
+ (``_shared_coordinates``). Every one of
561
+ up to MD_READS sampled reads is also an item, consistent with the candidates
562
+ whose bases equal all of its implied reference bases: MD is exact, so a file
563
+ aligned to a version that is not listed shows reads that fit none.
564
+ """
565
+ try:
566
+ import pysam
567
+ fh = pysam.AlignmentFile(str(path), 'rb', check_sq=False)
568
+ if not fh.has_index():
569
+ fh.close(); return {'status': 'not_evaluated', 'reason': 'alignment_not_indexed'}
570
+ except ImportError:
571
+ return {'status': 'not_evaluated', 'reason': 'pysam_not_installed'}
572
+ except Exception as exc:
573
+ return {'status': 'not_evaluated', 'reason': f'cannot_open: {exc}'}
574
+ cand = sorted(candidates)
575
+ ref, same, sites = _shared_coordinates(graph, cand, seqs)
576
+ if same is None:
577
+ fh.close()
578
+ return {'status': 'not_evaluated', 'reason': 'versions_not_compared_pairwise'}
579
+ if len(sites) > MAX_MD_SITES:
580
+ sites = sorted(random.Random(1).sample(sites, MAX_MD_SITES))
581
+ candset = set(cand)
582
+ checked = no_md = reads = fitting_none = 0
583
+ with fh:
584
+ for contig, pos in sites:
585
+ base = None
586
+ try:
587
+ for r in fh.fetch(contig, pos - 1, pos):
588
+ if r.is_secondary or r.is_supplementary or not r.has_tag('MD'):
589
+ no_md += 1
590
+ continue
591
+ for qpos, rpos, rb in r.get_aligned_pairs(matches_only=True, with_seq=True):
592
+ if rpos == pos - 1:
593
+ base = rb.upper(); break
594
+ if base:
595
+ break
596
+ except (ValueError, KeyError):
597
+ continue
598
+ if not base:
599
+ continue
600
+ ok = {v for v in cand if seqs(v).get(contig, '')[pos - 1:pos] == base}
601
+ if ok != candset:
602
+ ev.add('md_bases', ok)
603
+ else:
604
+ ev.observe('md_bases')
605
+ checked += 1
606
+ try:
607
+ with pysam.AlignmentFile(str(path), 'rb', check_sq=False) as f2:
608
+ # reads sampled at evenly spaced places over every contig, so the whole reference is tested for fit
609
+ spans = [(c, n) for c, n in zip(f2.references, f2.lengths) if n]
610
+ total = sum(n for _, n in spans) or 1
611
+ places = []
612
+ for c, n in spans:
613
+ k = max(1, round(MD_WINDOWS * n / total))
614
+ places += [(c, int(n * (i + 0.5) / k)) for i in range(k)]
615
+ random.Random(1).shuffle(places) # any prefix of the visits is spread over the whole reference
616
+ bases = 0; seen = set()
617
+ for contig, pos in places:
618
+ if reads >= MD_READS or bases >= MD_BASES:
619
+ break
620
+ taken = 0
621
+ for r in f2.fetch(contig, pos, pos + 1):
622
+ if taken >= MD_READS_PER_PLACE:
623
+ break
624
+ if r.is_unmapped or r.is_secondary or r.is_supplementary or not r.has_tag('MD'):
625
+ continue
626
+ key = (r.query_name, r.is_read1, r.reference_start)
627
+ if key in seen:
628
+ continue
629
+ seen.add(key)
630
+ try:
631
+ pairs = [(rp, rb.upper()) for _, rp, rb in r.get_aligned_pairs(matches_only=True, with_seq=True)]
632
+ except (ValueError, KeyError):
633
+ continue
634
+ if not pairs:
635
+ continue
636
+ ok = set()
637
+ for v in cand: # MD restates bases by coordinate number: exact in any version
638
+ sq = seqs(v).get(contig, '')
639
+ if all(rp < len(sq) and sq[rp] == b for rp, b in pairs):
640
+ ok.add(v)
641
+ fitting_none += not ok
642
+ ev.add('md_bases', ok, MD_READ_ERROR)
643
+ reads += 1; taken += 1; bases += len(pairs)
644
+ except (ValueError, OSError):
645
+ pass
646
+ return {'status': 'evaluated' if checked or reads else 'not_evaluated', 'sites_checked': checked,
647
+ 'reads_checked': reads, 'reads_fitting_no_version': fitting_none,
648
+ 'reason': None if checked or reads else ('no_md_tags' if no_md else 'no_reads_at_sites')}
649
+
650
+
651
+ # ---------------------------------------------------------------- variants
652
+
653
+ def vcf_evidence(path, header, versions, ev, seqs, all_ids, *, max_records=2000, graph=None, max_sited=5000):
654
+ """Contig header, ##reference label and REF alleles: every record at a site where versions differ, plus a sample.
655
+
656
+ A record whose REF covers a changed site between two versions tells them apart; elsewhere REF alleles agree
657
+ across versions unless an indel shifted the numbering. The whole file is streamed: records overlapping a
658
+ change of any pair (up to ``max_sited``) are all checked, and a reservoir sample of ``max_records`` of the
659
+ others.
660
+ """
661
+ from .formats import side
662
+ names, lengths = header.get('names', []), header.get('lengths', [])
663
+ out = side_evidence(side(names, {n: l for n, l in zip(names, lengths) if l}), versions, ev, all_ids)
664
+ out['label_versions'] = sorted(_label_evidence(header.get('reference_header') or '', versions, ev, all_ids))
665
+ sited_index = {}
666
+ if graph is not None:
667
+ merged = defaultdict(list)
668
+ for v in versions:
669
+ for c, idx in _events_by_contig(graph, v['id']).items():
670
+ merged[c].extend(idx.starts)
671
+ sited_index = {c: _Spans(sorted(set(x))) for c, x in merged.items()}
672
+ rng = random.Random(1)
673
+ sited, sample, seen = [], [], 0
674
+ with _open(path) as fh:
675
+ for line in fh:
676
+ if line.startswith('#'):
677
+ continue
678
+ f = line.split('\t', 5)
679
+ if len(f) < 4:
680
+ continue
681
+ try:
682
+ rec = (f[0], int(f[1]), f[3].upper())
683
+ except ValueError:
684
+ continue
685
+ idx = sited_index.get(rec[0])
686
+ if idx is not None and len(sited) < max_sited and idx.overlapping(rec[1], rec[1] + max(1, len(rec[2]))):
687
+ sited.append(rec); continue
688
+ seen += 1
689
+ if len(sample) < max_records:
690
+ sample.append(rec)
691
+ else:
692
+ j = rng.randrange(seen)
693
+ if j < max_records:
694
+ sample[j] = rec
695
+ records = sited + sample
696
+ out['records_at_change_sites'] = len(sited)
697
+ checked = 0; consistent = defaultdict(int); none = 0
698
+ for contig, pos, ref in records:
699
+ if not ref or ref == '.' or any(c not in 'ACGTN' for c in ref):
700
+ continue
701
+ ok = set()
702
+ for v in versions:
703
+ s = seqs(v['id']).get(contig)
704
+ if s is not None and _ref_matches(ref, s[pos - 1:pos - 1 + len(ref)]):
705
+ ok.add(v['id'])
706
+ if ok != all_ids:
707
+ ev.add('ref_alleles', ok)
708
+ for v in ok:
709
+ consistent[v] += 1
710
+ none += not ok
711
+ else:
712
+ ev.observe('ref_alleles')
713
+ checked += 1
714
+ out.update(records_checked=checked, consistent=dict(consistent), consistent_with_no_version=none)
715
+ return out
716
+
717
+
718
+ # ---------------------------------------------------------------- annotation
719
+
720
+ def _cds_groups(records):
721
+ """The CDS segments of each coding sequence: those sharing a protein or transcript identifier, else those of
722
+ one parent transcript; a segment's own ID is the key only without a parent, since AUGUSTUS and BRAKER write a
723
+ distinct ID on the CDS of every exon (g1.t1.CDS1, g1.t1.CDS2). A segment with several parents (an exon shared
724
+ by isoforms) belongs to each."""
725
+ groups = defaultdict(list)
726
+ for r in records:
727
+ if r['type'] != 'CDS':
728
+ continue
729
+ a = r['attributes']
730
+ key = a.get('protein_id') or a.get('transcript_id')
731
+ for k in [key] if key else (list(r['parents']) or [a.get('ID') or ('line', r['line'])]):
732
+ groups[k].append(r)
733
+ return groups
734
+
735
+
736
+ def _cds_seq(segments, seq, phase=None):
737
+ strand = segments[0]['strand']
738
+ ordered = sorted(segments, key=lambda r: r['start'], reverse=(strand == '-'))
739
+ parts = []
740
+ for r in ordered:
741
+ if r['end'] > len(seq) or r['start'] < 1:
742
+ return None
743
+ frag = seq[r['start'] - 1:r['end']]
744
+ parts.append(frag if strand == '+' else frag.translate(_TRANS)[::-1])
745
+ nt = ''.join(parts)
746
+ if phase is None:
747
+ phase = int(ordered[0]['phase']) if ordered[0]['phase'] in ('0', '1', '2') else 0
748
+ return nt[phase:]
749
+
750
+
751
+ class _Spans:
752
+ """Sorted (start, end) spans with an overlap query."""
753
+
754
+ def __init__(self, items):
755
+ self.starts = sorted(items)
756
+ self.maxend = []
757
+ m = 0
758
+ for s, e in self.starts:
759
+ m = max(m, e)
760
+ self.maxend.append(m)
761
+
762
+ def overlapping(self, start, end):
763
+ import bisect
764
+ i = bisect.bisect_right(self.starts, (end, float('inf')))
765
+ out = []
766
+ for j in range(i - 1, -1, -1):
767
+ if self.maxend[j] < start:
768
+ break
769
+ if self.starts[j][1] >= start:
770
+ out.append(self.starts[j])
771
+ return out
772
+
773
+
774
+ def _events_by_contig(graph, version_id):
775
+ """Event spans in the coordinates of ``version_id`` from every pair, as an overlap index.
776
+
777
+ Events in a frame of the first version (a turned, merged or split contig)
778
+ are mapped back to its contigs, a span across a join of blocks in pieces.
779
+ """
780
+ from .segments import Frames
781
+ spans = defaultdict(list)
782
+ for p in graph['pairs']:
783
+ if p['a'] == version_id:
784
+ fr = Frames(p.get('frames'))
785
+ for e in p['events']:
786
+ x, y = e['ref_pos'], e['ref_pos'] + max(len(e['ref']), 1)
787
+ if e['contig'] not in fr.by_f:
788
+ spans[e['contig']].append((x, y)); continue
789
+ for c, u, v in fr.pieces(e['contig'], max(1, x), max(x, y - 1)):
790
+ spans[c].append((u, v + 1))
791
+ elif p['b'] == version_id:
792
+ for e in p['events']:
793
+ spans[e.get('contig_b', e['contig'])].append((e['alt_pos'], e['alt_pos'] + max(len(e['alt']), 1)))
794
+ return {c: _Spans(sorted(set(v))) for c, v in spans.items()}
795
+
796
+
797
+ def _overlaps(spans, contig, start, end):
798
+ idx = spans.get(contig)
799
+ return bool(idx and idx.overlapping(start, end))
800
+
801
+
802
+ def _sequence_region(path):
803
+ regions = {}
804
+ try:
805
+ with _open(path) as fh:
806
+ for line in fh:
807
+ if line.startswith('##sequence-region'):
808
+ p = line.split()
809
+ if len(p) >= 4:
810
+ regions[p[1]] = (int(p[2]), int(p[3]))
811
+ elif not line.startswith('#'):
812
+ break
813
+ except (OSError, ValueError):
814
+ pass
815
+ return regions
816
+
817
+
818
+ def transferred_annotation(records) -> bool:
819
+ """True for gene models carried over by Liftoff or LiftOn, and for protein-to-genome alignments (miniprot,
820
+ spaln, exonerate: a ``Target=`` attribute); both keep broken frames by design."""
821
+ for r in records[:20000]:
822
+ src = r.get('source', '') or ''
823
+ if 'liftoff' in src.lower() or 'lifton' in src.lower():
824
+ return True
825
+ if any(k in r['attributes'] for k in LIFT_ATTRIBUTES) or 'Target' in r['attributes']:
826
+ return True
827
+ return False
828
+
829
+
830
+ def gff_evidence(path, versions, graph, ev, seqs, all_ids, *, records=None):
831
+ """Coordinate system, plus reading-frame integrity of CDS at event sites as a weak plausibility group."""
832
+ if not versions:
833
+ return {'coordinate_versions': [], 'reason': 'no_candidate_versions',
834
+ 'cds_frame': 'not_used: no candidate assembly versions'}
835
+ records = parse_gff(path) if records is None else records
836
+ seqids = {r['seqid'] for r in records}
837
+ regions = _sequence_region(path)
838
+ circular = {r['seqid'] for r in records if str(r['attributes'].get('Is_circular', '')).lower() == 'true'}
839
+ # sequence-region lines give whole lengths when every one starts at 1; a file with one that starts elsewhere
840
+ # writes the span of its features there (TriTrypDB), so each is then only a lower bound on the length
841
+ exact = bool(regions) and all(start == 1 for start, _ in regions.values())
842
+ coords = set()
843
+ for v in versions:
844
+ have = dict(zip(v['names'], v['lengths']))
845
+ if not seqids <= set(have):
846
+ continue
847
+ if any((have.get(n) != end) if exact else (have.get(n, 0) < end) for n, (start, end) in regions.items()):
848
+ continue
849
+ if all(r['end'] <= have[r['seqid']] * (2 if r['seqid'] in circular else 1) for r in records):
850
+ coords.add(v['id'])
851
+ if coords != all_ids:
852
+ ev.add('header' if exact else 'coordinates', coords)
853
+ out = {'coordinate_versions': sorted(coords)}
854
+ if transferred_annotation(records):
855
+ out['cds_frame'] = 'not_used: transferred gene models and protein alignments keep broken frames by design'
856
+ return out
857
+ groups = _cds_groups(records)
858
+ spans = {v['id']: _events_by_contig(graph, v['id']) for v in versions}
859
+ code = _genetic_code(groups, seqs(versions[0]['id']))
860
+
861
+ def intact(segs):
862
+ contig = segs[0]['seqid']
863
+ table = segs[0]['attributes'].get('transl_table') or code
864
+ ok = set()
865
+ for v in versions:
866
+ s = seqs(v['id']).get(contig)
867
+ r = False if s is None else _open_frame(segs, s, table)
868
+ if r is None:
869
+ return None # an ambiguous base under a version: no observation
870
+ if r:
871
+ ok.add(v['id'])
872
+ return ok
873
+
874
+ checked = 0; clean = defaultdict(int); elsewhere = []
875
+ for key, segs in groups.items():
876
+ contig = segs[0]['seqid']; strand = segs[0]['strand']
877
+ if strand not in ('+', '-') or len({r['seqid'] for r in segs}) != 1:
878
+ continue
879
+ start, end = min(r['start'] for r in segs), max(r['end'] for r in segs)
880
+ if not any(_overlaps(spans[v['id']], contig, start, end) for v in versions):
881
+ a = segs[0]['attributes']
882
+ if str(a.get('partial', '00')) in ('00', '') and not any(k in a for k in ('pseudo', 'pseudogene')) \
883
+ and start > 3:
884
+ elsewhere.append(segs)
885
+ continue
886
+ if checked >= MAX_PROTEIN_CHECKS:
887
+ continue
888
+ ok = intact(segs)
889
+ if ok is None:
890
+ continue
891
+ if ok and ok != all_ids:
892
+ ev.add('cds_frame', ok)
893
+ for v in ok:
894
+ clean[v] += 1
895
+ checked += 1
896
+ # Complete gene models away from changed sites must stay intact under the version they were predicted on; a
897
+ # sample tests that fit (and shifted numbering after an indel in another version).
898
+ # The fit is judged against every model checked (cds_fit): correct annotations carry a few broken models of
899
+ # their own (FRAME_FIT_ERROR), so only a share of broken models above that says the file fits no version.
900
+ broken = shifted = fit = 0
901
+ step = max(1, len(elsewhere) // MAX_FIT_CHECKS)
902
+ for segs in elsewhere[::step][:MAX_FIT_CHECKS]:
903
+ if any(r['end'] > len(seqs(v['id']).get(r['seqid'], '')) - 3 for v in versions for r in segs):
904
+ continue # at a contig end: often truncated
905
+ ok = intact(segs)
906
+ if ok is None:
907
+ continue
908
+ if not ok:
909
+ ev.add('cds_fit', ok)
910
+ broken += 1
911
+ continue
912
+ ev.observe('cds_fit')
913
+ fit += 1
914
+ if ok != all_ids:
915
+ ev.add('cds_frame', ok)
916
+ shifted += 1
917
+ out.update(cds_at_event_sites_checked=checked, cds_in_frame=dict(clean), genetic_code=int(code),
918
+ elsewhere_checked=broken + fit, elsewhere_broken_under_every_version=broken,
919
+ elsewhere_intact_under_some=shifted)
920
+ return out
921
+
922
+
923
+ GENETIC_CODES = (1, 4, 6)
924
+
925
+
926
+ def _open_frame(segs, seq, table):
927
+ """Whether a CDS reads as one open frame under ``table``: from its phase, or from its first base when the
928
+ phase column holds the frame of the segment on the contig (RAST writes start mod 3). A stop codon split by an
929
+ intron does not break it (AUGUSTUS and BRAKER write such models; a difference between versions that shifts the
930
+ frame puts stops inside exons). None when the model tests nothing about the sequence: an ambiguous base (a
931
+ hard-masked repeat), or coordinates that are no whole number of codons under its phase (models kept with a
932
+ frameshift, as PASA-based and JGI catalogues keep them), which is the same under every version."""
933
+ declared, whole = _cds_seq(segs, seq), _cds_seq(segs, seq, 0)
934
+ if declared is None:
935
+ return False
936
+ if any(c not in 'ACGT' for c in whole):
937
+ return None
938
+ for phase, nt in ((None, declared), (0, whole)):
939
+ if len(nt) % 3:
940
+ continue
941
+ try:
942
+ prot = _translate(nt, table=int(table))
943
+ except (ValueError, KeyError):
944
+ continue
945
+ junctions = _junctions(segs, phase)
946
+ if prot and all(any(3 * i < b < 3 * i + 3 for b in junctions) for i, a in enumerate(prot) if a == '*'):
947
+ return True
948
+ return None if len(declared) % 3 else False
949
+
950
+
951
+ def _junctions(segs, phase):
952
+ """Offsets in the phase-trimmed CDS at which a new segment begins."""
953
+ strand = segs[0]['strand']
954
+ ordered = sorted(segs, key=lambda r: r['start'], reverse=(strand == '-'))
955
+ if phase is None:
956
+ phase = int(ordered[0]['phase']) if ordered[0]['phase'] in ('0', '1', '2') else 0
957
+ out, acc = [], -phase
958
+ for r in ordered[:-1]:
959
+ acc += r['end'] - r['start'] + 1
960
+ out.append(acc)
961
+ return out
962
+
963
+
964
+ def _genetic_code(groups, seqs) -> int:
965
+ """The genetic code the gene models of a file read under: the standard one unless code 4 (mycoplasmas,
966
+ mitochondria) or 6 (ciliates) opens most sampled models and at least twice as many."""
967
+ sample = [g for g in groups.values() if g[0]['strand'] in ('+', '-') and len({r['seqid'] for r in g}) == 1
968
+ and g[0]['seqid'] in seqs and 'transl_table' not in g[0]['attributes']]
969
+ sample = sample[::max(1, len(sample) // FRAME_SAMPLE)][:FRAME_SAMPLE]
970
+ if not sample:
971
+ return 1
972
+ n = {t: sum(bool(_open_frame(g, seqs[g[0]['seqid']], t)) for g in sample) for t in GENETIC_CODES}
973
+ best = max(GENETIC_CODES, key=lambda t: n[t])
974
+ return best if n[best] >= 2 * n[1] and n[best] > len(sample) / 2 else 1
975
+
976
+
977
+ START_CODONS = ('ATG', 'GTG', 'TTG', 'CTG')
978
+
979
+
980
+ def _header_ids(header):
981
+ """Identifiers a sequence header gives: its first word, and an ``ID=`` field when the header carries one
982
+ (Prodigal writes ``>contig_1_1 # 2 # 1234 # 1 # ID=1_1;...``, whose ID is the one in its GFF)."""
983
+ out = [header.split()[0]]
984
+ m = re.search(r'(?:^|[\s;#])ID=([^;\s]+)', header)
985
+ if m and m.group(1) != out[0]:
986
+ out.append(m.group(1))
987
+ return out
988
+
989
+
990
+ PRODIGAL_HEADER = re.compile(r'^(\S+)\s+#\s*(\d+)\s*#\s*(\d+)\s*#\s*(-?1)\s*#')
991
+
992
+
993
+ def header_records(path, *, min_share=0.9):
994
+ """CDS records from Prodigal-style protein or gene headers (``>contig_7 # start # end # strand # ...``).
995
+
996
+ Prodigal and Pyrodigal write the coordinates of each gene in its header, so
997
+ such a file carries its own coordinate system and needs no GFF: linking by
998
+ identifier would be ambiguous, because every run numbers its genes 1_1, 1_2,
999
+ ... alike. None unless at least ``min_share`` of the headers parse.
1000
+ """
1001
+ recs, n = [], 0
1002
+ for i, (name, _) in enumerate(_proteins(path)):
1003
+ n += 1
1004
+ m = PRODIGAL_HEADER.match(name)
1005
+ if not m:
1006
+ continue
1007
+ gid, start, end, strand = m.group(1), int(m.group(2)), int(m.group(3)), m.group(4)
1008
+ if '_' not in gid:
1009
+ continue
1010
+ part = re.search(r'partial=(\d\d)', name)
1011
+ recs.append({'seqid': gid.rsplit('_', 1)[0], 'type': 'CDS', 'start': start, 'end': end,
1012
+ 'strand': '+' if strand == '1' else '-', 'phase': '0',
1013
+ 'attributes': {'ID': gid, **({'partial': part.group(1)} if part else {})},
1014
+ 'parents': [], 'line': i + 1, 'source': 'header'})
1015
+ return recs if n and len(recs) >= min_share * n else None
1016
+
1017
+
1018
+ def _transitions(graph, src, versions):
1019
+ """For each version v, a Lifter that moves src coordinates exactly into v (None for src itself)."""
1020
+ from .lift import transition, Lifter
1021
+ out = {}
1022
+ for v in versions:
1023
+ vid = v['id']
1024
+ if vid == src:
1025
+ out[vid] = None; continue
1026
+ p = next((x for x in graph['pairs'] if {x['a'], x['b']} == {src, vid}), None)
1027
+ if p is None:
1028
+ continue
1029
+ events, names, pre, post = transition(p, src, vid)
1030
+ out[vid] = Lifter(events, names, p['unmatched_a'] if p['a'] == src else p['unmatched_b'],
1031
+ [u for u in p.get('unresolved', []) if p['a'] == src], pre=pre, post=post)
1032
+ return out
1033
+
1034
+
1035
+ def _lift_segments(segs, lifter):
1036
+ """CDS segments moved into another version, as records, or None when one cannot be placed."""
1037
+ if lifter is None:
1038
+ return segs
1039
+ out = []
1040
+ for r in segs:
1041
+ sp = lifter.span(r['seqid'], r['start'], r['end'])
1042
+ if sp is None:
1043
+ return None
1044
+ strand = r['strand'] if not sp['flip'] else {'+': '-', '-': '+'}.get(r['strand'], r['strand'])
1045
+ out.append(dict(r, seqid=sp['contig'], start=sp['start'], end=sp['end'], strand=strand))
1046
+ if len({(r['seqid'], r['strand']) for r in out}) > 1: # segments split by a join or break of contigs
1047
+ return None
1048
+ return out
1049
+
1050
+
1051
+ def protein_evidence(path, gff_path, versions, graph, ev, seqs, all_ids, *, mode='protein', observed=None,
1052
+ records=None, intrinsic=False, numbering_only=False):
1053
+ """Sequences of a protein, CDS or protein-MD5 file against the genes that encode them in every version.
1054
+
1055
+ mode 'protein': a protein FASTA against translations; 'md5': protein MD5s (InterProScan) against
1056
+ MD5s of translations, with and without an initiator methionine for alternative start codons;
1057
+ 'cds': a CDS/transcript FASTA against the spliced CDS sequence.
1058
+
1059
+ The gene models (from the file's own headers, or from the GFF whose models reproduce the sequences)
1060
+ give coordinates in one version, the one under which most of the sequences are reproduced as given
1061
+ (``frame``). Each gene is then moved exactly into every other version through the diff, so a sequence
1062
+ is compared with what each version itself encodes there: the evidence is about content, not about the
1063
+ numbering of the gene models. Genes that a change touches in some version tell versions apart; a sample
1064
+ of the other genes tests the fit (in every version they encode the same sequence, so a sequence that
1065
+ differs from it fits no listed version). When the coordinates are the file's own (Prodigal headers),
1066
+ the share of genes each version reproduces as numbered is also coordinate evidence.
1067
+ """
1068
+ import hashlib
1069
+ if observed is None:
1070
+ observed = {}
1071
+ for name, seq in (_proteins(path) if mode == 'protein' else _contigs(path)):
1072
+ seq = _without_terminal_stop(seq) if mode == 'protein' else seq.upper()
1073
+ for x in _header_ids(name):
1074
+ observed.setdefault(x, seq)
1075
+ groups = _cds_groups(parse_gff(gff_path) if records is None else records)
1076
+
1077
+ def encoded(v, segs, target):
1078
+ s = seqs(v).get(segs[0]['seqid'])
1079
+ if s is None:
1080
+ return False
1081
+ nt = _cds_seq(segs, s)
1082
+ if nt is None:
1083
+ return False
1084
+ if mode == 'cds': # with or without the stop codon on either side
1085
+ return nt == target or (len(target) == len(nt) + 3 and target.startswith(nt)) \
1086
+ or (len(nt) == len(target) + 3 and nt.startswith(target))
1087
+ if any(c not in 'ACGT' for c in nt):
1088
+ return None # an ambiguous base: the gene is no observation
1089
+ # a model whose length is not a multiple of three (a frameshift carried onto a draft by Liftoff) is
1090
+ # translated to its last complete codon, as gffread and Prodigal write such proteins
1091
+ nt = nt[:len(nt) - len(nt) % 3]
1092
+ if not nt:
1093
+ return False
1094
+ try:
1095
+ prot = _translate(nt)
1096
+ except ValueError:
1097
+ return False
1098
+ if mode == 'md5':
1099
+ prot = _without_terminal_stop(prot)
1100
+ variants = {prot} | ({'M' + prot[1:]} if nt[:3] in START_CODONS and prot else set())
1101
+ return any(hashlib.md5(x.encode()).hexdigest() == target for x in variants)
1102
+ return _same_protein(prot, target, nt)
1103
+
1104
+ linked_genes = []
1105
+ for key, segs in groups.items():
1106
+ pid = segs[0]['attributes'].get('protein_id') or segs[0]['attributes'].get('ID')
1107
+ target = next((observed[x] for x in [pid] + list(segs[0]['parents']) if x in observed), None)
1108
+ if target is not None and segs[0]['strand'] in ('+', '-') and len({r['seqid'] for r in segs}) == 1:
1109
+ linked_genes.append((segs, target))
1110
+ out = {'proteins_linked': len(linked_genes), 'proteins_at_event_sites_checked': 0, 'exact_matches': {},
1111
+ 'fit_some_version': 0}
1112
+ if not linked_genes:
1113
+ return out
1114
+ # 1. the version in whose numbering the gene models are written
1115
+ step = max(1, len(linked_genes) // FRAME_SAMPLE)
1116
+ sample = linked_genes[::step][:FRAME_SAMPLE]
1117
+ as_given = {v['id']: [bool(encoded(v['id'], segs, t)) for segs, t in sample] for v in versions}
1118
+ share = {v: sum(x) / len(sample) for v, x in as_given.items()}
1119
+ # versions that differ at a few places tie on the sample; the genes at those places decide, so a tie is broken on
1120
+ # every gene (a file read in the numbering of another version would have its genes there fit no version)
1121
+ top = max(share.values())
1122
+ tied = [v['id'] for v in versions if share[v['id']] == top]
1123
+ if len(tied) > 1:
1124
+ every = linked_genes[::max(1, len(linked_genes) // MAX_FIT_CHECKS)][:MAX_FIT_CHECKS]
1125
+ full = {v: sum(bool(encoded(v, segs, t)) for segs, t in every) for v in tied}
1126
+ frame = max(tied, key=lambda v: (full[v], -tied.index(v)))
1127
+ else:
1128
+ frame = tied[0]
1129
+ out['numbering_fit'] = {v: round(x, 4) for v, x in share.items()}
1130
+ out['frame'] = frame
1131
+ if numbering_only:
1132
+ return out
1133
+ if intrinsic:
1134
+ for i in range(len(sample)):
1135
+ ok = {v for v in as_given if as_given[v][i]}
1136
+ if ok != all_ids and ok:
1137
+ ev.add('coordinates', ok)
1138
+ # 2. content: each gene moved into every version
1139
+ spans = _events_by_contig(graph, frame)
1140
+ lifters = _transitions(graph, frame, versions)
1141
+ checked = agree = 0; matched = defaultdict(int); elsewhere = []
1142
+ for segs, target in linked_genes:
1143
+ contig = segs[0]['seqid']
1144
+ start, end = min(r['start'] for r in segs), max(r['end'] for r in segs)
1145
+ if not _overlaps(spans, contig, start, end):
1146
+ elsewhere.append((segs, target)); continue
1147
+ if checked >= MAX_PROTEIN_CHECKS:
1148
+ continue
1149
+ ok = set(); unknown = False
1150
+ for v in versions:
1151
+ if v['id'] not in lifters:
1152
+ continue
1153
+ moved = _lift_segments(segs, lifters[v['id']])
1154
+ r = encoded(v['id'], moved, target) if moved is not None else False
1155
+ if r is None:
1156
+ unknown = True
1157
+ break
1158
+ if r:
1159
+ ok.add(v['id'])
1160
+ if unknown:
1161
+ continue
1162
+ if ok != all_ids:
1163
+ ev.add('proteins', ok)
1164
+ for v in ok:
1165
+ matched[v] += 1
1166
+ else:
1167
+ ev.observe('proteins')
1168
+ checked += 1
1169
+ agree += bool(ok)
1170
+ # 3. fit away from changed sites: every version encodes the same sequence there
1171
+ fit_none = 0
1172
+ # a gene cut by a contig end is predicted from a truncated sequence (no start or no stop): not a fit test
1173
+ elsewhere = [(segs, t) for segs, t in elsewhere if str(segs[0]['attributes'].get('partial', '00')) in ('00', '')]
1174
+ step = max(1, len(elsewhere) // MAX_FIT_CHECKS)
1175
+ tested = elsewhere[::step][:MAX_FIT_CHECKS]
1176
+ evaluated = 0
1177
+ for segs, target in tested:
1178
+ r = encoded(frame, segs, target)
1179
+ if r is None:
1180
+ continue
1181
+ evaluated += 1
1182
+ if not r:
1183
+ ev.add('proteins', set())
1184
+ fit_none += 1
1185
+ else:
1186
+ ev.observe('proteins')
1187
+ out.update(proteins_at_event_sites_checked=checked, exact_matches=dict(matched), fit_some_version=agree,
1188
+ elsewhere_checked=evaluated, elsewhere_fit_no_version=fit_none)
1189
+ return out
1190
+
1191
+
1192
+ def _same_protein(prot, target, nt):
1193
+ """A translation under code 11 against the sequence in the file: an initiator codon reads as M, and a TGA read
1194
+ as W (codes 4 and 25) or U (selenocysteine) is accepted."""
1195
+ if prot and target.startswith('M') and nt[:3] in START_CODONS:
1196
+ prot = 'M' + prot[1:]
1197
+ if prot == target:
1198
+ return True
1199
+ if len(prot) != len(target):
1200
+ return False
1201
+ for i, (x, y) in enumerate(zip(prot, target)):
1202
+ if x != y and not (x == '*' and y in 'WU' and nt[3 * i:3 * i + 3] == 'TGA'):
1203
+ return False
1204
+ return True
1205
+
1206
+
1207
+ def _n50(lengths):
1208
+ ls = sorted(lengths, reverse=True); total = sum(ls); c = 0
1209
+ for x in ls:
1210
+ c += x
1211
+ if c * 2 >= total:
1212
+ return x
1213
+ return None
1214
+
1215
+
1216
+ def metric_evidence(desc, versions, ev, all_ids):
1217
+ """Statistics of one report form one group: they derive from the same contigs."""
1218
+ out = {}
1219
+ for field, key in (('contigs', 'n_sequences'), ('total_bp', 'total_length')):
1220
+ if desc.get(field) is not None:
1221
+ ok = {v['id'] for v in versions if v[key] == desc[field]}
1222
+ if ok != all_ids:
1223
+ ev.add('metrics', ok)
1224
+ out[field] = sorted(ok)
1225
+ if desc.get('n50') is not None:
1226
+ ok = {v['id'] for v in versions if _n50(v['lengths']) == desc['n50']}
1227
+ if ok != all_ids:
1228
+ ev.add('metrics', ok)
1229
+ out['n50'] = sorted(ok)
1230
+ return out
1231
+
1232
+
1233
+ # ---------------------------------------------------------------- driver
1234
+
1235
+ def attribute_all(scan_result, graph, *, log=None) -> list:
1236
+ versions = graph['full_versions']
1237
+ all_ids = {v['id'] for v in versions}
1238
+ seqs = _version_seqs(versions)
1239
+ gffs = [a for a in scan_result['artefacts'] if a['kind'] == 'gff']
1240
+ parsed = {}
1241
+
1242
+ def gff_records(path):
1243
+ if path not in parsed:
1244
+ try:
1245
+ parsed[path] = parse_gff(path)
1246
+ except (ValueError, OSError, UnicodeError) as exc:
1247
+ parsed[path] = exc
1248
+ return parsed[path]
1249
+
1250
+ def linked_gff(path, mode, observed=None):
1251
+ """Gene models for these sequences: of the GFFs whose identifiers link them, the one whose CDS reproduce
1252
+ most of them as numbered under some version (at least LINK_MIN_FIT). Gene identifiers repeat across
1253
+ runs of one predictor (Prodigal numbers 1_1, 1_2, ... in every run), so the identifiers alone do not
1254
+ tell which run made the file; and the GFF only supplies gene structure, since every gene is then
1255
+ moved into each version before the comparison."""
1256
+ best = None
1257
+ for g in gffs:
1258
+ recs = gff_records(g['path'])
1259
+ if isinstance(recs, Exception):
1260
+ continue
1261
+ try:
1262
+ r = protein_evidence(path, g['path'], versions, graph, Evidence(versions), seqs, all_ids,
1263
+ mode=mode, observed=observed, records=recs, numbering_only=True)
1264
+ except (ValueError, OSError):
1265
+ continue
1266
+ if not r['proteins_linked']:
1267
+ continue
1268
+ fit = max(r.get('numbering_fit', {}).values() or [0.0])
1269
+ key = (fit, r['proteins_linked'])
1270
+ if best is None or key > best[2]:
1271
+ best = (g, r, key)
1272
+ if best is None:
1273
+ return None
1274
+ if best[2][0] < LINK_MIN_FIT:
1275
+ return 'no_fit'
1276
+ return best
1277
+
1278
+ def link(detail_key, path, mode, ev, detail, observed=None):
1279
+ if mode in ('protein', 'cds') and observed is None:
1280
+ recs = header_records(path)
1281
+ if recs:
1282
+ detail[detail_key] = protein_evidence(path, None, versions, graph, ev, seqs, all_ids, mode=mode,
1283
+ records=recs, intrinsic=True)
1284
+ detail[detail_key]['coordinates'] = 'from_headers'
1285
+ return
1286
+ best = linked_gff(path, mode, observed)
1287
+ if best == 'no_fit':
1288
+ detail[detail_key] = {'reason': 'no_gff_reproduces_these_sequences'}
1289
+ elif best:
1290
+ detail[detail_key] = protein_evidence(path, best[0]['path'], versions, graph, ev, seqs, all_ids,
1291
+ mode=mode, observed=observed, records=gff_records(best[0]['path']))
1292
+ detail[detail_key]['gff'] = best[0]['relpath']
1293
+ else:
1294
+ detail[detail_key] = {'reason': 'no_gff_links_these_sequences'}
1295
+
1296
+ out = []
1297
+ for a in scan_result['artefacts']:
1298
+ kind = a['kind']
1299
+ path = Path(a['path'])
1300
+ if kind == 'other' and path.name.lower().endswith(TABLE_SUFFIXES) and (a.get('size') or 0) < (200 << 20):
1301
+ try:
1302
+ s = table_side(path, versions)
1303
+ except (OSError, ValueError, UnicodeError):
1304
+ s = None
1305
+ if s:
1306
+ a['kind'] = kind = 'contig_table'; a['stage'] = 'contig_tables'; a['sides'] = [s]
1307
+ if kind in ('assembly', 'other', 'checksums', 'hts_index', 'other_index', 'msa') or a.get('stage') in (
1308
+ 'workflow', 'environment', 'metadata', 'run_metadata', 'read_qc'):
1309
+ continue
1310
+ if not versions:
1311
+ summary = Evidence(versions).summary()
1312
+ if kind in NOT_VERSION_BOUND:
1313
+ summary['status'] = 'not_version_bound'
1314
+ summary.pop('reason')
1315
+ detail = {'note': 'raw reads are not derived from an assembly version'}
1316
+ else:
1317
+ detail = {'reason': 'no_candidate_versions'}
1318
+ rec = {'relpath': a['relpath'], 'kind': kind, 'attribution': summary,
1319
+ 'detail': detail}
1320
+ out.append(rec)
1321
+ if log:
1322
+ log(rec)
1323
+ continue
1324
+ sides = a.get('sides') or []
1325
+ if kind == 'paf' and len(sides) > 1: # a read-to-assembly PAF: the query side is reads, not a version
1326
+ names = {n for v in versions for n in v['names']}
1327
+ sides = [s for s in sides if s.get('side') != 'query' or set(s.get('names', [])) & names]
1328
+ if len(sides) > 1: # files joining two versions or several assemblies: every side
1329
+ for s in sides:
1330
+ ev = Evidence(versions)
1331
+ detail = side_evidence(s, versions, ev, all_ids)
1332
+ if s.get('metrics'):
1333
+ detail['metrics'] = metric_evidence(s['metrics'], versions, ev, all_ids)
1334
+ if s.get('report_label'):
1335
+ detail['label_versions'] = sorted(_label_evidence(s['report_label'], versions, ev, all_ids, stems=True))
1336
+ rec = {'relpath': f'{a["relpath"]}#{s["side"]}', 'kind': f'{kind}:{s["side"]}',
1337
+ 'attribution': ev.summary(), 'detail': detail, 'file': a['relpath']}
1338
+ out.append(rec)
1339
+ if log:
1340
+ log(rec)
1341
+ continue
1342
+ ev = Evidence(versions)
1343
+ detail = {}
1344
+ try:
1345
+ if sides:
1346
+ detail.update(side_evidence(sides[0], versions, ev, all_ids))
1347
+ label = (sides[0].get('report_label') if sides else None) or a.get('report_label')
1348
+ if label:
1349
+ detail['label_versions'] = sorted(_label_evidence(label, versions, ev, all_ids, stems=True))
1350
+ if a.get('metrics') and kind in ('repeatmasker_tbl', 'quast', 'busco', 'merqury'):
1351
+ detail['metrics'] = metric_evidence(a['metrics'], versions, ev, all_ids)
1352
+ if kind == 'merqury' and a.get('kmer_totals'):
1353
+ detail['kmer_totals'] = kmer_total_evidence(a['kmer_totals'], versions, ev, all_ids)
1354
+ if kind == 'interproscan':
1355
+ link('interproscan', path, 'md5', ev, detail, observed=a.get('proteins', {}).get('md5', {}))
1356
+ elif kind == 'cds_fasta':
1357
+ link('cds', path, 'cds', ev, detail)
1358
+ elif kind == 'protein':
1359
+ link('protein', path, 'protein', ev, detail)
1360
+ elif kind == 'assembly_subset':
1361
+ have = {v['id']: set(v['sequence_digests']) for v in versions}
1362
+ own = a.get('sequence_digests') or []
1363
+ for d in own:
1364
+ ev.add('sequences', {v for v, ds in have.items() if d in ds})
1365
+ detail['sequences'] = {'n': len(own), 'contained_in': sorted(v for v, ds in have.items() if set(own) <= ds)}
1366
+ elif kind in NOT_VERSION_BOUND:
1367
+ detail['note'] = 'raw reads are not derived from an assembly version'
1368
+ elif kind in ('bam', 'cram', 'sam'):
1369
+ detail.update(alignment_evidence(path, kind, a.get('header', {}), versions, graph, ev, seqs, all_ids))
1370
+ elif kind == 'vcf':
1371
+ detail['vcf'] = vcf_evidence(path, a.get('header', {}), versions, ev, seqs, all_ids, graph=graph)
1372
+ elif kind == 'gff':
1373
+ recs = gff_records(a['path'])
1374
+ if isinstance(recs, Exception):
1375
+ raise recs
1376
+ detail['gff'] = gff_evidence(path, versions, graph, ev, seqs, all_ids, records=recs)
1377
+ elif kind in ('busco', 'quast') and not a.get('metrics'):
1378
+ detail['metrics'] = metric_evidence(a, versions, ev, all_ids)
1379
+ except (ValueError, OSError, EOFError, UnicodeError, KeyError) as exc:
1380
+ detail['error'] = f'{type(exc).__name__}: {exc}'
1381
+ summary = ev.summary()
1382
+ if kind in NOT_VERSION_BOUND:
1383
+ summary['status'] = 'not_version_bound'
1384
+ rec = {'relpath': a['relpath'], 'kind': kind, 'attribution': summary, 'detail': detail}
1385
+ out.append(rec)
1386
+ if log:
1387
+ log(rec)
1388
+ return out