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,612 @@
1
+ """Declared provenance versus observed content, and joint attribution along derivation links.
2
+
3
+ Workflow records state how files were made: shell scripts and job logs,
4
+ tool command lines kept in file headers (SAM/BAM @PG, VCF ##...Command,
5
+ fastp JSON), Snakemake's per-output metadata, tool parameter files. Each
6
+ command is parsed into the project files it reads and writes. Three things
7
+ follow from a command whose inputs include exactly one assembly version v:
8
+
9
+ claim every output was made from v;
10
+ lineage an output FASTA that is itself a version descends from v;
11
+ link every output shares the version of each version-bound input
12
+ (variants from an alignment, proteins from an annotation).
13
+
14
+ Claims are compared with the content-based attribution: confirmed,
15
+ contradicted (the content decisively points to another version) or
16
+ unverifiable (the content carries no evidence). Links tie artefacts into
17
+ derivation chains. A chain is scored jointly: the log-likelihoods of its
18
+ members add, a member without evidence inherits the chain's version, and a
19
+ member whose own evidence decisively contradicts the rest of its chain is
20
+ reported as the place where the chain breaks (a file regenerated against
21
+ another version without its dependants, or the reverse).
22
+
23
+ Read files are linked to alignments by read-name sketches: both sides keep
24
+ the names whose hash falls in the same 1/1000 of the hash space, so the
25
+ fraction of an alignment's sketched names present in a read file's sketch
26
+ estimates the fraction of its reads that came from that file.
27
+ """
28
+ from __future__ import annotations
29
+
30
+ import math
31
+ import re
32
+ import shlex
33
+ from collections import defaultdict
34
+ from pathlib import PurePosixPath
35
+
36
+ OUTPUT_FLAGS = {'-o', '--out', '--output', '-O', '--outdir', '--out-dir', '--output-dir', '--output_dir',
37
+ '--prefix', '-out', '--outfile', '--output-file', '-y', '-x', '-w', '--out-prefix',
38
+ '--outFileNamePrefix'}
39
+ COPY_TOOLS = {'cp', 'mv', 'ln', 'rsync', 'install'}
40
+ LIFT_TOOLS = {'liftoff', 'lifton', 'crossmap', 'crossmap.py', 'liftover', 'transanno', 'leviosam', 'leviosam2',
41
+ 'chain_lift', 'halliftover'}
42
+ SPLIT_RE = re.compile(r'\s*(?:;|&&|\|\|)\s*')
43
+
44
+
45
+ def _tokens(command):
46
+ try:
47
+ return shlex.split(command, comments=False, posix=True)
48
+ except ValueError:
49
+ return command.split()
50
+
51
+
52
+ class Resolver:
53
+ """Maps tokens of a command to project files and directories."""
54
+
55
+ def __init__(self, relpaths, root_name):
56
+ self.files = set(relpaths)
57
+ self.dirs = set()
58
+ for r in relpaths:
59
+ parts = r.split('/')
60
+ for i in range(1, len(parts)):
61
+ self.dirs.add('/'.join(parts[:i]))
62
+ self.root = root_name
63
+
64
+ def resolve(self, token):
65
+ token = token.strip('\'"').rstrip(';,)')
66
+ if '=' in token and token.startswith('-'):
67
+ token = token.split('=', 1)[1]
68
+ token = token.lstrip('<>').replace('\\', '/')
69
+ if not token or token.startswith('-') or '://' in token:
70
+ return None, None
71
+ parts = [p for p in PurePosixPath(token).parts if p not in ('/', '.')]
72
+ if not parts:
73
+ return None, None
74
+ for k in range(len(parts), 0, -1):
75
+ if k == 1 and len(parts) > 1:
76
+ break # a bare file name only matches tokens without directories
77
+ cand = '/'.join(parts[-k:])
78
+ if cand in self.files:
79
+ return 'file', cand
80
+ if cand in self.dirs:
81
+ return 'dir', cand
82
+ if len(parts) >= 2 and re.search(r'\.(f(ast)?[aq]|fna|gff3?|gtf|bam|cram|sam|vcf|bcf|bed|paf|agp|gfa|faa)(\.gz)?$',
83
+ parts[-1], re.I):
84
+ return 'external', token
85
+ return None, None
86
+
87
+
88
+ def _strip_comment(line):
89
+ """The command without a trailing shell comment (a # at a word start, outside quotes)."""
90
+ q = None
91
+ for i, ch in enumerate(line):
92
+ if q:
93
+ q = None if ch == q else q
94
+ elif ch in '\'"':
95
+ q = ch
96
+ elif ch == '#' and (i == 0 or line[i - 1].isspace()):
97
+ return line[:i]
98
+ return line
99
+
100
+
101
+ def _is_lift(prog, toks):
102
+ low = [t.lower() for t in toks]
103
+ if prog.lower() in LIFT_TOOLS:
104
+ return True
105
+ if prog in ('picard', 'gatk') and any('liftovervcf' in t for t in low):
106
+ return True
107
+ if prog == 'bcftools' and '+liftover' in low:
108
+ return True
109
+ return prog == 'assemblytrace' and len(toks) > 1 and toks[1] == 'lift'
110
+
111
+
112
+ LIFT_TARGET_FLAGS = {'--to', '-R', '--reference', '-f', '--fasta-ref'}
113
+
114
+
115
+ def parse_command(command, resolver):
116
+ """Inputs, outputs, the copy flag and the liftover target of one logical command (pipes joined).
117
+
118
+ Liftover tools (Liftoff, LiftOn, CrossMap, UCSC liftOver, Picard or GATK
119
+ LiftoverVcf, bcftools +liftover, assemblytrace lift, ...) move coordinates from
120
+ one version to another: their outputs belong to the target, which is the
121
+ first positional assembly for Liftoff and LiftOn (``liftoff target reference``)
122
+ and the --to, -R / R= or -f argument otherwise.
123
+ """
124
+ inputs, outputs, external = [], [], []
125
+ ext_in, ext_out = [], [] # paths outside the project, to follow files made on the way
126
+ copy = lift = False
127
+ target = None
128
+ for segment in SPLIT_RE.split(_strip_comment(command)):
129
+ toks = _tokens(segment)
130
+ while toks and (toks[0] in ('+', '++', 'time', 'srun', 'command', 'exec', 'env')
131
+ or re.match(r'^[A-Za-z_][A-Za-z0-9_]*=', toks[0])):
132
+ toks = toks[1:] # set -x prefix, launchers and VAR=value prefixes
133
+ if not toks:
134
+ continue
135
+ prog = PurePosixPath(toks[0]).name
136
+ seg_lift = _is_lift(prog, toks)
137
+ lift = lift or seg_lift
138
+ positional = []
139
+ nxt_out = skip = nxt_target = False
140
+ for i, t in enumerate(toks[1:], 1):
141
+ if skip:
142
+ skip = False; continue
143
+ if t in ('2>', '2>>', '&>', '&>>'):
144
+ skip = True; continue # stderr redirection: the next token is a log, not an input
145
+ if t in ('>', '>>', '1>'):
146
+ nxt_out = True; continue
147
+ if t.startswith(('2>', '&>')) or t == '2>&1':
148
+ continue
149
+ if seg_lift and (t in LIFT_TARGET_FLAGS or t.startswith(('R=', 'REFERENCE_SEQUENCE='))):
150
+ if '=' in t:
151
+ kind, ref = resolver.resolve(t.split('=', 1)[1])
152
+ if kind == 'file':
153
+ target = ref
154
+ else:
155
+ nxt_target = True
156
+ continue
157
+ if t in OUTPUT_FLAGS or (prog in ('bowtie2', 'hisat2') and t == '-S'):
158
+ nxt_out = True; continue
159
+ is_out = nxt_out or t.startswith(('>', '1>')) or any(t.startswith(f + '=') for f in OUTPUT_FLAGS if f.startswith('--'))
160
+ nxt_out = False
161
+ kind, ref = resolver.resolve(t)
162
+ if nxt_target:
163
+ nxt_target = False
164
+ if kind == 'file':
165
+ target = ref
166
+ if kind in (None, 'external'):
167
+ tok = t.strip('\'"').lstrip('<>').rstrip(';,)')
168
+ if '=' in tok and tok.startswith('-'):
169
+ tok = tok.split('=', 1)[1]
170
+ if ('/' in tok or re.search(r'\.(f(ast)?[aq]|fna|sam|bam|paf|gfa)(\.gz)?$', tok)) and \
171
+ not tok.startswith(('-', '$')) and '://' not in tok:
172
+ (ext_out if is_out else ext_in).append(tok.rstrip('/'))
173
+ if kind == 'external':
174
+ external.append(ref)
175
+ continue
176
+ if is_out:
177
+ outputs.append((kind, ref))
178
+ else:
179
+ positional.append((kind, ref))
180
+ if seg_lift and target is None and prog.lower() in ('liftoff', 'lifton'):
181
+ fa = [r for k_, r in positional if k_ == 'file' and re.search(r'\.(fa|fasta|fna|fas)(\.gz)?$', r, re.I)]
182
+ if fa:
183
+ target = fa[0]
184
+ if prog in COPY_TOOLS and positional:
185
+ copy = True
186
+ if len(positional) >= 2:
187
+ inputs.extend(positional[:-1])
188
+ outputs.append(positional[-1]) # with one project path the source lies outside the project
189
+ else:
190
+ inputs.extend(positional)
191
+ return {'inputs': list(dict.fromkeys(inputs)), 'outputs': list(dict.fromkeys(outputs)),
192
+ 'external': list(dict.fromkeys(external)), 'copy': copy, 'lift': lift, 'lift_target': target,
193
+ 'ext_inputs': list(dict.fromkeys(ext_in)), 'ext_outputs': list(dict.fromkeys(ext_out))}
194
+
195
+
196
+ def _nextflow_maps(artefacts):
197
+ """Project files by resolved path and by (size, SHA-256), and every Nextflow task output mapped to the
198
+ project file that publishes it (a link to it, or a copy with the same content)."""
199
+ import os
200
+ by_real, by_digest = {}, {}
201
+ for a in artefacts:
202
+ by_real.setdefault(a.get('link_target') or os.path.realpath(a['path']), a['relpath'])
203
+ if a.get('sha256') and a.get('size') is not None:
204
+ by_digest.setdefault((a['size'], a['sha256']), a['relpath'])
205
+ published = {}
206
+ for a in artefacts:
207
+ if a['kind'] == 'nextflow_task' and a.get('record'):
208
+ for path, (size, sha) in a['record'].get('outputs', {}).items():
209
+ rel = by_real.get(path) or (by_digest.get((size, sha)) if sha else None)
210
+ if rel:
211
+ published[path] = rel
212
+ return by_real, published
213
+
214
+
215
+ def _nextflow_statement(a, by_real, published):
216
+ r = a['record']
217
+ if r.get('exitcode') not in (None, '0'):
218
+ return None
219
+ inputs, external, staged = [], [], {}
220
+ for name, path in r.get('inputs_abs', []):
221
+ rel = by_real.get(path) or published.get(path)
222
+ if rel:
223
+ inputs.append(('file', rel)); staged[name] = rel
224
+ elif re.search(r'\.(f(ast)?[aq]|fna|gff3?|gtf|bam|cram|sam|vcf|bcf|bed|paf|agp|gfa|faa)(\.gz)?$', path, re.I):
225
+ external.append(path)
226
+ outputs = [('file', published[p]) for p in r.get('outputs', {}) if p in published]
227
+ lift, target = False, None
228
+ local = Resolver(list(staged), '') # the command names its inputs by their staged names
229
+ for line in (r.get('shellcmd') or '').splitlines():
230
+ line = _strip_comment(line).strip()
231
+ if line and not line.startswith('#'):
232
+ pc = parse_command(line, local)
233
+ if pc.get('lift'):
234
+ lift, target = True, staged.get(pc.get('lift_target'))
235
+ cmd = ' '.join(x.strip() for x in (r.get('shellcmd') or '').splitlines() if x.strip() and not x.lstrip().startswith('#'))
236
+ return {'source': a['relpath'], 'line': 0, 'command': (cmd or f'process {r.get("rule")}')[:500],
237
+ 'inputs': inputs, 'outputs': outputs, 'external': external, 'copy': False, 'origin': 'nextflow',
238
+ 'lift': lift, 'lift_target': target}
239
+
240
+
241
+ def collect_statements(artefacts, resolver):
242
+ """Commands from workflow files, headers, Snakemake records and Nextflow task directories, with their resolved files."""
243
+ out = []
244
+ nf = None
245
+ for a in artefacts:
246
+ src = a['relpath']
247
+ if a['kind'] == 'nextflow_task' and a.get('record'):
248
+ if nf is None:
249
+ nf = _nextflow_maps(artefacts)
250
+ st = _nextflow_statement(a, *nf)
251
+ if st and (st['inputs'] or st['outputs']):
252
+ out.append(st)
253
+ continue
254
+ if a['kind'] == 'snakemake_record' and a.get('record'):
255
+ r = a['record']
256
+ outs = [resolver.resolve(r['output'])] if r.get('output') else []
257
+ ins = [resolver.resolve(x) for x in r.get('input', [])]
258
+ sh = parse_command(r['shellcmd'], resolver) if r.get('shellcmd') else {}
259
+ st = {'source': src, 'line': 0, 'command': r.get('shellcmd') or f'rule {r.get("rule")}',
260
+ 'inputs': [x for x in ins if x[0] in ('file', 'dir')], 'outputs': [x for x in outs if x[0] in ('file', 'dir')],
261
+ 'external': [x[1] for x in ins if x[0] == 'external'], 'copy': False, 'origin': 'snakemake',
262
+ 'lift': sh.get('lift', False), 'lift_target': sh.get('lift_target')}
263
+ out.append(st); continue
264
+ claims = list(a.get('claims') or [])
265
+ if a['kind'] == 'workflow_script' and claims and all(isinstance(c, dict) for c in claims):
266
+ from .shellexp import expand_script
267
+ claims = expand_script([(c.get('line', 0), c['command']) for c in claims], resolver.files)
268
+ header_claims = []
269
+ if a['kind'] in ('bam', 'cram', 'sam', 'ubam'):
270
+ header_claims = list(a.get('header', {}).get('programs', []))
271
+ if a['kind'] in ('vcf',):
272
+ header_claims = list(a.get('header', {}).get('claims', []))
273
+ if a['kind'] in ('bcf', 'fastp', 'delta'):
274
+ header_claims, claims = [c if isinstance(c, str) else c['command'] for c in claims], []
275
+ for c in claims:
276
+ cmd = c['command'] if isinstance(c, dict) else c
277
+ st = parse_command(cmd, resolver)
278
+ if st['inputs'] or st['outputs'] or st['external'] or st['ext_inputs'] or st['ext_outputs']:
279
+ st.update(source=src, line=c.get('line', 0) if isinstance(c, dict) else 0, command=cmd[:500], origin='workflow')
280
+ out.append(st)
281
+ for cmd in header_claims: # the file itself is the output of its recorded command
282
+ st = parse_command(cmd, resolver)
283
+ st['outputs'] = [('file', src)]
284
+ if st['inputs'] or st['external']:
285
+ st.update(source=src, line=0, command=cmd[:500], origin='header')
286
+ out.append(st)
287
+ return out
288
+
289
+
290
+ def _expand(item, files_by_dir):
291
+ kind, ref = item
292
+ if kind == 'file':
293
+ return [ref]
294
+ return files_by_dir.get(ref, [])
295
+
296
+
297
+ def derive(statements, artefacts, version_of_file, same_content):
298
+ """Claims (artefact -> declared versions), lineage edges, links and copy checks."""
299
+ files_by_dir = defaultdict(list)
300
+ for a in artefacts:
301
+ parts = a['relpath'].split('/')
302
+ for i in range(1, len(parts)):
303
+ files_by_dir['/'.join(parts[:i])].append(a['relpath'])
304
+ kind_of = {a['relpath']: a['kind'] for a in artefacts}
305
+ claims, lineage, links, copies = defaultdict(list), [], [], []
306
+ from .formats import VERSION_BOUND
307
+ writes = defaultdict(list)
308
+ for st in statements:
309
+ for o in st['outputs']:
310
+ for f in _expand(o, files_by_dir):
311
+ writes[f].append((st['source'], st['line']))
312
+ behind = {} # path outside the project -> versions it was made from (empty: made from none)
313
+
314
+ def behind_of(x):
315
+ if re.search(r'\.(f(ast)?q|fq)(\.gz)?$', x, re.I):
316
+ return frozenset() # sequencing reads: made from no assembly version
317
+ hit = None
318
+ for d, vs in behind.items():
319
+ if x == d or x.startswith(d + '/'):
320
+ if hit is None or len(d) > len(hit[0]):
321
+ hit = (d, vs)
322
+ return None if hit is None else hit[1]
323
+
324
+ for st in statements:
325
+ ins = [f for i in st['inputs'] for f in _expand(i, files_by_dir)]
326
+ outs = [f for o in st['outputs'] for f in _expand(o, files_by_dir)]
327
+ in_versions = {version_of_file[f] for f in ins if f in version_of_file}
328
+ where = f'{st["source"]}:{st["line"]}' if st['line'] else st['source']
329
+ via = [behind_of(x) for x in st.get('ext_inputs', ())]
330
+ known = [v for v in via if v is not None]
331
+ via_versions = set().union(*known) if known else set()
332
+ if st.get('ext_outputs') and not st.get('lift'):
333
+ made_from = in_versions | via_versions
334
+ # recorded as made from no version only when every path it read is accounted for
335
+ for x in st['ext_outputs']:
336
+ if made_from or (known and len(known) == len(via)) or not via:
337
+ behind[x] = frozenset(made_from)
338
+ if not in_versions and via and len(known) == len(via) and not st.get('lift'):
339
+ for o in outs:
340
+ if o in version_of_file:
341
+ if len(via_versions) == 1:
342
+ v = next(iter(via_versions))
343
+ if not same_content(version_of_file[o], v):
344
+ lineage.append({'parent': v, 'child': version_of_file[o], 'where': where,
345
+ 'command': st['command'], 'through': st['ext_inputs'][:3]})
346
+ elif not via_versions:
347
+ lineage.append({'parent': None, 'child': version_of_file[o], 'where': where,
348
+ 'command': st['command'], 'through': st['ext_inputs'][:3]})
349
+ if st['copy']:
350
+ for o in outs:
351
+ if any(src_ == st['source'] and ln > st['line'] for src_, ln in writes.get(o, [])):
352
+ continue # overwritten later in the same record: not checkable as a copy
353
+ for i in ins:
354
+ if i != o:
355
+ copies.append({'source': i, 'copy': o, 'where': where})
356
+ if st.get('lift'):
357
+ tv = version_of_file.get(st.get('lift_target'))
358
+ for o in outs:
359
+ if tv and o not in version_of_file and (kind_of.get(o) in VERSION_BOUND or kind_of.get(o) == 'contig_table'):
360
+ claims[o].append({'version': tv, 'where': where, 'command': st['command'], 'how': 'lift_target'})
361
+ for i in ins:
362
+ if i != o and i not in version_of_file and kind_of.get(i) in VERSION_BOUND and kind_of.get(o) in VERSION_BOUND:
363
+ links.append({'a': o, 'b': i, 'where': where, 'kind': 'lifted'})
364
+ continue
365
+ if len(in_versions) > 1:
366
+ for o in outs:
367
+ for i in ins:
368
+ if i != o and i not in version_of_file and kind_of.get(i) in VERSION_BOUND and kind_of.get(o) in VERSION_BOUND:
369
+ links.append({'a': o, 'b': i, 'where': where, 'kind': 'several_versions_in'})
370
+ continue
371
+ if len(in_versions) == 1:
372
+ v = next(iter(in_versions))
373
+ for o in outs:
374
+ if o in version_of_file:
375
+ if not st['copy'] and not same_content(version_of_file[o], v):
376
+ lineage.append({'parent': v, 'child': version_of_file[o], 'where': where, 'command': st['command']})
377
+ elif kind_of.get(o) in VERSION_BOUND or kind_of.get(o) == 'contig_table':
378
+ claims[o].append({'version': v, 'where': where, 'command': st['command']})
379
+ for o in outs:
380
+ for i in ins:
381
+ if i != o and i not in version_of_file and (kind_of.get(i) in VERSION_BOUND) \
382
+ and (kind_of.get(o) in VERSION_BOUND) and not kind_of.get(i, '').endswith('index'):
383
+ links.append({'a': o, 'b': i, 'where': where, 'kind': 'derived_from'})
384
+ return dict(claims), lineage, links, copies
385
+
386
+
387
+ def compare_claims(claims, attribution_of, same_content):
388
+ rows = []
389
+ for f, cl in sorted(claims.items()):
390
+ declared = sorted({c['version'] for c in cl})
391
+ att = attribution_of.get(f, {})
392
+ best, status = att.get('best'), att.get('status')
393
+ if len(declared) > 1 and not all(same_content(declared[0], d) for d in declared):
394
+ verdict = 'conflicting_declarations'
395
+ elif status in ('matches_no_version', 'inconsistent_with_every_version'):
396
+ verdict = 'contradicted_by_unlisted_reference'
397
+ elif status == 'conflicting_evidence':
398
+ verdict = 'conflicting_evidence'
399
+ elif not isinstance(best, str) or status in ('no_evidence', 'weak', 'undecided', None):
400
+ verdict = 'unverifiable'
401
+ elif any(same_content(best, d) for d in declared):
402
+ verdict = 'confirmed'
403
+ elif status in ('decisive', 'very_strong', 'strong'):
404
+ verdict = 'contradicted'
405
+ else:
406
+ verdict = 'unverifiable'
407
+ rows.append({'artefact': f, 'declared': declared, 'observed': best, 'observed_status': status,
408
+ 'verdict': verdict, 'where': [c['where'] for c in cl][:5]})
409
+ return rows
410
+
411
+
412
+ def compare_lineage(lineage, versions, same_content):
413
+ parent = {v['id']: v.get('parent') for v in versions}
414
+ rows = []
415
+ for e in lineage:
416
+ if not e.get('parent'):
417
+ continue # a version recorded as made from reads alone
418
+ inferred = parent.get(e['child'])
419
+ ok = inferred is not None and same_content(inferred, e['parent'])
420
+ rows.append({**e, 'inferred_parent': inferred, 'verdict': 'confirmed' if ok else 'differs'})
421
+ return rows
422
+
423
+
424
+ JOINT_LINKS = ('derived_from', 'shared_identifiers')
425
+ LINK_ERROR = 0.05 # probability that a recorded derivation crosses to another version
426
+ BREAK_P = 0.95
427
+ POSSIBLE_BREAK_P = 0.5
428
+ INHERIT_P = 0.9 # one link alone gives at most 1 - lambda
429
+
430
+
431
+ def _lnorm(d):
432
+ m = max(d.values())
433
+ z = m + math.log(sum(math.exp(x - m) for x in d.values()))
434
+ return {k: x - z for k, x in d.items()}
435
+
436
+
437
+ def joint_attribution(attributions, links, same_content, *, link_error=LINK_ERROR):
438
+ """Belief propagation over derivation links between files.
439
+
440
+ Each file contributes its own evidence (the bounded group likelihood of its
441
+ attribution); a link (a derived file and what it was made from, or files
442
+ sharing gene identifiers) is a factor that prefers both ends on the same
443
+ version, psi = 1 - lambda for the same content class and lambda/(V-1)
444
+ otherwise. Liftovers and commands reading several versions are not same-version
445
+ links and are left out. Sum-product gives each file's marginal; a file without
446
+ evidence of its own inherits the version its chain makes at least 90% probable,
447
+ and a link whose ends are, jointly, more than 95% likely to lie on different
448
+ versions is reported as a break (more than 50%: a possible break), with the
449
+ evidence of both ends: the data cannot say which end is the stale one. Frame-integrity evidence of an
450
+ annotation is dropped when proteins linked to it already test the same CDS.
451
+ """
452
+ att = {r['relpath']: r for r in attributions}
453
+ use = [l for l in links if l.get('kind', 'derived_from') in JOINT_LINKS and l['a'] in att and l['b'] in att
454
+ and l['a'] != l['b']]
455
+ nbr = defaultdict(set)
456
+ for l in use:
457
+ nbr[l['a']].add(l['b']); nbr[l['b']].add(l['a'])
458
+ if not nbr:
459
+ return {'chains': [], 'inherited': {}, 'breaks': []}
460
+ versions = None
461
+ for r in attributions:
462
+ ll = r['attribution'].get('log_likelihood')
463
+ if ll:
464
+ versions = sorted(ll, key=lambda v: int(v[1:]) if v[1:].isdigit() else 0); break
465
+ if versions is None:
466
+ return {'chains': [], 'inherited': {}, 'breaks': []}
467
+ V = len(versions)
468
+ lpsi = {(x, y): math.log(1 - link_error) if same_content(x, y) else math.log(link_error / max(1, V - 1))
469
+ for x in versions for y in versions}
470
+ shared = {l['b'] for l in use if l.get('kind') == 'shared_identifiers'} | \
471
+ {l['a'] for l in use if l.get('kind') == 'shared_identifiers'}
472
+
473
+ def unary(m):
474
+ a = att[m]['attribution']
475
+ ll = dict(a.get('log_likelihood') or {})
476
+ if not ll:
477
+ return {v: 0.0 for v in versions}, False
478
+ g = (a.get('groups') or {}).get('cds_frame')
479
+ if m in shared and g:
480
+ ll = {v: ll[v] - g['log_likelihood'][v] for v in versions}
481
+ return {v: ll.get(v, 0.0) for v in versions}, True
482
+ U, has = {}, {}
483
+ for m in nbr:
484
+ U[m], has[m] = unary(m)
485
+ msg = {(a, b): {v: 0.0 for v in versions} for a in nbr for b in nbr[a]}
486
+ for _ in range(60): # exact on trees after diameter rounds; damped on cycles
487
+ new = {}
488
+ for (a, b) in msg:
489
+ h = {x: U[a][x] + sum(msg[(c, a)][x] for c in nbr[a] if c != b) for x in versions}
490
+ out = {}
491
+ for y in versions:
492
+ terms = [h[x] + lpsi[(x, y)] for x in versions]
493
+ mx = max(terms)
494
+ out[y] = mx + math.log(sum(math.exp(t - mx) for t in terms))
495
+ out = _lnorm(out)
496
+ old = msg[(a, b)]
497
+ new[(a, b)] = {v: math.log(0.5 * math.exp(out[v]) + 0.5 * math.exp(old[v])) for v in versions}
498
+ delta = max(abs(new[e][v] - msg[e][v]) for e in msg for v in versions)
499
+ msg = new
500
+ if delta < 1e-9:
501
+ break
502
+ marg = {}
503
+ for m in nbr:
504
+ marg[m] = _lnorm({x: U[m][x] + sum(msg[(c, m)][x] for c in nbr[m]) for x in versions})
505
+ seen, chains = set(), []
506
+ for m in nbr:
507
+ if m in seen:
508
+ continue
509
+ comp, stack = [], [m]
510
+ seen.add(m)
511
+ while stack:
512
+ x = stack.pop(); comp.append(x)
513
+ for y in nbr[x]:
514
+ if y not in seen:
515
+ seen.add(y); stack.append(y)
516
+ tot = _lnorm({v: sum(marg[x][v] for x in comp) for v in versions})
517
+ best = max(tot, key=tot.get)
518
+ chains.append({'members': sorted(comp), 'consensus': best,
519
+ 'members_versions': {x: max(marg[x], key=marg[x].get) for x in sorted(comp)},
520
+ 'members_probability': {x: round(math.exp(max(marg[x].values())), 4) for x in sorted(comp)}})
521
+ inherited = {}
522
+ for m in nbr:
523
+ if not has[m]:
524
+ v = max(marg[m], key=marg[m].get)
525
+ p = math.exp(marg[m][v])
526
+ if p >= INHERIT_P:
527
+ inherited[m] = {'version': v, 'probability': round(p, 4), 'via': sorted(nbr[m])}
528
+ breaks, done = [], set()
529
+ for l in use:
530
+ a, b = l['a'], l['b']
531
+ if (a, b) in done or (b, a) in done or not (has[a] and has[b]):
532
+ continue
533
+ done.add((a, b))
534
+ ha = {x: U[a][x] + sum(msg[(c, a)][x] for c in nbr[a] if c != b) for x in versions}
535
+ hb = {y: U[b][y] + sum(msg[(c, b)][y] for c in nbr[b] if c != a) for y in versions}
536
+ joint = {(x, y): ha[x] + hb[y] + lpsi[(x, y)] for x in versions for y in versions}
537
+ mx = max(joint.values())
538
+ z = sum(math.exp(t - mx) for t in joint.values())
539
+ p_diff = sum(math.exp(t - mx) for (x, y), t in joint.items() if not same_content(x, y)) / z
540
+ if p_diff > POSSIBLE_BREAK_P:
541
+ xa = max(versions, key=lambda x: ha[x]); yb = max(versions, key=lambda y: hb[y])
542
+ sa, sb = att[a]['attribution'], att[b]['attribution']
543
+ breaks.append({'files': [a, b], 'versions': [xa, yb], 'probability_different': round(p_diff, 4),
544
+ 'level': 'break' if p_diff > BREAK_P else 'possible_break',
545
+ 'evidence': {a: {'status': sa['status'], 'log10_bayes_factor': sa.get('log10_bayes_factor')},
546
+ b: {'status': sb['status'], 'log10_bayes_factor': sb.get('log10_bayes_factor')}},
547
+ 'where': l.get('where'), 'link': l.get('kind', 'derived_from')})
548
+ return {'chains': chains, 'inherited': inherited, 'breaks': breaks}
549
+
550
+
551
+ def read_links(artefacts, min_sketch=20):
552
+ """Which read files each alignment's reads came from; paired-file and QC report consistency."""
553
+ reads = [a for a in artefacts if a['kind'] in ('fastq', 'reads_fasta', 'ubam')]
554
+ sketches = {a['relpath']: set(a.get('reads', {}).get('name_sketch') or a.get('read_name_sketch') or []) for a in reads}
555
+ out = {'alignment_sources': [], 'pairs': [], 'qc_reports': []}
556
+ full = {a['relpath']: set(a['reads']['all_names']) for a in reads if a.get('reads', {}).get('all_names')}
557
+ for a in artefacts:
558
+ if a['kind'] not in ('bam', 'cram', 'sam'):
559
+ continue
560
+ s, first = set(a.get('read_name_sketch') or []), set(a.get('read_first_names') or [])
561
+ cont = {}
562
+ if len(s) >= min_sketch: # comparable hashed subsamples
563
+ for r, t in sketches.items():
564
+ if t:
565
+ cont[r] = len(s & t) / len(s)
566
+ if first: # small read files keep every name
567
+ for r, t in full.items():
568
+ cont[r] = max(cont.get(r, 0.0), len(first & t) / len(first))
569
+ if not cont:
570
+ out['alignment_sources'].append({'alignment': a['relpath'], 'status': 'not_evaluable',
571
+ 'reason': 'too few reads to compare names'})
572
+ continue
573
+ src = [{'reads': r, 'containment': round(c, 3)} for r, c in sorted(cont.items(), key=lambda x: -x[1]) if c >= 0.05]
574
+ explained = max(cont.values()) if cont else 0.0
575
+ if len(s) >= min_sketch:
576
+ union = set().union(*[t for t in sketches.values() if t]) if sketches else set()
577
+ explained = max(explained, len(s & union) / len(s))
578
+ out['alignment_sources'].append({'alignment': a['relpath'], 'sources': src, 'explained': round(explained, 3),
579
+ 'status': 'reads_in_project' if explained >= 0.9 else
580
+ ('partly_in_project' if explained >= 0.1 else 'reads_not_in_project')})
581
+ by_pair = defaultdict(dict)
582
+ for a in reads:
583
+ pk = a.get('reads', {}).get('pair_key')
584
+ if pk:
585
+ d = str(PurePosixPath(a['relpath']).parent)
586
+ by_pair[pk[0] if d == '.' else f'{d}/{pk[0]}'][pk[1]] = a
587
+ for key, mates in by_pair.items():
588
+ if set(mates) != {'1', '2'}:
589
+ out['pairs'].append({'pair': key, 'status': 'mate_missing', 'present': sorted(m['relpath'] for m in mates.values())})
590
+ continue
591
+ r1, r2 = mates['1'], mates['2']
592
+ c1, c2 = r1['reads']['count'], r2['reads']['count']
593
+ s1, s2 = set(r1['reads']['name_sketch']), set(r2['reads']['name_sketch'])
594
+ same = len(s1 & s2) / len(s1 | s2) if (s1 | s2) else (1.0 if r1['reads'].get('first_name') == r2['reads'].get('first_name') else 0.0)
595
+ if same == 0 and r1['reads'].get('first_name') != r2['reads'].get('first_name'):
596
+ continue # no shared read names: numbered chunks (MinKNOW _1, _2), not mates
597
+ status = 'consistent' if c1 == c2 and same >= 0.99 else 'inconsistent'
598
+ out['pairs'].append({'pair': key, 'mate1': r1['relpath'], 'mate2': r2['relpath'], 'reads1': c1, 'reads2': c2,
599
+ 'shared_names': round(same, 4), 'status': status})
600
+ counts = {a['relpath']: a['reads']['count'] for a in reads if a.get('reads', {}).get('count')}
601
+ for a in artefacts:
602
+ q = a.get('qc')
603
+ if not q or q.get('read_count') is None:
604
+ continue
605
+ named = q.get('reports_on')
606
+ match = [r for r, c in counts.items() if c == q['read_count'] or (q.get('paired') and c * 2 == q['read_count'])]
607
+ by_name = [r for r in counts if named and PurePosixPath(r).name == named]
608
+ status = 'matches' if match and (not by_name or set(by_name) & set(match)) else (
609
+ 'count_differs' if by_name else 'no_read_file_with_this_count')
610
+ out['qc_reports'].append({'report': a['relpath'], 'read_count': q['read_count'], 'reports_on': named,
611
+ 'matching_read_files': match, 'status': status})
612
+ return out