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/cli.py ADDED
@@ -0,0 +1,230 @@
1
+ """CLI for AssemblyTrace. The v0.1 positional comparison remains valid."""
2
+ import argparse
3
+ import json
4
+ from pathlib import Path
5
+ import sys
6
+ from .core import compare
7
+ from .identity import identity_mapping
8
+ from .provenance import capture_manifest,capture_run,resolve_manifest
9
+ from .release import audit_release,write_reports,discover_project,collect_release_inputs
10
+ from .annotation import audit_annotation
11
+ from .change import compare_changes,parse_cs_paf,annotate_change_impact
12
+ from .indels import normalize_variants
13
+ from .io_safety import validate_output_paths,atomic_write_text
14
+ from .variant_input import load_variants
15
+
16
+
17
+ def _json(data,path=None):
18
+ content=json.dumps(data,indent=2,ensure_ascii=False)+'\n'
19
+ if path:
20
+ atomic_write_text(Path(path),content)
21
+ else:print(content,end='')
22
+
23
+
24
+ def _report_paths(out_dir):
25
+ return [Path(out_dir)/name for name in ('audit.json','issues.tsv','report.html')]
26
+
27
+
28
+ def _preflight(args,found=None):
29
+ """Protect explicit and indirectly consumed files before computing a result."""
30
+ inputs=[]
31
+ for name in ('a','b','assembly','manifest','gff','faa','cds','quast','busco',
32
+ 'checksums','before','after','paf','variants_json','reference'):
33
+ value=getattr(args,name,None)
34
+ if value:inputs.append(Path(value))
35
+ inputs.extend(Path(value) for value in getattr(args,'artifact',[]))
36
+ inputs.extend(Path(value) for value in getattr(args,'expect',[]))
37
+ inputs.extend(Path(value) for value in (found or {}).values() if value)
38
+ outputs=([Path(args.output)] if getattr(args,'output',None) else [])
39
+ if getattr(args,'out_dir',None):outputs.extend(_report_paths(args.out_dir))
40
+ validate_output_paths(inputs,outputs)
41
+ if args.command in ('resolve','release-check','audit'):
42
+ indirect=collect_release_inputs(manifest=getattr(args,'manifest',None),
43
+ checksums=getattr(args,'checksums',None) or (found or {}).get('checksums'))
44
+ validate_output_paths(inputs+indirect,outputs)
45
+
46
+
47
+ def _with_annotation(result,gff):
48
+ annotation=annotate_change_impact(result['variants'],gff)
49
+ return {**result,'variants':annotation['variants'],
50
+ 'annotation_limitations':annotation['limitations']}
51
+
52
+
53
+ def _pair_from_files(a,b,*,k=31,with_kmers=True,ids=('a','b')):
54
+ from .scan import describe
55
+ from .versions import diff_versions
56
+ va=describe(Path(a),'assembly');vb=describe(Path(b),'assembly')
57
+ va.update(id=ids[0],representative=str(a));vb.update(id=ids[1],representative=str(b))
58
+ return diff_versions(va,vb,k=k,with_kmers=with_kmers),va,vb
59
+
60
+
61
+ def _requested_outputs(argv):
62
+ """Recover destinations for failure diagnostics, including --option=value."""
63
+ outputs=[]
64
+ for i,arg in enumerate(argv):
65
+ option,sep,value=arg.partition('=')
66
+ if option not in ('--output','--out-dir'):continue
67
+ if not sep:
68
+ if i+1>=len(argv):continue
69
+ value=argv[i+1]
70
+ outputs.extend(_report_paths(value) if option=='--out-dir' else [Path(value)])
71
+ return outputs
72
+
73
+
74
+ def _parser():
75
+ p=argparse.ArgumentParser(description='Assembly identity, provenance and release consistency auditing')
76
+ sub=p.add_subparsers(dest='command',required=True)
77
+ q=sub.add_parser('scan',help='Scan a project directory: versions, differences, attribution, PROV, RO-Crate, lockfile')
78
+ q.add_argument('project');q.add_argument('--out-dir',required=True)
79
+ q.add_argument('--k',type=int,default=31,help='k-mer size of the discriminating panels (default 31)')
80
+ q.add_argument('--threads',type=int,default=4)
81
+ q.add_argument('--full-hash',action='store_true',help='SHA-256 every file, including alignments above 512 MB')
82
+ q.add_argument('--name',help='dataset name for the RO-Crate');q.add_argument('--quiet',action='store_true')
83
+ q.add_argument('--fail-on-review',action='store_true',help='return 3 when the verdict is review')
84
+ q.add_argument('--latest',help='the release: an assembly FASTA of the project (or a version id) that the other files are checked against')
85
+ q.add_argument('--license',help='licence of the project data for the RO-Crate (a URL such as https://spdx.org/licenses/CC-BY-4.0); none is asserted otherwise')
86
+ q=sub.add_parser('verify',help='Recompute every file pinned in a lockfile and report drift')
87
+ q.add_argument('project');q.add_argument('--lock',help='lockfile (default: <project>/assemblytrace.lock.json or scan output)')
88
+ q.add_argument('--output')
89
+ q=sub.add_parser('diff',help='Alignment-free events between two near-identical assemblies')
90
+ q.add_argument('a');q.add_argument('b');q.add_argument('--output');q.add_argument('--k',type=int,default=31)
91
+ q.add_argument('--no-kmers',action='store_true',help='omit the discriminating k-mer panel')
92
+ q=sub.add_parser('lift',help='Move GFF3/GTF, BED or VCF coordinates exactly from one version to another')
93
+ q.add_argument('input');q.add_argument('--from',dest='src',required=True);q.add_argument('--to',dest='dst',required=True)
94
+ q.add_argument('--output',required=True);q.add_argument('--unmapped',help='file for records that cannot be placed')
95
+ q=sub.add_parser('seqcol',help='GA4GH refget seqcol digests of a FASTA')
96
+ q.add_argument('a');q.add_argument('--output');q.add_argument('--level',type=int,choices=(0,1,2),default=1)
97
+ q=sub.add_parser('identity',help='Compare FASTA identities and map contigs')
98
+ q.add_argument('a');q.add_argument('b');q.add_argument('--output')
99
+ q=sub.add_parser('snapshot',help='Record current hashes; NOT execution proof')
100
+ q.add_argument('--assembly',required=True);q.add_argument('--artifact',action='append',default=[]);q.add_argument('--output',required=True)
101
+ q=sub.add_parser('capture-run',help='Execute external QC command and record input/output hashes')
102
+ q.add_argument('--assembly',required=True);q.add_argument('--artifact',action='append',default=[]);q.add_argument('--output',required=True)
103
+ q.add_argument('argv',nargs=argparse.REMAINDER)
104
+ q=sub.add_parser('resolve',help='Verify file hashes against a manifest')
105
+ q.add_argument('manifest');q.add_argument('--assembly');q.add_argument('--output')
106
+ q=sub.add_parser('release-check',aliases=['audit'],help='Audit assembly and related outputs')
107
+ q.add_argument('--assembly');q.add_argument('--project-dir');q.add_argument('--gff');q.add_argument('--faa');q.add_argument('--cds')
108
+ q.add_argument('--quast');q.add_argument('--busco');q.add_argument('--manifest');q.add_argument('--checksums');q.add_argument('--expect',action='append',default=[])
109
+ q.add_argument('--out-dir',required=True);q.add_argument('--fail-on-review',action='store_true',help='Return exit status 3 when human review is required')
110
+ q=sub.add_parser('annotation',help='Check GFF3, proteins and coordinates')
111
+ q.add_argument('--assembly',required=True);q.add_argument('--gff',required=True);q.add_argument('--faa');q.add_argument('--cds');q.add_argument('--output')
112
+ q=sub.add_parser('changes',help='Conservative direct FASTA change detection')
113
+ q.add_argument('before');q.add_argument('after');q.add_argument('--gff');q.add_argument('--output')
114
+ q.add_argument('--assume-collinear',action='store_true',help='Allow direct multi-SNV calls without an alignment (potentially misleading for indels)')
115
+ q=sub.add_parser('paf-changes',help='Parse minimap2 PAF with cs tags')
116
+ q.add_argument('paf');q.add_argument('--min-mapq',type=int,default=20);q.add_argument('--before');q.add_argument('--after');q.add_argument('--gff');q.add_argument('--output')
117
+ q=sub.add_parser('normalize-indels',help='Reference-left-normalize simple indels, with explicit unresolved cases')
118
+ q.add_argument('variants_json',help='JSON variant list or VCF');q.add_argument('--reference',required=True);q.add_argument('--output')
119
+ return p
120
+
121
+
122
+ COMMANDS={'scan','verify','diff','lift','seqcol','identity','snapshot','capture-run','resolve','release-check','audit',
123
+ 'annotation','changes','paf-changes','normalize-indels'}
124
+
125
+
126
+ def main(argv=None):
127
+ argv=list(sys.argv[1:] if argv is None else argv)
128
+ if argv==['--version']:
129
+ from . import __version__
130
+ print(f'assemblytrace {__version__}')
131
+ return 0
132
+ if argv and argv[0] not in COMMANDS and argv[0] not in ('-h','--help'):
133
+ old=argparse.ArgumentParser(description='Legacy FASTA identity comparison')
134
+ old.add_argument('a');old.add_argument('b');old.add_argument('--output')
135
+ args=old.parse_args(argv)
136
+ args.command='legacy'
137
+ _preflight(args)
138
+ _json(compare(args.a,args.b),args.output);return 0
139
+ args=_parser().parse_args(argv)
140
+ if args.command=='scan':
141
+ from .project import run_project
142
+ r=run_project(args.project,args.out_dir,k=args.k,threads=args.threads,full_hash=args.full_hash,
143
+ name=args.name,quiet=args.quiet,latest=args.latest,license=args.license,
144
+ command=['assemblytrace',*argv])
145
+ print(json.dumps({'status':r['verdict']['status'],'versions':len(r['graph']['versions']),
146
+ 'artefacts':len(r['attributions']),'out_dir':args.out_dir}))
147
+ return 2 if r['verdict']['status']=='fail' else (3 if args.fail_on_review and r['verdict']['status']=='review' else 0)
148
+ if args.command=='verify':
149
+ from .prov import verify_lock
150
+ lock=Path(args.lock) if args.lock else Path(args.project)/'assemblytrace.lock.json'
151
+ if not lock.is_file():raise FileNotFoundError(f'Lockfile not found: {lock}')
152
+ lock_data=json.loads(lock.read_text(encoding='utf-8'))
153
+ if args.output:
154
+ validate_output_paths([lock]+[Path(args.project)/e['path'] for e in lock_data.get('artefacts',[])],[Path(args.output)])
155
+ r=verify_lock(args.project,lock_data)
156
+ _json(r,args.output)
157
+ return 0 if r['status']=='pass' else 2
158
+ if args.command=='diff':
159
+ if args.output:validate_output_paths([Path(args.a),Path(args.b)],[Path(args.output)])
160
+ r,_,_=_pair_from_files(args.a,args.b,k=args.k,with_kmers=not args.no_kmers)
161
+ _json(r,args.output);return 0
162
+ if args.command=='lift':
163
+ from .lift import lift_pair,kind_of
164
+ from .core import load
165
+ outs=[Path(args.output)]+([Path(args.unmapped)] if args.unmapped else [])
166
+ validate_output_paths([Path(args.input),Path(args.src),Path(args.dst)],outs)
167
+ pair,_,_=_pair_from_files(args.src,args.dst,with_kmers=False)
168
+ stats,unmapped=lift_pair(kind_of(args.input),args.input,args.output,pair,load(args.dst),reference=Path(args.dst).name)
169
+ if args.unmapped:atomic_write_text(Path(args.unmapped),''.join(unmapped))
170
+ print(json.dumps({'lifted':stats,'unmapped':len(unmapped),'events':len(pair['events'])}))
171
+ return 0
172
+ if args.command=='seqcol':
173
+ from . import seqcol as sc
174
+ obj=sc.level2(args.a)
175
+ r={'seqcol_digest':sc.level0(obj),'level1':sc.level1(obj)}
176
+ if args.level==2:r['level2']=obj
177
+ if args.level==0:r={'seqcol_digest':r['seqcol_digest']}
178
+ if args.output:validate_output_paths([Path(args.a)],[Path(args.output)])
179
+ _json(r,args.output);return 0
180
+ if args.command not in ('release-check','audit'):_preflight(args)
181
+ if args.command=='identity':_json(identity_mapping(args.a,args.b),args.output)
182
+ elif args.command=='snapshot':_json(capture_manifest(args.assembly,args.artifact,args.output))
183
+ elif args.command=='capture-run':
184
+ cmd=args.argv[1:] if args.argv and args.argv[0]=='--' else args.argv
185
+ _json(capture_run(args.assembly,cmd,args.artifact,args.output))
186
+ elif args.command=='resolve':_json(resolve_manifest(args.manifest,args.assembly),args.output)
187
+ elif args.command in ('release-check','audit'):
188
+ found=discover_project(args.project_dir,assembly=args.assembly) if args.project_dir else {}
189
+ assembly=args.assembly or found.get('assembly')
190
+ if not assembly:raise ValueError('Provide --assembly or --project-dir')
191
+ _preflight(args,found)
192
+ r=audit_release(assembly,gff=args.gff or found.get('gff'),faa=args.faa or found.get('faa'),
193
+ cds=args.cds,quast=args.quast or found.get('quast'),busco=args.busco or found.get('busco'),
194
+ manifest=args.manifest,checksums=args.checksums or found.get('checksums'),expected=args.expect)
195
+ if found:r['discovered_files']=found
196
+ write_reports(r,args.out_dir)
197
+ print(json.dumps({'status':r['status'],'out_dir':args.out_dir,'issue_counts':r['issue_counts']}))
198
+ return 2 if r['status']=='fail' else (3 if args.fail_on_review and r['status']=='review' else 0)
199
+ elif args.command=='annotation':_json(audit_annotation(args.assembly,args.gff,faa=args.faa,cds=args.cds),args.output)
200
+ elif args.command=='changes':
201
+ r=compare_changes(args.before,args.after,assume_collinear=args.assume_collinear)
202
+ if args.gff:r=_with_annotation(r,args.gff)
203
+ _json(r,args.output)
204
+ elif args.command=='paf-changes':
205
+ r=parse_cs_paf(args.paf,min_mapq=args.min_mapq,before=args.before,after=args.after)
206
+ if args.gff:r=_with_annotation(r,args.gff)
207
+ _json(r,args.output)
208
+ elif args.command=='normalize-indels':
209
+ variants=load_variants(args.variants_json)
210
+ _json(normalize_variants(variants,args.reference),args.output)
211
+ return 0
212
+
213
+ def cli_entry(argv=None):
214
+ """User-facing entry point: report input failures without Python tracebacks."""
215
+ argv=list(sys.argv[1:] if argv is None else argv)
216
+ previous=[]
217
+ try:
218
+ previous=[p for p in _requested_outputs(argv) if p.is_file()]
219
+ return main(argv)
220
+ except (OSError, EOFError, ValueError, RuntimeError, UnicodeError, KeyError) as exc:
221
+ print(f'assemblytrace: {type(exc).__name__}: {exc}', file=sys.stderr)
222
+ for path in previous:
223
+ print('assemblytrace: Destination already exists and may contain a previous '
224
+ f'or incomplete result: {path}; do not treat it as the result of this failed invocation.',
225
+ file=sys.stderr)
226
+ return 2
227
+
228
+
229
+ if __name__=='__main__':
230
+ raise SystemExit(cli_entry())
assemblytrace/core.py ADDED
@@ -0,0 +1,100 @@
1
+ """Deterministic assembly identity, with multiplicity and strand invariance."""
2
+ from collections import Counter
3
+ from pathlib import Path
4
+ import gzip
5
+ import hashlib
6
+
7
+ _TRANS = str.maketrans('ACGTRYMKBDHVN', 'TGCAYRKMVHDBN')
8
+ _ALLOWED = set('ACGTURYSWKMBDHVN') # the IUPAC nucleotide codes
9
+
10
+ def _open(path):
11
+ path = Path(path)
12
+ with path.open('rb') as fh: # gzip and BGZF by content, whatever the extension
13
+ compressed = fh.read(2) == b'\x1f\x8b'
14
+ return gzip.open(path, 'rt', encoding='utf-8') if compressed else path.open('r', encoding='utf-8')
15
+
16
+ def _contigs(path):
17
+ header = None
18
+ seq = []
19
+ with _open(path) as handle:
20
+ for lineno, line in enumerate(handle, 1):
21
+ line = line.strip()
22
+ if not line:
23
+ continue
24
+ if line.startswith('>'):
25
+ if header is not None:
26
+ if not seq:
27
+ raise ValueError(f'Empty FASTA record: {header}')
28
+ yield header, ''.join(seq)
29
+ header = line[1:].strip()
30
+ if not header:
31
+ raise ValueError(f'Empty FASTA header at line {lineno}')
32
+ seq = []
33
+ else:
34
+ if header is None:
35
+ raise ValueError(f'Sequence before FASTA header at line {lineno}')
36
+ value = line.upper()
37
+ if not set(value) <= _ALLOWED:
38
+ raise ValueError(f'Invalid DNA character at line {lineno}')
39
+ seq.append(value)
40
+ if header is not None:
41
+ if not seq:
42
+ raise ValueError(f'Empty FASTA record: {header}')
43
+ yield header, ''.join(seq)
44
+
45
+ def _fingerprint(path):
46
+ counts = Counter()
47
+ lengths = []
48
+ names = []
49
+ for name, seq in _contigs(path):
50
+ rev = seq.translate(_TRANS)[::-1]
51
+ canonical = min(seq, rev)
52
+ counts[hashlib.sha256(canonical.encode('ascii')).hexdigest()] += 1
53
+ lengths.append(len(seq))
54
+ names.append(name)
55
+ if not lengths:
56
+ raise ValueError('No FASTA records')
57
+ digest = hashlib.sha256()
58
+ for key, count in sorted(counts.items()):
59
+ digest.update(f'{key}:{count}\n'.encode())
60
+ return {'fingerprint': digest.hexdigest(), 'contigs': len(lengths), 'total_bp': sum(lengths), 'names': names, 'lengths': lengths}
61
+
62
+ def _sha256(path):
63
+ digest = hashlib.sha256()
64
+ with Path(path).open('rb') as fh:
65
+ for chunk in iter(lambda: fh.read(1024 * 1024), b''):
66
+ digest.update(chunk)
67
+ return digest.hexdigest()
68
+
69
+ def compare(path_a, path_b):
70
+ a = _fingerprint(path_a)
71
+ b = _fingerprint(path_b)
72
+ sha_a = _sha256(path_a)
73
+ sha_b = _sha256(path_b)
74
+ return {
75
+ 'file_a': str(path_a), 'file_b': str(path_b),
76
+ 'sha256_a': sha_a, 'sha256_b': sha_b,
77
+ 'byte_identical': sha_a == sha_b,
78
+ 'sequence_equivalent': a['fingerprint'] == b['fingerprint'],
79
+ 'fingerprint_a': a['fingerprint'], 'fingerprint_b': b['fingerprint'],
80
+ 'contigs_a': a['contigs'], 'contigs_b': b['contigs'],
81
+ 'total_bp_a': a['total_bp'], 'total_bp_b': b['total_bp'],
82
+ 'names_identical_in_order': a['names'] == b['names'],
83
+ 'limitations': 'Sequence equivalence treats each linear DNA contig as interchangeable with its reverse complement, disregards record names/order, preserves multiplicity; it does not prove biological identity, circular rotation equivalence, or QC report provenance.'
84
+ }
85
+
86
+
87
+ def load(path) -> dict:
88
+ """FASTA indexed by unique first-word IDs for coordinate-based operations.
89
+
90
+ Sequence identity functions deliberately retain records as a multiset;
91
+ a coordinate lookup instead requires an unambiguous name for each record.
92
+ """
93
+ result = {}
94
+ for header, sequence in _contigs(path):
95
+ name = header.split()[0]
96
+ if name in result:
97
+ raise ValueError(f'Duplicate FASTA sequence identifier {name!r} in {path}; '
98
+ 'coordinate operations require unique identifiers')
99
+ result[name] = sequence.upper()
100
+ return result
@@ -0,0 +1,155 @@
1
+ """Change tracks of a transition: a VCF of the changes and BED tracks in both versions' coordinates.
2
+
3
+ ``changes.vcf`` holds every change from A to B in A's coordinates (REF is A's
4
+ allele, ALT is B's); applied to A with ``bcftools consensus`` it gives B.
5
+ Indels carry the base before them (the base after at a contig start), as VCF
6
+ requires; changes whose padded records would overlap are written as one record
7
+ so that consensus tools apply them together. The BED tracks mark every change
8
+ in A's and in B's coordinates.
9
+ """
10
+ from __future__ import annotations
11
+
12
+ import re
13
+ from datetime import date
14
+ from pathlib import Path
15
+
16
+ from . import __version__
17
+
18
+ def safe_name(x) -> str:
19
+ return re.sub(r'[^A-Za-z0-9._-]+', '_', str(x)).strip('_') or 'version'
20
+
21
+
22
+ def _edit(e):
23
+ """0-based half-open span of A replaced by B's allele (empty span for an insertion)."""
24
+ if e['type'] == 'INS':
25
+ return e['ref_pos'], e['ref_pos'], e['alt']
26
+ s = e['ref_pos'] - 1
27
+ return s, s + len(e['ref']), e['alt']
28
+
29
+
30
+ def records(events, seqs, chosen=None):
31
+ """VCF records (contig, pos, ref, alt, event indices) for the events, padded and merged where they overlap."""
32
+ chosen = range(len(events)) if chosen is None else chosen
33
+ by = {}
34
+ for i in chosen:
35
+ e = events[i]
36
+ s, t, repl = _edit(e)
37
+ seq = seqs[e['contig']]
38
+ if seq[s:t] != e['ref'].upper():
39
+ raise ValueError(f'change {i} does not match {e["contig"]}:{s + 1}')
40
+ if s == t or not repl: # an indel takes the base before it, or after at a contig start
41
+ ws, we = (s - 1, t) if s > 0 else (s, t + 1)
42
+ else:
43
+ ws, we = s, t
44
+ by.setdefault(e['contig'], []).append([ws, we, [(s, t, repl, i)]])
45
+ out = []
46
+ for contig in seqs:
47
+ rows = sorted(by.get(contig, ()), key=lambda r: (r[0], r[1]))
48
+ merged = []
49
+ for r in rows:
50
+ if merged and r[0] < merged[-1][1]:
51
+ merged[-1][1] = max(merged[-1][1], r[1]); merged[-1][2].extend(r[2])
52
+ else:
53
+ merged.append(r)
54
+ seq = seqs[contig]
55
+ for ws, we, edits in merged:
56
+ ref = seq[ws:we]
57
+ alt = ref
58
+ for s, t, repl, _ in sorted(edits, key=lambda x: (x[0], x[1]), reverse=True):
59
+ alt = alt[:s - ws] + repl + alt[t - ws:]
60
+ if not alt: # a whole window deleted: keep the next base
61
+ ref, alt = seq[ws:we + 1], seq[we:we + 1]
62
+ out.append((contig, ws + 1, ref, alt, sorted(x[3] for x in edits)))
63
+ return out
64
+
65
+
66
+ def _header(seqs, reference, a_name, b_name):
67
+ h = ['##fileformat=VCFv4.2', f'##fileDate={date.today():%Y%m%d}', f'##source=AssemblyTrace {__version__}',
68
+ f'##reference={reference}', f'##AssemblyTrace_transition=<From="{a_name}",To="{b_name}",Records="changes">']
69
+ h += [f'##contig=<ID={c},length={len(s)}>' for c, s in seqs.items()]
70
+ h += ['##INFO=<ID=AT_EVENT,Number=.,Type=Integer,Description="Index of the change in the transition (0-based)">',
71
+ '##INFO=<ID=AT_TYPE,Number=.,Type=String,Description="Change type: SNV, INS, DEL or COMPLEX">',
72
+ '##INFO=<ID=AT_POS_OTHER,Number=.,Type=Integer,Description="Position of the change in the other version '
73
+ '(AssemblyTrace convention: an insertion follows this base, a deletion follows this base)">',
74
+ '#CHROM\tPOS\tID\tREF\tALT\tQUAL\tFILTER\tINFO']
75
+ return h
76
+
77
+
78
+ def changes_vcf(events, A, *, reference='', a_name='A', b_name='B') -> str:
79
+ """Every change from A to B in A's coordinates."""
80
+ lines = _header(A, reference, a_name, b_name)
81
+ for contig, pos, ref, alt, members in records(events, A):
82
+ info = (f'AT_EVENT={",".join(map(str, members))};AT_TYPE={",".join(events[i]["type"] for i in members)};'
83
+ f'AT_POS_OTHER={",".join(str(events[i]["alt_pos"]) for i in members)}')
84
+ lines.append(f'{contig}\t{pos}\t.\t{ref}\t{alt}\t.\t.\t{info}')
85
+ return '\n'.join(lines) + '\n'
86
+
87
+
88
+ def _span(e, side):
89
+ """0-based BED span of a change in A ('a') or B ('b'); a pure insertion point shows its anchor base."""
90
+ if side == 'a':
91
+ pos, allele, empty = e['ref_pos'], e['ref'], e['type'] == 'INS'
92
+ else:
93
+ pos, allele, empty = e['alt_pos'], e['alt'], e['type'] == 'DEL'
94
+ if empty:
95
+ return max(0, pos - 1), max(1, pos)
96
+ return pos - 1, pos - 1 + len(allele)
97
+
98
+
99
+ def changes_bed(events, *, side='a', name='changes', frames=None) -> str:
100
+ """Changes as a BED track on one side; with ``frames`` (that side's), frame spans are mapped to its contigs."""
101
+ lines = [f'track name="{name}" description="AssemblyTrace changes"']
102
+ rows = []
103
+ for i, e in enumerate(events):
104
+ start, end = _span(e, side)
105
+ contig = e['contig'] if side == 'a' else e.get('contig_b', e['contig'])
106
+ if frames is not None and contig in frames.by_f:
107
+ rows += [(c, s - 1, t, f'{i}:{e["type"]}') for c, s, t in frames.pieces(contig, start + 1, end)]
108
+ else:
109
+ rows.append((contig, start, end, f'{i}:{e["type"]}'))
110
+ order = {}
111
+ for r in rows:
112
+ order.setdefault(r[0], len(order))
113
+ for c, start, end, nm in sorted(rows, key=lambda r: (order[r[0]], r[1], r[2])):
114
+ lines.append(f'{c}\t{start}\t{end}\t{nm}')
115
+ return '\n'.join(lines) + '\n'
116
+
117
+
118
+ def curation_paths(out_dir, prefix):
119
+ """All files of a transition, shared by preflight and the writer."""
120
+ return {k: Path(out_dir) / f'{prefix}{k}' for k in ('changes.vcf', 'a.bed', 'b.bed')}
121
+
122
+
123
+ def write_curation(out_dir, prefix, events, A, *, a_path, a_name='A', b_name='B', pre=None, post=None):
124
+ """Write the changes VCF and BED tracks of one transition; returns the paths written.
125
+
126
+ Changes in a frame (a turned, merged or split contig, see ``segments``) are written on the frame,
127
+ whose blocks are stated in the VCF header: ``pre`` holds the frames of the source, ``post`` those of
128
+ the target. The BED tracks give every change in each version's own contigs.
129
+ """
130
+ from .io_safety import atomic_write_text, validate_output_paths
131
+ from .segments import Frames, frame_seq
132
+ p = curation_paths(out_dir, prefix)
133
+ validate_output_paths([Path(a_path)], list(p.values()))
134
+ pre = pre if isinstance(pre, Frames) else Frames(pre)
135
+ post = post if isinstance(post, Frames) else Frames(post)
136
+ seqs = {c: s for c, s in A.items() if c not in pre.by_a}
137
+ for fid, fr in pre.frames.items():
138
+ seqs[fid] = frame_seq(fr, A)
139
+ text = changes_vcf(events, seqs, reference=Path(a_path).resolve().as_uri(), a_name=a_name, b_name=b_name)
140
+ desc = lambda fr: ','.join(f'{c}:{s}-{e}:{st}' for c, s, e, st in fr['blocks']) + \
141
+ (f'",Shared="{",".join(map(str, fr["shared"]))}' if fr.get('shared') else '')
142
+ notes = [f'##AssemblyTrace_frame=<ID={fid},Side="source",Target={fr["contig_b"]},Blocks="{desc(fr)}",'
143
+ f'Description="records on this ID are on these blocks of the source (contig:start-end:strand) joined in '
144
+ f'this order, each reverse complemented when its strand is -, the first Shared bases of a block written once with '
145
+ f'the block before>' for fid, fr in sorted(pre.frames.items())]
146
+ notes += [f'##AssemblyTrace_frame=<ID={fid},Side="target",Source={fr["contig_b"]},Blocks="{desc(fr)}",'
147
+ f'Description="the records turn the source contig into these blocks of the target (contig:start-end:strand) '
148
+ f'joined in this order">' for fid, fr in sorted(post.frames.items())]
149
+ if notes:
150
+ head, _, rest = text.partition('#CHROM')
151
+ text = head + '\n'.join(notes) + '\n#CHROM' + rest
152
+ atomic_write_text(p['changes.vcf'], text)
153
+ atomic_write_text(p['a.bed'], changes_bed(events, side='a', name=f'{a_name} to {b_name} on {a_name}', frames=pre))
154
+ atomic_write_text(p['b.bed'], changes_bed(events, side='b', name=f'{a_name} to {b_name} on {b_name}', frames=post))
155
+ return list(p.values())