assemblytrace 1.1.0__py3-none-any.whl
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- assemblytrace/__init__.py +1 -0
- assemblytrace/__main__.py +4 -0
- assemblytrace/annotation.py +307 -0
- assemblytrace/attribute.py +1388 -0
- assemblytrace/change.py +221 -0
- assemblytrace/claims.py +612 -0
- assemblytrace/cli.py +230 -0
- assemblytrace/core.py +100 -0
- assemblytrace/curation.py +155 -0
- assemblytrace/formats.py +957 -0
- assemblytrace/identity.py +74 -0
- assemblytrace/indels.py +95 -0
- assemblytrace/inventory.py +379 -0
- assemblytrace/io_safety.py +69 -0
- assemblytrace/lift.py +467 -0
- assemblytrace/localmatch.py +51 -0
- assemblytrace/project.py +494 -0
- assemblytrace/prov.py +277 -0
- assemblytrace/provenance.py +183 -0
- assemblytrace/py.typed +0 -0
- assemblytrace/release.py +432 -0
- assemblytrace/report.py +1046 -0
- assemblytrace/scan.py +538 -0
- assemblytrace/segments.py +348 -0
- assemblytrace/seqcol.py +161 -0
- assemblytrace/shellexp.py +229 -0
- assemblytrace/sparsediff.py +905 -0
- assemblytrace/summary.py +146 -0
- assemblytrace/variant_input.py +91 -0
- assemblytrace/versions.py +583 -0
- assemblytrace-1.1.0.dist-info/METADATA +198 -0
- assemblytrace-1.1.0.dist-info/RECORD +36 -0
- assemblytrace-1.1.0.dist-info/WHEEL +5 -0
- assemblytrace-1.1.0.dist-info/entry_points.txt +2 -0
- assemblytrace-1.1.0.dist-info/licenses/LICENSE +21 -0
- assemblytrace-1.1.0.dist-info/top_level.txt +1 -0
assemblytrace/project.py
ADDED
|
@@ -0,0 +1,494 @@
|
|
|
1
|
+
"""One-command project audit: versions, their differences, attribution of every file, provenance exports."""
|
|
2
|
+
from __future__ import annotations
|
|
3
|
+
|
|
4
|
+
import math
|
|
5
|
+
|
|
6
|
+
import csv
|
|
7
|
+
import io
|
|
8
|
+
import json
|
|
9
|
+
import sys
|
|
10
|
+
from pathlib import Path
|
|
11
|
+
|
|
12
|
+
from .scan import scan
|
|
13
|
+
from . import claims
|
|
14
|
+
from .versions import version_graph
|
|
15
|
+
from .attribute import attribute_all
|
|
16
|
+
from .core import load
|
|
17
|
+
from .curation import safe_name, curation_paths, write_curation
|
|
18
|
+
from .lift import transition
|
|
19
|
+
from .prov import prov_json, ro_crate, lockfile
|
|
20
|
+
from .report import render
|
|
21
|
+
from .io_safety import atomic_write_text, validate_output_paths
|
|
22
|
+
from .summary import OUTPUTS, SUMMARY_NAME, compact_summary, incomplete_summary
|
|
23
|
+
VERSION_BOUND = ('gff', 'protein', 'vcf', 'busco', 'quast', 'bed', 'agp')
|
|
24
|
+
|
|
25
|
+
|
|
26
|
+
def _log(msg):
|
|
27
|
+
print(f'assemblytrace: {msg}', file=sys.stderr, flush=True)
|
|
28
|
+
|
|
29
|
+
|
|
30
|
+
def _same_content(graph, x, y):
|
|
31
|
+
cls = {v['id']: v['content_class'] for v in graph['versions']}
|
|
32
|
+
return cls.get(x) == cls.get(y)
|
|
33
|
+
|
|
34
|
+
|
|
35
|
+
def _pair(graph, x, y):
|
|
36
|
+
return next(p for p in graph['pairs'] if {p['a'], p['b']} == {x, y})
|
|
37
|
+
|
|
38
|
+
|
|
39
|
+
def project_control(sc, graph, attributions, project, log):
|
|
40
|
+
"""Integrity, indexes, declared versus observed provenance, derivation chains, raw reads, stages."""
|
|
41
|
+
from . import inventory, claims
|
|
42
|
+
arts = sc['artefacts']
|
|
43
|
+
same = lambda x, y: x is not None and y is not None and _same_content(graph, x, y)
|
|
44
|
+
version_of_file = {f: v['id'] for v in graph['versions'] for f in v['files']}
|
|
45
|
+
from .scan import Cache
|
|
46
|
+
issues, duplicates = inventory.integrity(arts, project, sc.get('broken_links', []), cache=Cache(project))
|
|
47
|
+
resolver = claims.Resolver([a['relpath'] for a in arts], project.name)
|
|
48
|
+
statements = claims.collect_statements(arts, resolver)
|
|
49
|
+
declared, lineage, links, copies = claims.derive(statements, arts, version_of_file, same)
|
|
50
|
+
for r in attributions: # files linked through shared identifiers
|
|
51
|
+
for key in ('protein', 'interproscan', 'cds'):
|
|
52
|
+
g = (r.get('detail') or {}).get(key, {})
|
|
53
|
+
if isinstance(g, dict) and g.get('gff'):
|
|
54
|
+
links.append({'a': r['relpath'], 'b': g['gff'], 'kind': 'shared_identifiers', 'where': key})
|
|
55
|
+
att = {r['relpath']: r['attribution'] for r in attributions}
|
|
56
|
+
claim_rows = claims.compare_claims(declared, att, same)
|
|
57
|
+
lineage_rows = claims.compare_lineage(lineage, graph['versions'], same)
|
|
58
|
+
sha = {a['relpath']: a.get('sha256') for a in arts}
|
|
59
|
+
copy_rows = []
|
|
60
|
+
for c in copies:
|
|
61
|
+
a_, b_ = sha.get(c['source']), sha.get(c['copy'])
|
|
62
|
+
if a_ and b_:
|
|
63
|
+
copy_rows.append({**c, 'status': 'identical' if a_ == b_ else 'differs'})
|
|
64
|
+
joint = claims.joint_attribution(attributions, links, same)
|
|
65
|
+
reads = claims.read_links(arts)
|
|
66
|
+
indexes = inventory.stale_reference_indexes(arts, attributions, version_of_file, same, graph)
|
|
67
|
+
stages = inventory.stage_matrix(arts, attributions, graph['versions'], graph.get('latest'), same, joint['inherited'])
|
|
68
|
+
external = sorted({x for s in statements for x in s.get('external', [])})
|
|
69
|
+
log(f'control: {len(issues)} integrity notes, {len(statements)} recorded commands, {len(claim_rows)} declared versions, '
|
|
70
|
+
f'{len(links)} derivation links, {len(joint["breaks"])} chain breaks')
|
|
71
|
+
return {'integrity': issues, 'duplicates': duplicates, 'statements': len(statements), 'claims': claim_rows,
|
|
72
|
+
'lineage_claims': lineage_rows, 'copies': copy_rows, 'links': links, 'joint': joint, 'reads': reads,
|
|
73
|
+
'reference_indexes': indexes, 'stages': stages, 'stage_summary': inventory.stage_summary(arts),
|
|
74
|
+
'external_inputs': external}
|
|
75
|
+
|
|
76
|
+
|
|
77
|
+
STALE_LOG10 = 1.5 # log10 likelihood ratio of the file's version over the latest that makes it stale
|
|
78
|
+
|
|
79
|
+
|
|
80
|
+
SEVERITY_RANK = {'info': 0, 'review': 1, 'fail': 2}
|
|
81
|
+
CODE = '\0' # delimits a command or option inside a suggested action; NUL cannot occur in a path
|
|
82
|
+
|
|
83
|
+
|
|
84
|
+
def _cmd(text):
|
|
85
|
+
return f'{CODE}{text}{CODE}'
|
|
86
|
+
|
|
87
|
+
|
|
88
|
+
def assess(graph, attributions, control=None) -> dict:
|
|
89
|
+
"""The findings of a scan, each with the severity it raises the verdict to and a suggested action.
|
|
90
|
+
|
|
91
|
+
Returns {'status', 'items', 'latest'}. Every item holds the finding text that ``verdict`` publishes, its
|
|
92
|
+
severity ('fail', 'review' or 'info'), the project files it concerns, a specific action, a general next
|
|
93
|
+
step (None for information only) and whether that step comes first (``first``: the other checks depend on
|
|
94
|
+
it). The report shows the severities and actions; scan.json keeps the texts.
|
|
95
|
+
"""
|
|
96
|
+
items = []
|
|
97
|
+
control = control or {}
|
|
98
|
+
|
|
99
|
+
def add(severity, text, action, step=None, files=(), first=False):
|
|
100
|
+
items.append({'severity': severity, 'text': text, 'action': action, 'step': step,
|
|
101
|
+
'files': [f for f in files if f], 'first': first})
|
|
102
|
+
|
|
103
|
+
errors = [i for i in control.get('integrity', []) if i['severity'] == 'error']
|
|
104
|
+
if errors:
|
|
105
|
+
add('fail', f'{len(errors)} file integrity error(s): ' + '; '.join(f'{i["file"]} {i["code"]}' for i in errors[:8])
|
|
106
|
+
+ (' ...' if len(errors) > 8 else '') + '.',
|
|
107
|
+
'Replace each damaged file from a backup or its original source, or re-create it with the step that made '
|
|
108
|
+
'it. Where a checksum does not match, find out whether the file or the checksum list is out of date. '
|
|
109
|
+
'Then run the scan again.',
|
|
110
|
+
'Repair or re-create the damaged files, then run the scan again.', [i['file'] for i in errors])
|
|
111
|
+
for r in control.get('reference_indexes', []):
|
|
112
|
+
if r['status'] == 'stale':
|
|
113
|
+
add('fail', f'{r["index"]} indexes {r["index_version"]}, but the FASTA beside it is {r["fasta_version"]}: '
|
|
114
|
+
'aligners using this index work on the old sequence.',
|
|
115
|
+
f'Rebuild {r["index"]} from {r.get("fasta") or "the FASTA beside it"} with the tool that made it, then '
|
|
116
|
+
'redo every alignment made with the old index.',
|
|
117
|
+
'Rebuild out-of-date reference indexes and redo the alignments made with them.', [r['index']])
|
|
118
|
+
for c in control.get('claims', []):
|
|
119
|
+
if c['verdict'] == 'contradicted':
|
|
120
|
+
add('fail', f'{c["artefact"]}: the workflow record ({", ".join(c["where"][:2])}) says it was made from '
|
|
121
|
+
f'{", ".join(c["declared"])}, its content shows {c["observed"]} ({c["observed_status"]}).',
|
|
122
|
+
'Find out which reference was really used. Re-create the file from the version the record names, or '
|
|
123
|
+
'correct the record if the content is right.',
|
|
124
|
+
'Where a workflow record and a file disagree, find out which reference was used, then re-create the '
|
|
125
|
+
'file or correct the record.', [c['artefact']])
|
|
126
|
+
elif c['verdict'] == 'contradicted_by_unlisted_reference':
|
|
127
|
+
add('fail', f'{c["artefact"]}: the workflow record ({", ".join(c["where"][:2])}) says it was made from '
|
|
128
|
+
f'{", ".join(c["declared"])}, but its content fits no version in the project ({c["observed_status"]}).',
|
|
129
|
+
'The reference it was made from is not in the project. Add that reference, or re-create the file '
|
|
130
|
+
'from a version that is in the project.',
|
|
131
|
+
'Where a workflow record and a file disagree, find out which reference was used, then re-create the '
|
|
132
|
+
'file or correct the record.', [c['artefact']])
|
|
133
|
+
elif c['verdict'] in ('conflicting_declarations', 'conflicting_evidence'):
|
|
134
|
+
what = 'workflow records name different versions' if c['verdict'] == 'conflicting_declarations' \
|
|
135
|
+
else 'its evidence groups favour different versions'
|
|
136
|
+
add('review', f'{c["artefact"]}: {what} ({", ".join(c["declared"])} declared).',
|
|
137
|
+
'Find out which version the file was made from, keep one consistent record of it, and re-create the '
|
|
138
|
+
'file if needed.',
|
|
139
|
+
'Settle the files whose records or evidence name different versions.', [c['artefact']])
|
|
140
|
+
for e in control.get('lineage_claims', []):
|
|
141
|
+
if e['verdict'] == 'differs':
|
|
142
|
+
add('info', f'{e["child"]} is recorded as made from {e["parent"]} ({e["where"]}), and elsewhere as made '
|
|
143
|
+
f'from {e["inferred_parent"]}; the first record read was used.',
|
|
144
|
+
'Correct the workflow records so that each version names one source.')
|
|
145
|
+
for c in control.get('copies', []):
|
|
146
|
+
if c['status'] == 'differs':
|
|
147
|
+
add('fail', f'{c["copy"]} was recorded as a copy of {c["source"]} ({c["where"]}) but their contents differ.',
|
|
148
|
+
f'Copy {c["source"]} again, or record the change made to {c["copy"]} after it was copied.',
|
|
149
|
+
'Re-copy files that no longer match the file they were copied from, or record the later change.',
|
|
150
|
+
[c['copy'], c['source']])
|
|
151
|
+
for b in control.get('joint', {}).get('breaks', []):
|
|
152
|
+
(fa, fb), (va, vb) = b['files'], b['versions']
|
|
153
|
+
add('fail' if b['level'] == 'break' else 'review',
|
|
154
|
+
f'Derivation link {"broken" if b["level"] == "break" else "possibly broken"} '
|
|
155
|
+
f'({b.get("where") or b["link"]}): {fa} is on {va} and {fb} on {vb} '
|
|
156
|
+
f'(probability {b["probability_different"]:.3f} that they lie on different versions); one of the two '
|
|
157
|
+
'was regenerated against another version without the other.',
|
|
158
|
+
f'Find out which of {fa} and {fb} is out of date and re-create it from the same version as the other '
|
|
159
|
+
'(normally the release).',
|
|
160
|
+
'Re-create linked files that were made from different versions, so that each chain of files uses one '
|
|
161
|
+
'version.', [fa, fb])
|
|
162
|
+
rd = control.get('reads', {})
|
|
163
|
+
for p in rd.get('pairs', []):
|
|
164
|
+
if p['status'] != 'consistent':
|
|
165
|
+
add('fail' if p['status'] == 'inconsistent' else 'review',
|
|
166
|
+
f'Paired read files {p["pair"]}: {p["status"].replace("_", " ")}.',
|
|
167
|
+
'Check that both mate files come from the same run and are complete (the same number of reads with '
|
|
168
|
+
'the same names); copy or download them again if not.',
|
|
169
|
+
'Check the paired read files whose mates do not match.', [p.get('mate1'), p.get('mate2')])
|
|
170
|
+
for q in rd.get('qc_reports', []):
|
|
171
|
+
if q['status'] != 'matches':
|
|
172
|
+
add('review', f'{q["report"]} reports {q["read_count"]:,} reads; {q["status"].replace("_", " ")}.',
|
|
173
|
+
f'Run the read QC again on the current read file, or find out which read file {q["report"]} describes.',
|
|
174
|
+
'Run read QC again where a report does not match its read file.', [q['report']])
|
|
175
|
+
for s in rd.get('alignment_sources', []):
|
|
176
|
+
if s.get('status') == 'reads_not_in_project':
|
|
177
|
+
add('info', f'{s["alignment"]}: its reads come from no read file in the project.',
|
|
178
|
+
'Add the read files used for this alignment to the project, or note where they are kept.',
|
|
179
|
+
files=[s['alignment']])
|
|
180
|
+
for s in control.get('stages', {}).get('stages_missing_latest', []):
|
|
181
|
+
stage = s['stage'].replace('_', ' ')
|
|
182
|
+
add('review', f'Stage "{stage}" exists only for {", ".join(s["versions_with_files"])}, '
|
|
183
|
+
f'not for the latest version {s["latest"]}.',
|
|
184
|
+
f'Run the {stage} step again on the latest version {s["latest"]}; if an older version is the real '
|
|
185
|
+
f'release, declare it with {_cmd("--latest FILE")}.',
|
|
186
|
+
f'Run the steps that exist only for older versions again on the latest version {s["latest"]}, or declare '
|
|
187
|
+
f'the real release with {_cmd("--latest FILE")}.')
|
|
188
|
+
if control.get('external_inputs'):
|
|
189
|
+
add('info', f'{len(control["external_inputs"])} input file(s) named in workflow records are not in the project, e.g. '
|
|
190
|
+
+ ', '.join(control['external_inputs'][:3]) + '.',
|
|
191
|
+
'Add these inputs to the project, or record where they are kept, so that the record of how the files '
|
|
192
|
+
'were made is complete.')
|
|
193
|
+
versions = graph['versions']
|
|
194
|
+
if not versions: # nothing to check against: the verdict publishes no findings
|
|
195
|
+
return {'status': 'fail', 'items': [], 'latest': None}
|
|
196
|
+
latest = graph.get('latest')
|
|
197
|
+
latest_files = next((v['files'] for v in versions if v['id'] == latest), [])
|
|
198
|
+
if len(versions) > 1:
|
|
199
|
+
basis = {'declared': 'declared as the release', 'recorded': 'the latest in the lineage the workflow records',
|
|
200
|
+
'ambiguous': 'taken as the latest, but this is ambiguous'}
|
|
201
|
+
add('info', f'{len(versions)} distinct assembly versions found across {sum(len(v["files"]) for v in versions)} FASTA files; '
|
|
202
|
+
f'{latest} is {basis.get(graph.get("latest_status"), "the latest")}.',
|
|
203
|
+
'No action needed; this lists what was found.')
|
|
204
|
+
if graph.get('latest_status') == 'ambiguous':
|
|
205
|
+
example = (f', for example {_cmd("--latest " + latest_files[0])} if {latest} is the release'
|
|
206
|
+
if latest_files else '')
|
|
207
|
+
add('review', f'The latest version is ambiguous ({graph.get("latest_reason")}); declare it with --latest so '
|
|
208
|
+
'files are checked against the release.',
|
|
209
|
+
f'Tell AssemblyTrace which assembly is the release: run the scan again with {_cmd("--latest FILE")}{example}.',
|
|
210
|
+
f'Declare the release by running the scan again with {_cmd("--latest FILE")}; the files are then '
|
|
211
|
+
'checked against it.', first=True)
|
|
212
|
+
for v in versions:
|
|
213
|
+
if v.get('layout_check') == 'not_supported_by_layout':
|
|
214
|
+
add('review', f'{v["id"]}: the workflow records {v["parent"]} as its source, but {v["id"]} has contigs or '
|
|
215
|
+
f'header marks that {v["parent"]} lacks; check the record.',
|
|
216
|
+
f'Check the record that names {v["parent"]} as the source of {v["id"]}, and correct it if it is wrong.',
|
|
217
|
+
'Check the workflow records whose recorded source the sequences do not support.', v['files'])
|
|
218
|
+
elif v.get('parent') is None and v.get('lineage_basis') is None and len(versions) > 1 and v.get('parent_candidates'):
|
|
219
|
+
add('info', f'{v["id"]}: its source is not recorded and the layout does not single one out (could be '
|
|
220
|
+
+ ', '.join(v['parent_candidates']) + ').',
|
|
221
|
+
'Keep the command that made each version (for example the polishing script or its log) in the '
|
|
222
|
+
'project, so that its source is recorded.')
|
|
223
|
+
for v in versions:
|
|
224
|
+
if len(v['files']) > 1:
|
|
225
|
+
add('info', f'{v["id"]} is stored under {len(v["files"])} file names with identical content: ' + ', '.join(v['files']) + '.',
|
|
226
|
+
'No action needed if the copies are intended; otherwise keep one of them.')
|
|
227
|
+
if v.get('parent_relation') == 'same_sequence_content':
|
|
228
|
+
add('info', f'{v["id"]} has the same sequences as {v["parent"]} under different names or order.',
|
|
229
|
+
'No action needed if the renaming was intended; use one naming in the files made from it.')
|
|
230
|
+
for p in graph['pairs']:
|
|
231
|
+
if p.get('stretches'):
|
|
232
|
+
st = p['stretches']
|
|
233
|
+
add('info', f'{p["a"]} to {p["b"]}: {len(st)} stretch(es) differ beyond the local window '
|
|
234
|
+
f'({sum(x["length_a"] for x in st):,} bases replaced by {sum(x["length_b"] for x in st):,}), e.g. '
|
|
235
|
+
f'{st[0]["contig"]}:{st[0]["ref_pos"]:,}; each is one replacement event, the rest of the contig '
|
|
236
|
+
'is compared base by base.',
|
|
237
|
+
'No action needed; each replaced stretch is listed in events.tsv.')
|
|
238
|
+
if p['unresolved']:
|
|
239
|
+
add('review', f'{p["a"]} to {p["b"]}: {len(p["unresolved"])} contig(s) diverge beyond the local window; run paf-changes with a minimap2 alignment for these.',
|
|
240
|
+
f'Align {p["a"]} and {p["b"]} with {_cmd("minimap2 -c --cs")} and run {_cmd("assemblytrace paf-changes")} '
|
|
241
|
+
'on the alignment for these contigs.',
|
|
242
|
+
f'Align the versions that differ too much to compare directly with minimap2, and run '
|
|
243
|
+
f'{_cmd("assemblytrace paf-changes")}.')
|
|
244
|
+
undecided_step = 'Find out which version the undecided files were made from, or re-create them from the release.'
|
|
245
|
+
for r in attributions:
|
|
246
|
+
a = r['attribution']
|
|
247
|
+
if a['status'] in ('no_evidence', 'not_version_bound'):
|
|
248
|
+
if a['status'] == 'no_evidence' and r['kind'] in VERSION_BOUND and len(versions) > 1:
|
|
249
|
+
add('review', f'{r["relpath"]}: no evidence distinguishes the versions for this file.',
|
|
250
|
+
'Find out which version this file was made from: keep the command or log that made it in the '
|
|
251
|
+
'project, or re-create it from the release.', undecided_step, [r['relpath']])
|
|
252
|
+
continue
|
|
253
|
+
best = a['best']
|
|
254
|
+
if a['status'] in ('matches_no_version', 'inconsistent_with_every_version', 'conflicting_evidence') \
|
|
255
|
+
and r['kind'].split(':')[0] in VERSION_BOUND + ('bam', 'cram', 'sam', 'contig_table'):
|
|
256
|
+
step = ('Find the references used for the files that fit no version in the project, or re-create those '
|
|
257
|
+
'files from the release.')
|
|
258
|
+
if a['status'] == 'conflicting_evidence':
|
|
259
|
+
why = '; '.join(f'{g} favours {a["groups"][g]["best"]}' for g in a.get('conflicting_groups', []))
|
|
260
|
+
add('review', f'{r["relpath"]}: its evidence conflicts ({why}).',
|
|
261
|
+
'Parts of the file point to different versions; re-create it from one version (normally the release).',
|
|
262
|
+
step, [r['relpath']])
|
|
263
|
+
elif a.get('closest'):
|
|
264
|
+
c = a['closest']
|
|
265
|
+
add('review', f'{r["relpath"]}: no version in the project explains it; closest {c["version"]}, with '
|
|
266
|
+
f'{c["inconsistent"]} of {c["items"]} {c["group"].replace("_", " ")} items inconsistent '
|
|
267
|
+
'(made from a version not kept, or mixed from several).',
|
|
268
|
+
'Find the assembly it was made from (it is not in the project) and add it, or re-create the file '
|
|
269
|
+
'from the release.', step, [r['relpath']])
|
|
270
|
+
else:
|
|
271
|
+
add('review', f'{r["relpath"]}: it matches no version in the project (made from a reference not kept here).',
|
|
272
|
+
'Find the reference it was made from and add it to the project, or re-create the file from the '
|
|
273
|
+
'release.', step, [r['relpath']])
|
|
274
|
+
continue
|
|
275
|
+
if a['status'] in ('weak', 'undecided'):
|
|
276
|
+
cands = best if isinstance(best, list) else [best]
|
|
277
|
+
if len(cands) > 1 and all(_same_content(graph, cands[0], c) for c in cands):
|
|
278
|
+
continue
|
|
279
|
+
add('review', f'{r["relpath"]}: attribution undecided ({a["status"]}).',
|
|
280
|
+
'Nothing in this file separates the candidate versions. Keep the command or log that made it in the '
|
|
281
|
+
'project, or re-create it from the release.', undecided_step, [r['relpath']])
|
|
282
|
+
elif isinstance(best, str) and latest and best != latest and not _same_content(graph, best, latest) \
|
|
283
|
+
and r['kind'] in VERSION_BOUND + ('bam', 'cram', 'sam'):
|
|
284
|
+
text = f'{r["relpath"]} belongs to {best} ({a["status"]}), not to the latest version {latest}.'
|
|
285
|
+
if r['kind'] in VERSION_BOUND:
|
|
286
|
+
firm = graph.get('latest_status') in ('declared', 'recorded')
|
|
287
|
+
# stale when the reference's own bases, as the file restates them, rule the latest version out: a
|
|
288
|
+
# label capped for sparse evidence still says that the latest version does not fit
|
|
289
|
+
ll = a.get('log_likelihood') or {}
|
|
290
|
+
against = (ll[best] - ll[latest]) / math.log(10) if best in ll and latest in ll else 0.0
|
|
291
|
+
stale = a['status'] in ('decisive', 'very_strong') or \
|
|
292
|
+
(a.get('basis') in ('content', 'content_sparse') and against >= STALE_LOG10)
|
|
293
|
+
add('fail' if firm and stale else 'review', text,
|
|
294
|
+
f'Re-create this file from the latest version {latest}; if {best} is the real release, declare it '
|
|
295
|
+
f'with {_cmd("--latest FILE")}.',
|
|
296
|
+
f'Re-create the files that were made from another version, this time from the latest version '
|
|
297
|
+
f'{latest}, or declare the real release with {_cmd("--latest FILE")}.', [r['relpath']])
|
|
298
|
+
else:
|
|
299
|
+
add('info', text, f'If this alignment is still used, align the reads again to the latest version {latest}.',
|
|
300
|
+
files=[r['relpath']])
|
|
301
|
+
worst = max((i['severity'] for i in items), key=SEVERITY_RANK.get, default='info')
|
|
302
|
+
return {'status': 'pass' if worst == 'info' else worst, 'items': items, 'latest': latest}
|
|
303
|
+
|
|
304
|
+
|
|
305
|
+
def verdict(graph, attributions, control=None) -> dict:
|
|
306
|
+
if not graph['versions']:
|
|
307
|
+
return {'status': 'fail', 'summary': 'No assembly FASTA found in the project.', 'findings': [], 'latest_version': None}
|
|
308
|
+
found = assess(graph, attributions, control)
|
|
309
|
+
status = found['status']
|
|
310
|
+
summary = {'pass': 'Every file is intact, every version-bound file is attributable, and nothing contradicts the latest assembly or the workflow records.',
|
|
311
|
+
'review': 'Some relations could not be settled from the evidence, or a stage lacks the latest version; see findings.',
|
|
312
|
+
'fail': 'At least one file is damaged, stale or contradicts its declared or linked provenance; see findings.'}[status]
|
|
313
|
+
return {'status': status, 'summary': summary, 'findings': [i['text'] for i in found['items']],
|
|
314
|
+
'latest_version': found['latest']}
|
|
315
|
+
|
|
316
|
+
|
|
317
|
+
def _finite(x):
|
|
318
|
+
"""JSON has no Infinity or NaN: such floats become null."""
|
|
319
|
+
if isinstance(x, float):
|
|
320
|
+
return x if x == x and x not in (float('inf'), float('-inf')) else None
|
|
321
|
+
if isinstance(x, dict):
|
|
322
|
+
return {k: _finite(v) for k, v in x.items()}
|
|
323
|
+
if isinstance(x, (list, tuple)):
|
|
324
|
+
return [_finite(v) for v in x]
|
|
325
|
+
return x
|
|
326
|
+
|
|
327
|
+
|
|
328
|
+
def _recorded_lineage(arts, project):
|
|
329
|
+
"""Lineage edges between assembly versions recorded by the workflow, before the version graph is built."""
|
|
330
|
+
from .versions import group_versions
|
|
331
|
+
vs = group_versions(arts)
|
|
332
|
+
vof = {f: v['id'] for v in vs for f in v['files']}
|
|
333
|
+
cls = {v['id']: v['content_class'] for v in vs}
|
|
334
|
+
same = lambda a, b: cls.get(a) == cls.get(b)
|
|
335
|
+
resolver = claims.Resolver([a['relpath'] for a in arts], Path(project).name)
|
|
336
|
+
statements = claims.collect_statements(arts, resolver)
|
|
337
|
+
_, lineage, _, _ = claims.derive(statements, arts, vof, same)
|
|
338
|
+
return lineage
|
|
339
|
+
|
|
340
|
+
|
|
341
|
+
def run_project(project, out_dir, *, k=31, threads=4, full_hash=False, name=None, quiet=False, latest=None,
|
|
342
|
+
license=None, command=None) -> dict:
|
|
343
|
+
"""Scan a project and write every output. ``command``: the command line that started the scan, shown in the
|
|
344
|
+
provenance section of report.html only (scan.json is unchanged)."""
|
|
345
|
+
project = Path(project).resolve()
|
|
346
|
+
out = Path(out_dir)
|
|
347
|
+
outputs = [out / n for n in OUTPUTS]
|
|
348
|
+
log = (lambda m: None) if quiet else _log
|
|
349
|
+
log(f'scanning {project}')
|
|
350
|
+
sc = scan(project, threads=threads, full_hash=full_hash, exclude=[out])
|
|
351
|
+
inputs = [Path(a['path']) for a in sc['artefacts']]
|
|
352
|
+
validate_output_paths(inputs, outputs)
|
|
353
|
+
log(f'{len(sc["artefacts"])} files: ' + ', '.join(f'{v} {k_}' for k_, v in sorted(sc['counts'].items())))
|
|
354
|
+
recorded = _recorded_lineage(sc['artefacts'], project)
|
|
355
|
+
graph = version_graph(sc['artefacts'], k=k, with_kmers=False, recorded=[e for e in recorded if e['parent']],
|
|
356
|
+
origins=[e['child'] for e in recorded if not e['parent']], declared_latest=latest)
|
|
357
|
+
log(f'{len(graph["versions"])} assembly version(s); {len(graph["pairs"])} pair(s) compared, '
|
|
358
|
+
f'{sum(len(p["events"]) for p in graph["pairs"])} events; latest {graph.get("latest")}')
|
|
359
|
+
attributions = attribute_all(sc, graph, log=lambda r: log(f'{r["relpath"]}: {r["attribution"]["status"]} {r["attribution"].get("best")}'))
|
|
360
|
+
full = {v['id']: v for v in graph['full_versions']}
|
|
361
|
+
curation = [] # change tracks of every lineage transition
|
|
362
|
+
steps, seen, planned = [], set(), []
|
|
363
|
+
mt = {v['id']: v.get('mtime', 0) for v in graph['full_versions']}
|
|
364
|
+
for v in graph['versions']:
|
|
365
|
+
if v.get('parent') and v.get('parent_relation') == 'sequence_change':
|
|
366
|
+
steps.append((v['parent'], v['id']))
|
|
367
|
+
elif v.get('parent') is None and v.get('lineage_basis') is None and v.get('nearest'):
|
|
368
|
+
# source unknown: the changes to the most similar version, from the earlier file to the later one;
|
|
369
|
+
# a comparison, not a claim about which came first
|
|
370
|
+
x, y = sorted((v['nearest'], v['id']), key=lambda i: (mt.get(i, 0), int(i[1:]) if i[1:].isdigit() else 0))
|
|
371
|
+
steps.append((x, y))
|
|
372
|
+
for x, y in steps:
|
|
373
|
+
if (x, y) in seen:
|
|
374
|
+
continue
|
|
375
|
+
seen.add((x, y))
|
|
376
|
+
events, _, pre, post = transition(_pair(graph, x, y), x, y)
|
|
377
|
+
if not events and not pre and not post:
|
|
378
|
+
continue
|
|
379
|
+
prefix = f'{safe_name(x)}_to_{safe_name(y)}.'
|
|
380
|
+
outputs.extend(curation_paths(out / 'curation', prefix).values())
|
|
381
|
+
planned.append((x, y, prefix, events, pre, post))
|
|
382
|
+
# Discover every dynamic output before the first export is published. In
|
|
383
|
+
# particular, resolving a curation directory symlink must not hide an input.
|
|
384
|
+
validate_output_paths(inputs, outputs)
|
|
385
|
+
# Invalidate the earlier completion marker before publishing any output.
|
|
386
|
+
# Retain an explicit incomplete record on failure so census readers cannot
|
|
387
|
+
# fall back to a mixed set of old and new legacy outputs. All destinations
|
|
388
|
+
# have passed preflight; a safety rejection leaves previous outputs intact.
|
|
389
|
+
pending = incomplete_summary(project)
|
|
390
|
+
atomic_write_text(out / SUMMARY_NAME, json.dumps(pending, indent=1, allow_nan=False) + '\n')
|
|
391
|
+
for x, y, prefix, events, pre, post in planned:
|
|
392
|
+
curation += write_curation(out / 'curation', prefix, events,
|
|
393
|
+
load(full[x]['representative']), a_path=full[x]['representative'], a_name=x, b_name=y,
|
|
394
|
+
pre=pre, post=post)
|
|
395
|
+
control = project_control(sc, graph, attributions, project, log)
|
|
396
|
+
for a in sc['artefacts']: # bulky per-read data stays in the cache, not in the report
|
|
397
|
+
a.pop('read_first_names', None)
|
|
398
|
+
if a.get('reads'):
|
|
399
|
+
a['reads'].pop('all_names', None)
|
|
400
|
+
result = {'schema': 'assemblytrace.project.v1', 'run_id': pending['run_id'],
|
|
401
|
+
'created_utc': pending['created_utc'],
|
|
402
|
+
'project': str(project), 'source': pending['source'], 'k': k, 'scan': sc,
|
|
403
|
+
'graph': {'versions': graph['versions'], 'latest': graph.get('latest'),
|
|
404
|
+
'latest_status': graph.get('latest_status'), 'latest_reason': graph.get('latest_reason'),
|
|
405
|
+
'pairs': [{kk: vv for kk, vv in p.items() if kk != 'panel'} for p in graph['pairs']]},
|
|
406
|
+
'attributions': attributions, 'control': control}
|
|
407
|
+
result['curation'] = [str(x.relative_to(out)) for x in curation]
|
|
408
|
+
result['verdict'] = verdict(result['graph'], attributions, control)
|
|
409
|
+
out.mkdir(parents=True, exist_ok=True)
|
|
410
|
+
atomic_write_text(out / 'scan.json', json.dumps(_finite(result), indent=1, ensure_ascii=False, allow_nan=False) + '\n')
|
|
411
|
+
atomic_write_text(out / 'report.html', render(result, command=command))
|
|
412
|
+
atomic_write_text(out / 'attribution.tsv', attribution_tsv(result))
|
|
413
|
+
atomic_write_text(out / 'events.tsv', events_tsv(result))
|
|
414
|
+
atomic_write_text(out / 'inventory.tsv', inventory_tsv(result))
|
|
415
|
+
atomic_write_text(out / 'claims.tsv', claims_tsv(control))
|
|
416
|
+
atomic_write_text(out / 'prov.json', json.dumps(_finite(prov_json(sc, graph, attributions)), indent=1, allow_nan=False) + '\n')
|
|
417
|
+
written = [out / n for n in OUTPUTS if n != 'assemblytrace-ro-crate-metadata.json']
|
|
418
|
+
written += curation
|
|
419
|
+
crate = ro_crate(sc, graph, attributions, name=name or project.name, project=project, license=license, outputs=written)
|
|
420
|
+
atomic_write_text(out / 'assemblytrace-ro-crate-metadata.json', json.dumps(crate, indent=1, allow_nan=False) + '\n')
|
|
421
|
+
atomic_write_text(out / 'assemblytrace.lock.json', json.dumps(lockfile(sc, graph, attributions), indent=1) + '\n')
|
|
422
|
+
completed_outputs = [out / n for n in OUTPUTS if n != SUMMARY_NAME] + curation
|
|
423
|
+
summary = compact_summary(result, out, completed_outputs)
|
|
424
|
+
atomic_write_text(out / SUMMARY_NAME, json.dumps(_finite(summary), indent=1, ensure_ascii=False, allow_nan=False) + '\n')
|
|
425
|
+
log(f'verdict {result["verdict"]["status"]}: {result["verdict"]["summary"]}')
|
|
426
|
+
return result
|
|
427
|
+
|
|
428
|
+
|
|
429
|
+
def attribution_tsv(result) -> str:
|
|
430
|
+
vids = [v['id'] for v in result['graph']['versions']]
|
|
431
|
+
s = io.StringIO(newline='')
|
|
432
|
+
w = csv.writer(s, delimiter='\t', lineterminator='\n')
|
|
433
|
+
w.writerow(['artefact', 'kind', 'best_version', 'status', 'log10_bayes_factor'] + [f'posterior_{v}' for v in vids]
|
|
434
|
+
+ ['evidence', 'content_class', 'content_class_status', 'content_class_log10_bayes_factor'])
|
|
435
|
+
for r in result['attributions']:
|
|
436
|
+
a = r['attribution']
|
|
437
|
+
best = a.get('best')
|
|
438
|
+
lbf = a.get('log10_bayes_factor')
|
|
439
|
+
content = a.get('content_class_attribution', {})
|
|
440
|
+
content_best = content.get('best')
|
|
441
|
+
content_lbf = content.get('log10_bayes_factor')
|
|
442
|
+
w.writerow([r['relpath'], r['kind'], ','.join(best) if isinstance(best, list) else (best or ''), a['status'],
|
|
443
|
+
'' if lbf is None else f'{lbf:.3f}']
|
|
444
|
+
+ [f'{a["posterior"].get(v, 0):.4f}' if a.get('posterior') else '' for v in vids]
|
|
445
|
+
+ [';'.join(f'{k}={v}' for k, v in sorted(a.get('evidence_counts', {}).items())),
|
|
446
|
+
','.join(content_best) if isinstance(content_best, list) else (content_best or ''),
|
|
447
|
+
content.get('status', ''), '' if content_lbf is None else f'{content_lbf:.3f}'])
|
|
448
|
+
return s.getvalue()
|
|
449
|
+
|
|
450
|
+
|
|
451
|
+
def events_tsv(result) -> str:
|
|
452
|
+
s = io.StringIO(newline='')
|
|
453
|
+
w = csv.writer(s, delimiter='\t', lineterminator='\n')
|
|
454
|
+
w.writerow(['from', 'to', 'contig', 'type', 'pos_from', 'pos_to', 'ref', 'alt', 'contig_to'])
|
|
455
|
+
for p in result['graph']['pairs']:
|
|
456
|
+
for e in p['events']:
|
|
457
|
+
w.writerow([p['a'], p['b'], e['contig'], e['type'], e['ref_pos'], e['alt_pos'], e['ref'], e['alt'],
|
|
458
|
+
e.get('contig_b', e['contig'])])
|
|
459
|
+
return s.getvalue()
|
|
460
|
+
|
|
461
|
+
|
|
462
|
+
def inventory_tsv(result) -> str:
|
|
463
|
+
s = io.StringIO(newline='')
|
|
464
|
+
w = csv.writer(s, delimiter='\t', lineterminator='\n')
|
|
465
|
+
w.writerow(['file', 'stage', 'kind', 'size', 'sha256', 'integrity', 'version', 'status', 'link_target'])
|
|
466
|
+
att = {}
|
|
467
|
+
for r in result['attributions']:
|
|
468
|
+
att.setdefault(r.get('file', r['relpath']), []).append(r['attribution'])
|
|
469
|
+
vfile = {f: v['id'] for v in result['graph']['versions'] for f in v['files']}
|
|
470
|
+
inh = result.get('control', {}).get('joint', {}).get('inherited', {})
|
|
471
|
+
for a in sorted(result['scan']['artefacts'], key=lambda x: (x.get('stage', ''), x['relpath'])):
|
|
472
|
+
rs = att.get(a['relpath'], [])
|
|
473
|
+
if a['relpath'] in vfile:
|
|
474
|
+
ver, st = vfile[a['relpath']], 'is_version'
|
|
475
|
+
elif a['relpath'] in inh:
|
|
476
|
+
ver, st = inh[a['relpath']]['version'], 'inherited_via_links'
|
|
477
|
+
elif rs:
|
|
478
|
+
ver = ';'.join(str(r.get('best') if not isinstance(r.get('best'), list) else ','.join(r['best'])) for r in rs)
|
|
479
|
+
st = ';'.join(r['status'] for r in rs)
|
|
480
|
+
else:
|
|
481
|
+
ver, st = '', ''
|
|
482
|
+
w.writerow([a['relpath'], a.get('stage', ''), a['kind'], a.get('size', ''), a.get('sha256') or '',
|
|
483
|
+
a.get('integrity', ''), ver, st, a.get('link_target') or ''])
|
|
484
|
+
return s.getvalue()
|
|
485
|
+
|
|
486
|
+
|
|
487
|
+
def claims_tsv(control) -> str:
|
|
488
|
+
s = io.StringIO(newline='')
|
|
489
|
+
w = csv.writer(s, delimiter='\t', lineterminator='\n')
|
|
490
|
+
w.writerow(['artefact', 'declared', 'observed', 'observed_status', 'verdict', 'recorded_at'])
|
|
491
|
+
for c in control.get('claims', []):
|
|
492
|
+
w.writerow([c['artefact'], ','.join(c['declared']), c['observed'] or '', c['observed_status'] or '', c['verdict'],
|
|
493
|
+
'; '.join(c['where'])])
|
|
494
|
+
return s.getvalue()
|