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,74 @@
1
+ """Sequence-aware, multiplicity-preserving contig identity and mapping.
2
+
3
+ A unique sequence match is not necessarily a unique FASTA identifier match.
4
+ """
5
+
6
+ from collections import Counter, defaultdict
7
+ import hashlib
8
+
9
+ from .core import _contigs, _TRANS, compare
10
+
11
+
12
+ def _orientation(seq, rc):
13
+ if seq == rc:
14
+ return 'palindromic'
15
+ return 'canonical' if seq < rc else 'reverse_of_canonical'
16
+
17
+
18
+ def _relative_orientation(first, second):
19
+ if first == 'palindromic' or second == 'palindromic':
20
+ return 'palindromic_ambiguous'
21
+ return 'forward' if first == second else 'reverse'
22
+
23
+
24
+ def identity_mapping(a, b):
25
+ """Map exact canonical sequence groups; never force a repeated-contig pairing."""
26
+ result = compare(a, b)
27
+ groups = [defaultdict(list), defaultdict(list)]
28
+ identifier_counts = [Counter(), Counter()]
29
+
30
+ for side, path in enumerate((a, b)):
31
+ for header, seq in _contigs(path):
32
+ identifier_counts[side][header.split()[0]] += 1
33
+ rc = seq.translate(_TRANS)[::-1]
34
+ key = hashlib.sha256(min(seq, rc).encode('ascii')).hexdigest()
35
+ groups[side][key].append((header, len(seq), _orientation(seq, rc)))
36
+
37
+ dup_a = {name for name, count in identifier_counts[0].items() if count > 1}
38
+ dup_b = {name for name, count in identifier_counts[1].items() if count > 1}
39
+ result['duplicate_identifiers_a'] = sorted(dup_a)
40
+ result['duplicate_identifiers_b'] = sorted(dup_b)
41
+ result['groups'] = []
42
+ sequence_mappings = []
43
+ safe_mappings = []
44
+
45
+ for key in sorted(set(groups[0]) | set(groups[1])):
46
+ aa, bb = groups[0][key], groups[1][key]
47
+ result['groups'].append({
48
+ 'sequence_sha256': key,
49
+ 'length_bp': (aa or bb)[0][1],
50
+ 'names_a': [record[0] for record in aa],
51
+ 'names_b': [record[0] for record in bb],
52
+ 'count_a': len(aa),
53
+ 'count_b': len(bb),
54
+ 'ambiguous': len(aa) > 1 or len(bb) > 1,
55
+ 'status': 'matched' if len(aa) == len(bb) else 'multiplicity_mismatch',
56
+ })
57
+ if len(aa) != 1 or len(bb) != 1:
58
+ continue
59
+ mapping = {
60
+ 'name_a': aa[0][0],
61
+ 'name_b': bb[0][0],
62
+ 'length_bp': aa[0][1],
63
+ 'orientation': _relative_orientation(aa[0][2], bb[0][2]),
64
+ }
65
+ sequence_mappings.append(mapping)
66
+ if aa[0][0].split()[0] not in dup_a and bb[0][0].split()[0] not in dup_b:
67
+ safe_mappings.append(mapping)
68
+
69
+ result['sequence_level_one_to_one'] = sequence_mappings
70
+ result['unique_one_to_one_mappings'] = safe_mappings
71
+ result['limitations'] += (' Duplicate FASTA identifiers invalidate ID-based crosswalks; '
72
+ 'sequence-level matches remain available but are not assigned '
73
+ 'unique identifier mappings.')
74
+ return result
@@ -0,0 +1,95 @@
1
+ """Reference-anchored equivalence classes for simple indels in tandem repeats.
2
+
3
+ Coordinates follow AssemblyTrace: INS ref_pos is the number of reference bases
4
+ preceding the insertion (0 allowed); DEL ref_pos is a 1-based deleted start.
5
+ Normalisation establishes sequence equivalence, not biological truth.
6
+ """
7
+
8
+ DNA = frozenset('ACGTN')
9
+
10
+
11
+ def canonical_indel(variant, reference, *, max_shift=4096):
12
+ """Return leftmost equivalent indel, its positional span, or a reason.
13
+
14
+ The reference is a single contig, not a FASTA path. Repeated shifts rotate
15
+ the allele to preserve the actual alternate haplotype. Fail closed if the
16
+ repeat extends beyond the configured finite normalization window.
17
+ """
18
+ kind = variant.get('type')
19
+ if kind not in ('INS', 'DEL'):
20
+ raise ValueError('canonical_indel supports INS and DEL only')
21
+ refseq = reference.upper()
22
+ pos = variant.get('ref_pos')
23
+ allele = str(variant.get('alt' if kind == 'INS' else 'ref', '')).upper()
24
+ if not isinstance(pos, int) or not allele or set(allele) - DNA:
25
+ return {'status': 'invalid_allele_or_position'}
26
+ if kind == 'INS':
27
+ if not 0 <= pos <= len(refseq) or variant.get('ref', ''):
28
+ return {'status': 'reference_mismatch'}
29
+ else:
30
+ if pos < 1 or pos - 1 + len(allele) > len(refseq) or refseq[pos-1:pos-1+len(allele)] != allele or variant.get('alt', ''):
31
+ return {'status': 'reference_mismatch'}
32
+ left, seq = pos, allele
33
+ shifts = 0
34
+ while (left > (0 if kind == 'INS' else 1)
35
+ and refseq[left-1 if kind == 'INS' else left-2] == seq[-1]):
36
+ if shifts >= max_shift:
37
+ return {'status': 'repeat_span_exceeds_limit', 'max_shift': max_shift}
38
+ left -= 1
39
+ seq = seq[-1] + seq[:-1]
40
+ shifts += 1
41
+ right, rotated = left, seq
42
+ while True:
43
+ next_base = right if kind == 'INS' else right - 1 + len(rotated)
44
+ if next_base >= len(refseq) or refseq[next_base] != rotated[0]:
45
+ break
46
+ if right - left >= max_shift:
47
+ return {'status': 'repeat_span_exceeds_limit', 'max_shift': max_shift}
48
+ right += 1
49
+ rotated = rotated[1:] + rotated[0]
50
+ return {'status': 'normalized', 'type': kind, 'ref_pos': left,
51
+ 'ref': seq if kind == 'DEL' else '',
52
+ 'alt': seq if kind == 'INS' else '',
53
+ 'equivalent_start': left, 'equivalent_end': right,
54
+ 'repeat_ambiguous': left != right,
55
+ 'coordinate_convention': 'INS after base; DEL first deleted base (1-based)'}
56
+
57
+
58
+ def normalized_key(variant, reference):
59
+ c = canonical_indel(variant, reference)
60
+ if c['status'] != 'normalized':
61
+ return None
62
+ return (c['type'], c['ref_pos'], c['ref'], c['alt'])
63
+
64
+
65
+ def normalize_variants(variants, reference):
66
+ """Normalize indels in a JSON-compatible variant collection.
67
+
68
+ This is a representation normalization, NOT a variant caller and not
69
+ independent proof of a change. Unsupported or ambiguous cases are retained
70
+ as explicit unresolved records rather than silently discarded.
71
+ """
72
+ from .core import _contigs
73
+ targets={v.get('contig') for v in variants if v.get('type') in ('INS','DEL')}
74
+ sequences={}
75
+ for header,seq in _contigs(reference):
76
+ name=header.split()[0]
77
+ if name in targets:
78
+ if name in sequences:raise ValueError(f'Duplicate reference contig: {name}')
79
+ sequences[name]=seq.upper()
80
+ normalized=[];unresolved=[]
81
+ for i,v in enumerate(variants):
82
+ if v.get('type') not in ('INS','DEL'):
83
+ normalized.append({**v,'normalization':'not_applicable'});continue
84
+ if v.get('contig') not in sequences:
85
+ unresolved.append({'index':i,'reason':'reference_contig_missing','variant':v});continue
86
+ result=canonical_indel(v,sequences[v['contig']])
87
+ if result['status']!='normalized':
88
+ unresolved.append({'index':i,'reason':result['status'],'variant':v});continue
89
+ normalized.append({**v,'original_ref_pos':v['ref_pos'],
90
+ 'original_ref':v.get('ref',''),'original_alt':v.get('alt',''),
91
+ **result,'normalization':'reference_left_normalized'})
92
+ return {'variants':normalized,'unresolved':unresolved,
93
+ 'reference':str(reference),'limitations':
94
+ 'Normalization identifies equivalent local indel haplotypes within 4096 shifts; '
95
+ 'it does not establish that a variant is biologically real.'}
@@ -0,0 +1,379 @@
1
+ """Inventory of a project: integrity of every file, sidecars and indexes, duplicates, stages.
2
+
3
+ Checks that need no version knowledge (empty and truncated files, BGZF end
4
+ markers, MD5 sidecars and checksum lists, duplicates, broken links) and the
5
+ checks that do: whether a reference index (.fai, .dict, BWA, minimap2, STAR)
6
+ still describes the FASTA it sits beside, and which stages of the analysis
7
+ exist for the latest assembly version.
8
+ """
9
+ from __future__ import annotations
10
+
11
+ import hashlib
12
+ import re
13
+ from collections import defaultdict
14
+ from pathlib import Path
15
+
16
+ from .formats import STAGES, STAGE_OF, VERSION_BOUND, is_bgzf, bgzf_eof_ok
17
+
18
+ BGZF_KINDS = {'bam', 'bcf', 'vcf', 'gff', 'bed', 'fastq', 'paf', 'pairs', 'bedgraph', 'assembly'}
19
+ REF_INDEX = {'fai', 'dict', 'bwa_index', 'mmi', 'star_index'}
20
+ FASTA_EXT = ('.fa', '.fasta', '.fna', '.fas', '.fa.gz', '.fasta.gz', '.fna.gz')
21
+ DATA_STAGES = [s for s in STAGES if s not in ('workflow', 'environment', 'metadata', 'checksums', 'other',
22
+ 'raw_reads', 'run_metadata', 'read_qc', 'assembly', 'assembly_graph')]
23
+
24
+
25
+ def _md5(path):
26
+ h = hashlib.md5()
27
+ with open(path, 'rb') as fh:
28
+ for chunk in iter(lambda: fh.read(1 << 20), b''):
29
+ h.update(chunk)
30
+ return h.hexdigest()
31
+
32
+
33
+ def integrity(artefacts, project: Path, broken_links=(), cache=None):
34
+ issues = []
35
+ for a in artefacts:
36
+ p = Path(a['path'])
37
+ st = a.get('integrity')
38
+ invalid = bool(st and st != 'ok')
39
+ if a.get('size', 0) == 0: # an empty log or marker file is normal; an empty data file is not
40
+ sev = 'error' if invalid or a['kind'] in VERSION_BOUND or a['kind'] in ('assembly', 'fastq', 'reads_fasta', 'ubam') else 'info'
41
+ issues.append({'file': a['relpath'], 'code': 'EMPTY_FILE', 'severity': sev})
42
+ continue
43
+ if invalid:
44
+ issues.append({'file': a['relpath'], 'code': 'TRUNCATED' if st.startswith('truncated') else 'INVALID',
45
+ 'severity': 'error', 'detail': st})
46
+ if a['kind'] in BGZF_KINDS and str(p).endswith(('.gz', '.bgz', '.bam', '.bcf')) and is_bgzf(p) and not bgzf_eof_ok(p):
47
+ issues.append({'file': a['relpath'], 'code': 'BGZF_EOF_MISSING', 'severity': 'error',
48
+ 'detail': 'no BGZF end-of-file block: the file is probably truncated'})
49
+ by_rel = {a['relpath']: a for a in artefacts}
50
+ for a in artefacts:
51
+ if a['kind'] == 'hts_index':
52
+ cands = [Path(a['sidecar_of'])] if a.get('sidecar_of') else []
53
+ if a['path'].endswith('.bai'):
54
+ cands.append(Path(a['path'][:-4] + '.bam'))
55
+ dp = next((c for c in cands if c.exists()), None)
56
+ if dp is None:
57
+ issues.append({'file': a['relpath'], 'code': 'ORPHAN_INDEX', 'severity': 'warning',
58
+ 'detail': 'index without its data file'})
59
+ elif Path(a['path']).stat().st_mtime + 1 < dp.stat().st_mtime:
60
+ issues.append({'file': a['relpath'], 'code': 'STALE_INDEX', 'severity': 'error',
61
+ 'detail': f'older than {dp.name}: the data file was rewritten after indexing'})
62
+ for kind in ('bam', 'cram', 'vcf', 'bcf'):
63
+ for a in artefacts:
64
+ if a['kind'] != kind:
65
+ continue
66
+ p = a['path']
67
+ if kind == 'vcf' and not p.endswith('.gz'):
68
+ continue
69
+ cands = {'bam': ('.bai', '.csi'), 'cram': ('.crai',), 'vcf': ('.tbi', '.csi'), 'bcf': ('.csi',)}[kind]
70
+ if not any(Path(p + s).exists() for s in cands) and not (kind == 'bam' and Path(p[:-4] + '.bai').exists()):
71
+ issues.append({'file': a['relpath'], 'code': 'NOT_INDEXED', 'severity': 'info',
72
+ 'detail': 'no index beside the file; region access and targeted reading are unavailable'})
73
+ for a in artefacts:
74
+ if a['kind'] != 'checksums':
75
+ continue
76
+ p = Path(a['path'])
77
+ if p.suffix.lower() == '.md5' and not p.name.lower().startswith(('md5sum', 'checksum')):
78
+ target = Path(str(p)[:-4])
79
+ if target.exists():
80
+ want = re.findall(r'\b[0-9a-fA-F]{32}\b', p.read_text(errors='replace'))
81
+ got = None
82
+ if cache is not None: # large targets are hashed once, not on every scan
83
+ from .scan import quick_key
84
+ key = 'md5-' + quick_key(target)
85
+ got = (cache.get(key) or {}).get('md5')
86
+ if got is None:
87
+ got = _md5(target)
88
+ if cache is not None:
89
+ cache.put(key, {'md5': got})
90
+ if want and want[0].lower() != got:
91
+ issues.append({'file': str(target.relative_to(project)).replace('\\', '/'), 'code': 'MD5_MISMATCH',
92
+ 'severity': 'error', 'detail': f'{p.name} says {want[0]}, file has {got}'})
93
+ else:
94
+ try:
95
+ from .release import verify_checksums
96
+ r = verify_checksums(p)
97
+ for e in r['entries']:
98
+ if e['status'] != 'verified':
99
+ issues.append({'file': e['file'], 'code': 'CHECKSUM_' + e['status'].upper(), 'severity': 'error',
100
+ 'detail': f'listed in {a["relpath"]}'})
101
+ except (ValueError, OSError) as exc:
102
+ issues.append({'file': a['relpath'], 'code': 'CHECKSUM_LIST_INVALID', 'severity': 'warning', 'detail': str(exc)})
103
+ groups = defaultdict(list)
104
+ for a in artefacts:
105
+ if a.get('sha256') and a.get('size', 0) > 0:
106
+ groups[a['sha256']].append(a['relpath'])
107
+ duplicates = [sorted(g) for g in groups.values() if len(g) > 1]
108
+ for g in duplicates:
109
+ issues.append({'file': g[0], 'code': 'DUPLICATE_CONTENT', 'severity': 'info',
110
+ 'detail': 'identical content: ' + ', '.join(g)})
111
+ for b in broken_links:
112
+ issues.append({'file': b, 'code': 'BROKEN_LINK', 'severity': 'error', 'detail': 'symbolic link to a missing file'})
113
+ return issues, duplicates
114
+
115
+
116
+ def _fasta_beside(index_path: str, files_by_path):
117
+ p = index_path
118
+ for suffix in ('.fai', '.mmi', '.ann', '.dict'):
119
+ if p.endswith(suffix):
120
+ base = p[:-len(suffix)]
121
+ cands = [base] + [base + e for e in FASTA_EXT]
122
+ if suffix == '.dict':
123
+ stem = re.sub(r'\.(fa|fasta|fna)(\.gz)?$', '', base)
124
+ cands += [stem + e for e in FASTA_EXT]
125
+ for c in cands:
126
+ if c in files_by_path:
127
+ return files_by_path[c]
128
+ if Path(p).name.lower() == 'chrnamelength.txt':
129
+ return None
130
+ return None
131
+
132
+
133
+ def fasta_layout(path):
134
+ """samtools faidx rows (name, length, offset, linebases, linewidth) of a FASTA, in its uncompressed stream."""
135
+ import gzip
136
+ with open(path, 'rb') as fh:
137
+ gz = fh.read(2) == b'\x1f\x8b'
138
+ rows, cur = [], None
139
+ off = 0
140
+ with (gzip.open(path, 'rb') if gz else open(path, 'rb')) as fh:
141
+ for line in fh:
142
+ n = len(line)
143
+ if line.startswith(b'>'):
144
+ if cur:
145
+ rows.append(cur)
146
+ cur = [line[1:].split()[0].decode('utf-8', 'replace') if line[1:].split() else '', 0, off + n, None, None]
147
+ elif cur is not None:
148
+ body = line.rstrip(b'\r\n')
149
+ if cur[3] is None and body:
150
+ cur[3], cur[4] = len(body), n
151
+ cur[1] += len(body)
152
+ off += n
153
+ if cur:
154
+ rows.append(cur)
155
+ return {r[0]: (r[1], r[2], r[3] or 0, r[4] or 0) for r in rows}
156
+
157
+
158
+ def _read_fai(path):
159
+ out = {}
160
+ for line in open(path, encoding='utf-8', errors='replace'):
161
+ f = line.rstrip('\n').split('\t')
162
+ if len(f) >= 5 and all(x.isdigit() for x in f[1:5]):
163
+ out[f[0]] = tuple(int(x) for x in f[1:5])
164
+ return out
165
+
166
+
167
+ def _bwa_bases(base, names_offsets, sites):
168
+ """Bases of a BWA .pac at (contig, 1-based position) sites, 2 bits per base as in bwa's _get_pac."""
169
+ pac = Path(base + '.pac')
170
+ if not pac.exists():
171
+ return None
172
+ out = {}
173
+ with open(pac, 'rb') as fh:
174
+ for c, p in sites:
175
+ if c not in names_offsets:
176
+ continue
177
+ i = names_offsets[c] + p - 1
178
+ fh.seek(i >> 2)
179
+ b = fh.read(1)
180
+ if not b:
181
+ return None
182
+ out[(c, p)] = 'ACGT'[(b[0] >> ((~i & 3) << 1)) & 3]
183
+ return out
184
+
185
+
186
+ def _mmi_bases(path, sites):
187
+ """Bases of a minimap2 index at sites, from the 4-bit sequence block of each part (mm_idx_dump layout).
188
+
189
+ A part is: magic, (w, k, b, n_seq, flag), names and lengths, 2^b hash buckets
190
+ (n, n positions, size, size key-value pairs), then the packed sequence unless
191
+ the index was built with --idx-no-seq. Indexes of large genomes hold several
192
+ parts one after another; each is parsed in turn.
193
+ """
194
+ import struct
195
+ size = Path(path).stat().st_size
196
+ out = {}
197
+ want = defaultdict(list)
198
+ for c, p in sites:
199
+ want[c].append(p)
200
+ with open(path, 'rb') as fh:
201
+ if fh.read(4) != b'MMI\x02':
202
+ return None
203
+ fh.seek(0)
204
+ while fh.tell() < size:
205
+ if fh.read(4) != b'MMI\x02':
206
+ return None if not out else out
207
+ w, k, b, n_seq, flag = struct.unpack('<5I', fh.read(20))
208
+ offs, total = {}, 0
209
+ for _ in range(n_seq):
210
+ l = fh.read(1)[0]
211
+ name = fh.read(l).decode('utf-8', 'replace') if l else ''
212
+ length = struct.unpack('<I', fh.read(4))[0]
213
+ offs[name] = total; total += length
214
+ for _ in range(1 << b):
215
+ n = struct.unpack('<I', fh.read(4))[0]
216
+ fh.seek(8 * n, 1)
217
+ hsize = struct.unpack('<I', fh.read(4))[0]
218
+ fh.seek(16 * hsize, 1)
219
+ if flag & 2: # MM_I_NO_SEQ: built with --idx-no-seq
220
+ return None
221
+ start = fh.tell()
222
+ end = start + 4 * ((total + 7) // 8)
223
+ if end > size:
224
+ return None
225
+ for c, ps in want.items():
226
+ if c not in offs:
227
+ continue
228
+ for p in ps:
229
+ i = offs[c] + p - 1
230
+ fh.seek(start + 4 * (i >> 3))
231
+ word = struct.unpack('<I', fh.read(4))[0]
232
+ v = (word >> ((i & 7) << 2)) & 0xf
233
+ out[(c, p)] = 'ACGTN'[v] if v < 5 else 'N'
234
+ fh.seek(end)
235
+ return out
236
+
237
+
238
+ def _check_sites(graph, vid, limit=500):
239
+ """Substitution sites, in the coordinates of ``vid``, where it differs from another version."""
240
+ from .segments import Frames
241
+ sites = []
242
+ for p in graph.get('pairs', []):
243
+ if p['a'] == vid:
244
+ fr = Frames(p.get('frames'))
245
+ for e in p['events']:
246
+ if e['type'] == 'SNV':
247
+ back = fr.outof(e['contig'], e['ref_pos'], e['ref_pos'])
248
+ if back:
249
+ sites.append((back[0], back[1]))
250
+ elif p['b'] == vid:
251
+ sites += [(e.get('contig_b', e['contig']), e['alt_pos']) for e in p['events'] if e['type'] == 'SNV']
252
+ sites = sorted(set(sites))
253
+ return sites[:: max(1, len(sites) // limit)][:limit]
254
+
255
+
256
+ def stale_reference_indexes(artefacts, attributions, version_of_file, same_content, graph=None):
257
+ """Reference indexes that no longer describe the FASTA beside them.
258
+
259
+ Names and lengths are checked for every index; beyond them, .fai offsets and
260
+ line layout against the FASTA bytes, .dict MD5s against the sequences, and the
261
+ sequence held by a BWA .pac or a minimap2 .mmi at the substitution sites where
262
+ this version differs from the others. A .fai, a STAR index or an index built
263
+ without its sequence cannot see a substitution-only change, and is reported as
264
+ ``names_lengths_only`` when another version shares this one's layout.
265
+ """
266
+ by_path = {a['path']: a for a in artefacts}
267
+ att = {r['relpath']: r for r in attributions}
268
+ full = {v['id']: v for v in (graph or {}).get('full_versions', [])}
269
+ seq_cache = {}
270
+ rows = []
271
+ for a in artefacts:
272
+ if a['kind'] not in REF_INDEX:
273
+ continue
274
+ fasta = _fasta_beside(a['path'], by_path)
275
+ r = att.get(a['relpath'], {})
276
+ cv = r.get('detail', {}).get('coordinate_versions')
277
+ best = r.get('attribution', {}).get('best')
278
+ if fasta is None:
279
+ rows.append({'index': a['relpath'], 'fasta': None, 'index_version': best, 'status': 'no_fasta_beside'})
280
+ continue
281
+ fv = version_of_file.get(fasta['relpath'])
282
+ row = {'index': a['relpath'], 'fasta': fasta['relpath'], 'fasta_version': fv, 'index_version': best}
283
+ if fv is None:
284
+ rows.append({**row, 'status': 'not_an_assembly'}); continue
285
+ ok = cv is not None and any(same_content(fv, v) for v in cv)
286
+ status, how = ('current' if ok else 'stale'), 'names_lengths'
287
+ try:
288
+ if ok and a['kind'] == 'fai':
289
+ want, have = fasta_layout(fasta['path']), _read_fai(a['path'])
290
+ if any(want.get(n) != t for n, t in have.items()):
291
+ status, how = 'stale', 'layout'
292
+ else:
293
+ how = 'layout'
294
+ elif ok and a['kind'] == 'dict':
295
+ md5 = dict(zip(full.get(fv, {}).get('names', []), full.get(fv, {}).get('md5', [])))
296
+ got = (a.get('sides') or [{}])[0].get('md5') or {}
297
+ if got:
298
+ how = 'md5'
299
+ if any(md5.get(n) != d for n, d in got.items()):
300
+ status = 'stale'
301
+ elif ok and a['kind'] in ('bwa_index', 'mmi') and graph:
302
+ sites = _check_sites(graph, fv)
303
+ if sites:
304
+ if a['kind'] == 'bwa_index':
305
+ offs = _bwa_offsets(a['path'])
306
+ got = _bwa_bases(a['path'][:-4], offs, sites) if offs is not None else None
307
+ else:
308
+ got = _mmi_bases(a['path'], sites)
309
+ if got:
310
+ if fv not in seq_cache:
311
+ from .core import _contigs
312
+ seq_cache[fv] = {h.split()[0]: s.upper() for h, s in _contigs(fasta['path'])}
313
+ seqs = seq_cache[fv]
314
+ bad = sum(1 for (c, p), x in got.items() if x != 'N' and seqs.get(c, '')[p - 1:p] != x)
315
+ how = 'sequence_at_differing_sites'
316
+ row['sites_checked'] = len(got)
317
+ if bad:
318
+ status = 'stale'; row['sites_differing'] = bad
319
+ except (OSError, ValueError, IndexError) as exc:
320
+ row['check_error'] = f'{type(exc).__name__}: {exc}'
321
+ if status == 'current' and how in ('names_lengths', 'layout') and cv and len(cv) > 1:
322
+ status = 'names_lengths_only'
323
+ rows.append({**row, 'status': status, 'checked': how})
324
+ return rows
325
+
326
+
327
+ def _bwa_offsets(ann_path):
328
+ """Contig offsets in the concatenated BWA sequence, from the .ann file (bns_dump)."""
329
+ offs = {}
330
+ with open(ann_path, encoding='utf-8', errors='replace') as fh:
331
+ head = fh.readline().split()
332
+ n = int(head[1]) if len(head) > 1 and head[1].isdigit() else 0
333
+ for _ in range(n):
334
+ a = fh.readline().split(); b = fh.readline().split()
335
+ if len(a) >= 2 and len(b) >= 2 and b[0].isdigit():
336
+ offs[a[1]] = int(b[0])
337
+ return offs or None
338
+
339
+
340
+ def stage_matrix(artefacts, attributions, versions, latest, same_content, inherited=None):
341
+ """Artefacts per (version, stage) from the attribution; stages lacking the latest version."""
342
+ stage_of_rel = {a['relpath']: a.get('stage') or STAGE_OF.get(a['kind'], 'other') for a in artefacts}
343
+ matrix = {v['id']: defaultdict(list) for v in versions}
344
+ unattributed = defaultdict(list)
345
+ for r in attributions:
346
+ rel = r.get('file', r['relpath'])
347
+ stage = stage_of_rel.get(rel, 'other')
348
+ a = r['attribution']
349
+ best = a.get('best')
350
+ if (inherited or {}).get(r['relpath']):
351
+ best = inherited[r['relpath']]['version']
352
+ if isinstance(best, str) and a.get('status') in ('decisive', 'very_strong', 'strong', 'substantial', 'weak') or \
353
+ (inherited or {}).get(r['relpath']):
354
+ matrix[best][stage].append(r['relpath'])
355
+ elif isinstance(best, list):
356
+ for b in best:
357
+ matrix[b][stage].append(r['relpath'])
358
+ else:
359
+ unattributed[stage].append(r['relpath'])
360
+ stale = []
361
+ for stage in DATA_STAGES:
362
+ holders = [v['id'] for v in versions if matrix[v['id']].get(stage)]
363
+ if holders and latest and not any(same_content(h, latest) for h in holders):
364
+ stale.append({'stage': stage, 'latest': latest, 'versions_with_files': holders})
365
+ return {'matrix': {v: dict(s) for v, s in matrix.items()}, 'unattributed': dict(unattributed),
366
+ 'stages_missing_latest': stale}
367
+
368
+
369
+ def stage_summary(artefacts):
370
+ counts = defaultdict(lambda: defaultdict(int))
371
+ for a in artefacts:
372
+ counts[a.get('stage') or STAGE_OF.get(a['kind'], 'other')][a['kind']] += 1
373
+ unknown = defaultdict(int)
374
+ for a in artefacts:
375
+ if a['kind'] == 'other':
376
+ name = Path(a['path']).name.lower()
377
+ ext = re.search(r'(\.[a-z0-9]{1,8})(\.gz)?$', name)
378
+ unknown[(ext.group(0) if ext else '(none)')] += 1
379
+ return {'by_stage': {s: dict(k) for s, k in counts.items()}, 'unrecognised_extensions': dict(unknown)}
@@ -0,0 +1,69 @@
1
+ """Input alias checks and atomic publication of individual text outputs.
2
+
3
+ Checks are point-in-time protection against accidental overwrites. They do not
4
+ sandbox external programs or exclude concurrent hostile filesystem changes.
5
+ """
6
+ import os
7
+ from pathlib import Path
8
+ import tempfile
9
+ from typing import Sequence
10
+
11
+
12
+ def _identity(path: Path):
13
+ try:
14
+ resolved = path.resolve()
15
+ except (OSError, RuntimeError) as exc:
16
+ raise ValueError(f'Cannot resolve output/input path {path}: {exc}') from exc
17
+ try:
18
+ info = path.stat()
19
+ except OSError: # absent, or a name the platform cannot hold (Windows: <, >, ...)
20
+ inode = None
21
+ else:
22
+ inode = (info.st_dev, info.st_ino)
23
+ return resolved, inode
24
+
25
+
26
+ def validate_output_paths(inputs: Sequence[Path], outputs: Sequence[Path]) -> None:
27
+ """Reject outputs aliasing inputs or one another, including existing links.
28
+
29
+ Inputs need not be distinct. Paths that do not exist are compared after
30
+ resolving their existing parent symlinks and relative path components.
31
+ """
32
+ input_paths = [(Path(p), _identity(Path(p))) for p in inputs]
33
+ checked_outputs = []
34
+ for value in outputs:
35
+ path = Path(value)
36
+ identity = _identity(path)
37
+ for other, other_identity in input_paths + checked_outputs:
38
+ if (identity[0] == other_identity[0] or
39
+ (identity[1] is not None and identity[1] == other_identity[1])):
40
+ raise ValueError(f'Output path aliases an input or another output: {path} overlaps {other}')
41
+ checked_outputs.append((path, identity))
42
+
43
+
44
+ def atomic_write_text(path: Path, text: str) -> None:
45
+ """Publish UTF-8 text with a sibling temporary file and atomic replacement.
46
+
47
+ A failed write, fsync, or replacement leaves any previous output intact and
48
+ removes the temporary file. Existing destination symlinks are replaced,
49
+ rather than followed. This provides single-file atomicity, not a transaction
50
+ across multiple outputs or protection from arbitrary external commands.
51
+ """
52
+ path = Path(path)
53
+ path.parent.mkdir(parents=True, exist_ok=True)
54
+ temporary = None
55
+ try:
56
+ with tempfile.NamedTemporaryFile(mode='w', encoding='utf-8', newline='',
57
+ dir=path.parent, prefix=f'.{path.name}.',
58
+ suffix='.tmp', delete=False) as handle:
59
+ temporary = Path(handle.name)
60
+ handle.write(text)
61
+ handle.flush()
62
+ os.fsync(handle.fileno())
63
+ os.replace(temporary, path)
64
+ finally:
65
+ if temporary is not None:
66
+ try:
67
+ temporary.unlink()
68
+ except FileNotFoundError:
69
+ pass