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/formats.py
ADDED
|
@@ -0,0 +1,957 @@
|
|
|
1
|
+
"""Recognition and description of every file class of a genome project.
|
|
2
|
+
|
|
3
|
+
Each recognised file gets a kind and a stage. Descriptors are reduced to a
|
|
4
|
+
small common vocabulary so that one evidence function can attribute them:
|
|
5
|
+
|
|
6
|
+
sides list of {'side', 'names', 'lengths', 'max_pos', 'digests', 'md5', 'labels'}
|
|
7
|
+
describing the reference coordinate system(s) a file refers to.
|
|
8
|
+
Files that join two versions (PAF, chain, MUMmer delta, AGP) have
|
|
9
|
+
two sides, attributed separately.
|
|
10
|
+
reads for read files: count, bases, validity, a deterministic sketch of
|
|
11
|
+
read names (names whose hash falls in 1/1000 of the hash space,
|
|
12
|
+
so that sketches of different files are directly comparable)
|
|
13
|
+
integrity 'ok', 'empty', 'truncated', 'invalid: <reason>' or absent
|
|
14
|
+
claims command lines (for workflow records and headers)
|
|
15
|
+
"""
|
|
16
|
+
from __future__ import annotations
|
|
17
|
+
|
|
18
|
+
import os
|
|
19
|
+
import base64
|
|
20
|
+
import csv
|
|
21
|
+
import gzip
|
|
22
|
+
import hashlib
|
|
23
|
+
import io
|
|
24
|
+
import json
|
|
25
|
+
import re
|
|
26
|
+
import struct
|
|
27
|
+
import zlib
|
|
28
|
+
from pathlib import Path
|
|
29
|
+
|
|
30
|
+
SKETCH_MOD = 1000
|
|
31
|
+
ALL_NAMES_LIMIT = 20000 # small read files keep every name, so small projects link exactly too
|
|
32
|
+
FIRST_NAMES = 2000
|
|
33
|
+
BGZF_EOF = bytes.fromhex('1f8b08040000000000ff0600424302001b0003000000000000000000')
|
|
34
|
+
|
|
35
|
+
STAGES = ('raw_reads', 'run_metadata', 'read_qc', 'assembly', 'assembly_graph', 'index', 'alignment',
|
|
36
|
+
'coverage', 'variants', 'annotation', 'derived_sequences', 'functional_annotation', 'repeats',
|
|
37
|
+
'scaffolding', 'assembly_qc', 'contig_tables', 'workflow', 'environment', 'metadata', 'checksums', 'other')
|
|
38
|
+
|
|
39
|
+
STAGE_OF = {
|
|
40
|
+
'fastq': 'raw_reads', 'reads_fasta': 'raw_reads', 'ubam': 'raw_reads', 'raw_signal': 'raw_reads',
|
|
41
|
+
'sequencing_summary': 'run_metadata', 'run_report': 'run_metadata', 'samplesheet': 'run_metadata',
|
|
42
|
+
'fastqc': 'read_qc', 'fastp': 'read_qc', 'nanostats': 'read_qc', 'multiqc': 'read_qc',
|
|
43
|
+
'assembly': 'assembly', 'gfa': 'assembly_graph', 'assembly_info': 'assembly_graph',
|
|
44
|
+
'fai': 'index', 'dict': 'index', 'bwa_index': 'index', 'mmi': 'index', 'star_index': 'index',
|
|
45
|
+
'hts_index': 'index', 'other_index': 'index',
|
|
46
|
+
'bam': 'alignment', 'cram': 'alignment', 'sam': 'alignment', 'paf': 'alignment', 'chain': 'alignment',
|
|
47
|
+
'delta': 'alignment',
|
|
48
|
+
'bigwig': 'coverage', 'bedgraph': 'coverage',
|
|
49
|
+
'vcf': 'variants', 'bcf': 'variants',
|
|
50
|
+
'gff': 'annotation', 'genbank': 'annotation', 'ncbi_tbl': 'annotation', 'bed': 'annotation',
|
|
51
|
+
'protein': 'derived_sequences', 'cds_fasta': 'derived_sequences', 'assembly_subset': 'derived_sequences',
|
|
52
|
+
'interproscan': 'functional_annotation', 'id_table': 'functional_annotation',
|
|
53
|
+
'repeatmasker_out': 'repeats', 'repeatmasker_tbl': 'repeats',
|
|
54
|
+
'agp': 'scaffolding', 'pairs': 'scaffolding', 'hic': 'scaffolding',
|
|
55
|
+
'busco': 'assembly_qc', 'busco_table': 'assembly_qc', 'quast': 'assembly_qc', 'merqury': 'assembly_qc',
|
|
56
|
+
'workflow_script': 'workflow', 'workflow_log': 'workflow', 'snakemake_record': 'workflow', 'nextflow_task': 'workflow',
|
|
57
|
+
'nextflow_trace': 'workflow', 'tool_params': 'workflow',
|
|
58
|
+
'environment': 'environment', 'readme': 'metadata', 'metadata_table': 'metadata',
|
|
59
|
+
'checksums': 'checksums', 'contig_table': 'contig_tables', 'msa': 'other', 'transcripts': 'other', 'other': 'other',
|
|
60
|
+
}
|
|
61
|
+
|
|
62
|
+
VERSION_BOUND = {'gff', 'genbank', 'ncbi_tbl', 'bed', 'protein', 'cds_fasta', 'assembly_subset', 'interproscan', 'vcf', 'bcf',
|
|
63
|
+
'bam', 'cram', 'sam', 'paf', 'chain', 'delta', 'agp', 'pairs', 'bigwig', 'bedgraph',
|
|
64
|
+
'fai', 'dict', 'bwa_index', 'mmi', 'star_index', 'gfa', 'assembly_info',
|
|
65
|
+
'repeatmasker_out', 'repeatmasker_tbl', 'busco', 'busco_table', 'quast', 'merqury', 'contig_table'}
|
|
66
|
+
|
|
67
|
+
READS = {'fastq', 'reads_fasta', 'ubam'}
|
|
68
|
+
|
|
69
|
+
_READ_NAME = re.compile(r'^([0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}' # ONT
|
|
70
|
+
r'|m\d+[A-Za-z]?_\d+_\d+(?:_s\d+)?(?:/\d+)+(?:/ccs(?:/(?:fwd|rev))?)?.*' # PacBio (Sequel, Revio)
|
|
71
|
+
r'|[SED]RR\d+\.\d+.*' # SRA
|
|
72
|
+
r'|[^:\s]+:\d+:[^:\s]+:\d+:\d+:\d+:\d+.*)$') # Illumina
|
|
73
|
+
|
|
74
|
+
|
|
75
|
+
def opener(path):
|
|
76
|
+
with open(path, 'rb') as fh:
|
|
77
|
+
magic = fh.read(2)
|
|
78
|
+
if magic == b'\x1f\x8b':
|
|
79
|
+
return lambda: gzip.open(path, 'rt', encoding='utf-8', errors='replace')
|
|
80
|
+
return lambda: open(path, 'r', encoding='utf-8', errors='replace')
|
|
81
|
+
|
|
82
|
+
|
|
83
|
+
def is_bgzf(path):
|
|
84
|
+
with open(path, 'rb') as fh:
|
|
85
|
+
head = fh.read(18)
|
|
86
|
+
return len(head) >= 16 and head[:4] == b'\x1f\x8b\x08\x04' and head[12:14] == b'BC'
|
|
87
|
+
|
|
88
|
+
|
|
89
|
+
def bgzf_eof_ok(path):
|
|
90
|
+
with open(path, 'rb') as fh:
|
|
91
|
+
fh.seek(0, 2)
|
|
92
|
+
if fh.tell() < 28:
|
|
93
|
+
return False
|
|
94
|
+
fh.seek(-28, 2)
|
|
95
|
+
return fh.read() == BGZF_EOF
|
|
96
|
+
|
|
97
|
+
|
|
98
|
+
def name_hash(name: str) -> int:
|
|
99
|
+
return int.from_bytes(hashlib.blake2b(name.encode('utf-8', 'replace'), digest_size=8).digest(), 'little')
|
|
100
|
+
|
|
101
|
+
|
|
102
|
+
def normalise_read_name(name: str) -> str:
|
|
103
|
+
name = name.split()[0] if name.split() else name
|
|
104
|
+
return name[:-2] if name.endswith(('/1', '/2')) else name
|
|
105
|
+
|
|
106
|
+
|
|
107
|
+
# ---------------------------------------------------------------- detection
|
|
108
|
+
|
|
109
|
+
NAMED = [
|
|
110
|
+
(re.compile(r'^sequencing_summary.*\.txt(\.gz)?$', re.I), 'sequencing_summary'),
|
|
111
|
+
(re.compile(r'^(final_summary|report_).*\.(txt|json|html|md)$', re.I), 'run_report'),
|
|
112
|
+
(re.compile(r'^(samplesheet|sample_sheet).*\.(csv|tsv)$|^runinfo\.xml$|^runparameters\.xml$', re.I), 'samplesheet'),
|
|
113
|
+
(re.compile(r'_fastqc\.(zip|html)$', re.I), 'fastqc'),
|
|
114
|
+
(re.compile(r'^nanostats.*\.txt$', re.I), 'nanostats'),
|
|
115
|
+
(re.compile(r'^multiqc.*\.(html|json|txt)$', re.I), 'multiqc'),
|
|
116
|
+
(re.compile(r'^assembly_info\.txt$', re.I), 'assembly_info'),
|
|
117
|
+
(re.compile(r'^chrnamelength\.txt$', re.I), 'star_index'),
|
|
118
|
+
(re.compile(r'^params\.json$', re.I), 'tool_params'),
|
|
119
|
+
(re.compile(r'^(execution_)?trace.*\.txt$', re.I), 'nextflow_trace'),
|
|
120
|
+
(re.compile(r'^(environment|env|conda).*\.ya?ml$|^requirements.*\.txt$|^dockerfile$|\.def$|^singularity', re.I), 'environment'),
|
|
121
|
+
(re.compile(r'^readme(\.\w+)?$|^changelog(\.\w+)?$', re.I), 'readme'),
|
|
122
|
+
(re.compile(r'^(md5sums?|sha256sums?|checksums?)(\.txt|\.md5|\.sha256)?$', re.I), 'checksums'),
|
|
123
|
+
(re.compile(r'\.(md5|sha256)$', re.I), 'checksums'),
|
|
124
|
+
(re.compile(r'^\.command\.(sh|run|log|err|out)$'), 'workflow_log'),
|
|
125
|
+
(re.compile(r'^snakefile$', re.I), 'workflow_script'),
|
|
126
|
+
(re.compile(r'^slurm-\d+.*\.(out|err)$', re.I), 'workflow_log'),
|
|
127
|
+
]
|
|
128
|
+
|
|
129
|
+
EXT = [
|
|
130
|
+
('.fastq.gz', 'fastq'), ('.fq.gz', 'fastq'), ('.fastq', 'fastq'), ('.fq', 'fastq'),
|
|
131
|
+
('.pod5', 'raw_signal'), ('.fast5', 'raw_signal'), ('.blow5', 'raw_signal'), ('.slow5', 'raw_signal'),
|
|
132
|
+
('.gfa.gz', 'gfa'), ('.gfa', 'gfa'),
|
|
133
|
+
('.fai', 'fai'), ('.dict', 'dict'), ('.mmi', 'mmi'), ('.ann', 'bwa_index'),
|
|
134
|
+
('.amb', 'other_index'), ('.bwt', 'other_index'), ('.pac', 'other_index'), ('.sa', 'other_index'),
|
|
135
|
+
('.bt2', 'other_index'), ('.ht2', 'other_index'), ('.nhr', 'other_index'), ('.nin', 'other_index'),
|
|
136
|
+
('.nsq', 'other_index'), ('.phr', 'other_index'), ('.pin', 'other_index'), ('.psq', 'other_index'),
|
|
137
|
+
('.bai', 'hts_index'), ('.csi', 'hts_index'), ('.crai', 'hts_index'), ('.tbi', 'hts_index'), ('.gzi', 'hts_index'),
|
|
138
|
+
('.bcf', 'bcf'), ('.bw', 'bigwig'), ('.bigwig', 'bigwig'), ('.bb', 'bigwig'), ('.bigbed', 'bigwig'),
|
|
139
|
+
('.bedgraph.gz', 'bedgraph'), ('.bedgraph', 'bedgraph'), ('.bdg', 'bedgraph'),
|
|
140
|
+
('.chain.gz', 'chain'), ('.chain', 'chain'), ('.over.chain', 'chain'), ('.delta', 'delta'),
|
|
141
|
+
('.gbk', 'genbank'), ('.gbff', 'genbank'), ('.gb', 'genbank'), ('.embl', 'genbank'),
|
|
142
|
+
('.gbk.gz', 'genbank'), ('.gbff.gz', 'genbank'), ('.embl.gz', 'genbank'),
|
|
143
|
+
('.tbl', None), # NCBI feature table or RepeatMasker summary, decided by content
|
|
144
|
+
('.out', None), # RepeatMasker .out or a log, decided by content
|
|
145
|
+
('.pairs.gz', 'pairs'), ('.pairs', 'pairs'), ('.hic', 'hic'), ('.mcool', 'hic'), ('.cool', 'hic'),
|
|
146
|
+
('.qv', 'merqury'), ('.completeness.stats', 'merqury'),
|
|
147
|
+
('.sh', 'workflow_script'), ('.bash', 'workflow_script'), ('.sbatch', 'workflow_script'),
|
|
148
|
+
('.slurm', 'workflow_script'), ('.pbs', 'workflow_script'), ('.smk', 'workflow_script'),
|
|
149
|
+
('.nf', 'workflow_script'), ('.wdl', 'workflow_script'), ('.cwl', 'workflow_script'),
|
|
150
|
+
('.log', 'workflow_log'), ('.err', 'workflow_log'),
|
|
151
|
+
('.yml', None), ('.yaml', None), ('.json', None), ('.xml', 'metadata_table'),
|
|
152
|
+
('.md', 'readme'), ('.rst', 'readme'),
|
|
153
|
+
]
|
|
154
|
+
|
|
155
|
+
|
|
156
|
+
def detect(path: Path, head: bytes, relparts=()):
|
|
157
|
+
"""Kind for files that extension or name alone identifies; None to defer."""
|
|
158
|
+
name = path.name
|
|
159
|
+
low = name.lower()
|
|
160
|
+
if '.snakemake' in relparts and 'metadata' in relparts:
|
|
161
|
+
return 'snakemake_record'
|
|
162
|
+
if name == '.command.sh' and 'work' in relparts:
|
|
163
|
+
return 'nextflow_task'
|
|
164
|
+
for rx, kind in NAMED:
|
|
165
|
+
if rx.search(name):
|
|
166
|
+
return kind
|
|
167
|
+
if low.endswith(('.fastq.gz', '.fq.gz', '.fastq', '.fq')):
|
|
168
|
+
return 'fastq'
|
|
169
|
+
for ext, kind in sorted(EXT, key=lambda x: -len(x[0])):
|
|
170
|
+
if low.endswith(ext):
|
|
171
|
+
if kind:
|
|
172
|
+
return kind
|
|
173
|
+
text = head.decode('utf-8', 'replace')
|
|
174
|
+
if ext == '.tbl':
|
|
175
|
+
if text.startswith('>Feature'):
|
|
176
|
+
return 'ncbi_tbl'
|
|
177
|
+
if 'file name:' in text and 'sequences:' in text:
|
|
178
|
+
return 'repeatmasker_tbl'
|
|
179
|
+
return None
|
|
180
|
+
if ext == '.out':
|
|
181
|
+
if 'SW' in text.split('\n')[0] and 'perc' in text.split('\n')[0]:
|
|
182
|
+
return 'repeatmasker_out'
|
|
183
|
+
return 'workflow_log'
|
|
184
|
+
if ext in ('.yml', '.yaml'):
|
|
185
|
+
return 'environment' if re.search(r'^\s*(dependencies|channels)\s*:', text, re.M) else 'metadata_table'
|
|
186
|
+
if ext == '.json':
|
|
187
|
+
if '"summary"' in text and '"before_filtering"' in text:
|
|
188
|
+
return 'fastp'
|
|
189
|
+
if '"busco' in text.lower() or ('"results"' in text and '"one_line_summary"' in text):
|
|
190
|
+
return 'busco'
|
|
191
|
+
return 'metadata_table'
|
|
192
|
+
if head.startswith(b'\x8bPOD') or head.startswith(b'\x89HDF\r\n\x1a\n') and low.endswith(('.fast5', '.hdf5')):
|
|
193
|
+
return 'raw_signal'
|
|
194
|
+
if head.startswith(b'MMI\x02'):
|
|
195
|
+
return 'mmi'
|
|
196
|
+
if head[:4] in (b'\x26\xfc\x8f\x88', b'\xeb\xf2\x89\x87'):
|
|
197
|
+
return 'bigwig'
|
|
198
|
+
return None
|
|
199
|
+
|
|
200
|
+
|
|
201
|
+
TRANSCRIPT_NAME = re.compile(r'^(TRINITY_DN\d+|NODE_\d+_length_\d+_cov_[\d.]+_g\d+_i\d+|STRG\.\d+|transcript[_:])', re.I)
|
|
202
|
+
|
|
203
|
+
|
|
204
|
+
def fasta_subtype(path, sniff=2000):
|
|
205
|
+
"""'reads_fasta', 'cds_fasta', 'transcripts', 'msa' or 'assembly' from the extension and the first records."""
|
|
206
|
+
low = str(path).lower()
|
|
207
|
+
for ext, kind in (('.ffn', 'cds_fasta'), ('.frn', 'other'), ('.cds.fa', 'cds_fasta'), ('.cds.fasta', 'cds_fasta'),
|
|
208
|
+
('.aln', 'msa'), ('.afa', 'msa')):
|
|
209
|
+
if low.endswith(ext) or low.endswith(ext + '.gz'):
|
|
210
|
+
return kind
|
|
211
|
+
names, seqs, cur = [], [], []
|
|
212
|
+
with opener(path)() as fh:
|
|
213
|
+
for line in fh:
|
|
214
|
+
if line.startswith('>'):
|
|
215
|
+
if names:
|
|
216
|
+
seqs.append(''.join(cur)); cur = []
|
|
217
|
+
if len(names) >= sniff:
|
|
218
|
+
break
|
|
219
|
+
names.append(line[1:].strip())
|
|
220
|
+
else:
|
|
221
|
+
cur.append(line.strip())
|
|
222
|
+
else:
|
|
223
|
+
if names:
|
|
224
|
+
seqs.append(''.join(cur))
|
|
225
|
+
seqs = seqs[:len(names)]
|
|
226
|
+
if not names:
|
|
227
|
+
return 'assembly'
|
|
228
|
+
if seqs and any(c in seqs[0] for c in '-.'):
|
|
229
|
+
return 'msa' # gapped alignment, not an assembly
|
|
230
|
+
readlike = sum(bool(_READ_NAME.match(n.split()[0])) for n in names) / len(names)
|
|
231
|
+
if readlike >= 0.9 and len(names) >= 20:
|
|
232
|
+
return 'reads_fasta'
|
|
233
|
+
if sum(bool(TRANSCRIPT_NAME.match(n)) for n in names) / len(names) >= 0.9 and len(names) >= 20:
|
|
234
|
+
return 'transcripts'
|
|
235
|
+
if len(names) >= 50:
|
|
236
|
+
starts = ('ATG', 'GTG', 'TTG', 'CTG') # bacterial genes start with alternative codons too
|
|
237
|
+
orf = sum(1 for s in seqs if len(s) % 3 == 0 and s[:3].upper() in starts
|
|
238
|
+
and s[-3:].upper() in ('TAA', 'TAG', 'TGA')) / len(seqs)
|
|
239
|
+
if orf >= 0.7:
|
|
240
|
+
return 'cds_fasta'
|
|
241
|
+
return 'assembly'
|
|
242
|
+
|
|
243
|
+
|
|
244
|
+
# ---------------------------------------------------------------- reads
|
|
245
|
+
|
|
246
|
+
def describe_fastq(path):
|
|
247
|
+
"""Full validating pass: counts, bases, mean length, name sketch, pairing key."""
|
|
248
|
+
n = bases = 0
|
|
249
|
+
sketch, every = [], []
|
|
250
|
+
first = None
|
|
251
|
+
problem = None
|
|
252
|
+
try:
|
|
253
|
+
with opener(path)() as fh:
|
|
254
|
+
while True:
|
|
255
|
+
h = fh.readline()
|
|
256
|
+
if not h:
|
|
257
|
+
break
|
|
258
|
+
if not h.strip():
|
|
259
|
+
continue # a blank line between or after records
|
|
260
|
+
s = fh.readline(); p = fh.readline(); q = fh.readline()
|
|
261
|
+
n += 1
|
|
262
|
+
if not h.startswith('@') or not p.startswith('+') or len(s.rstrip('\r\n')) != len(q.rstrip('\r\n')):
|
|
263
|
+
problem = f'invalid FASTQ record {n}'
|
|
264
|
+
break
|
|
265
|
+
name = normalise_read_name(h[1:])
|
|
266
|
+
if first is None:
|
|
267
|
+
first = name
|
|
268
|
+
bases += len(s.rstrip('\r\n'))
|
|
269
|
+
if name_hash(name) % SKETCH_MOD == 0:
|
|
270
|
+
sketch.append(name)
|
|
271
|
+
if n <= ALL_NAMES_LIMIT:
|
|
272
|
+
every.append(name)
|
|
273
|
+
except (EOFError, OSError, zlib.error) as exc:
|
|
274
|
+
problem = f'truncated: {exc}'
|
|
275
|
+
integrity = 'ok' if problem is None else ('truncated' if problem.startswith('truncated') else f'invalid: {problem}')
|
|
276
|
+
return {'reads': {'count': n, 'bases': bases, 'mean_length': round(bases / n, 1) if n else 0,
|
|
277
|
+
'first_name': first, 'name_sketch': sorted(set(sketch)), 'pair_key': pair_key(path),
|
|
278
|
+
'all_names': every if n <= ALL_NAMES_LIMIT else None},
|
|
279
|
+
'integrity': integrity if n else ('empty' if integrity == 'ok' else integrity)}
|
|
280
|
+
|
|
281
|
+
|
|
282
|
+
def describe_reads_fasta(path):
|
|
283
|
+
n = bases = 0; sketch = []
|
|
284
|
+
try:
|
|
285
|
+
with opener(path)() as fh:
|
|
286
|
+
for line in fh:
|
|
287
|
+
if line.startswith('>'):
|
|
288
|
+
n += 1
|
|
289
|
+
name = normalise_read_name(line[1:])
|
|
290
|
+
if name_hash(name) % SKETCH_MOD == 0:
|
|
291
|
+
sketch.append(name)
|
|
292
|
+
else:
|
|
293
|
+
bases += len(line.strip())
|
|
294
|
+
integrity = 'ok' if n else 'empty'
|
|
295
|
+
except (EOFError, OSError, zlib.error) as exc:
|
|
296
|
+
integrity = 'truncated'
|
|
297
|
+
return {'reads': {'count': n, 'bases': bases, 'mean_length': round(bases / n, 1) if n else 0,
|
|
298
|
+
'name_sketch': sorted(set(sketch)), 'pair_key': None}, 'integrity': integrity}
|
|
299
|
+
|
|
300
|
+
|
|
301
|
+
def pair_key(path):
|
|
302
|
+
"""'sample', '1'|'2' for files named like x_R1.fastq.gz / x_1.fq / x.R2.fq.gz, else None."""
|
|
303
|
+
m = re.match(r'^(.*?)([._-]R?)([12])((?:[._-]\d{3})?\.f(?:ast)?q(?:\.gz)?)$', Path(path).name, re.I)
|
|
304
|
+
return [m.group(1) + m.group(4), m.group(3)] if m else None
|
|
305
|
+
|
|
306
|
+
|
|
307
|
+
def alignment_name_sketch(path, kind, max_reads=3_000_000, want=300):
|
|
308
|
+
"""{'sketch': hashed subsample of read names, 'first': the first names}, read until enough are sketched."""
|
|
309
|
+
names, first = set(), []
|
|
310
|
+
|
|
311
|
+
def keep(nm):
|
|
312
|
+
if len(first) < FIRST_NAMES and (not first or first[-1] != nm):
|
|
313
|
+
first.append(nm)
|
|
314
|
+
if name_hash(nm) % SKETCH_MOD == 0:
|
|
315
|
+
names.add(nm)
|
|
316
|
+
try:
|
|
317
|
+
import pysam
|
|
318
|
+
with pysam.AlignmentFile(str(path), 'rc' if kind == 'cram' else ('r' if kind == 'sam' else 'rb'),
|
|
319
|
+
check_sq=False) as fh:
|
|
320
|
+
for i, r in enumerate(fh.fetch(until_eof=True)):
|
|
321
|
+
if r.is_secondary or r.is_supplementary:
|
|
322
|
+
continue
|
|
323
|
+
keep(normalise_read_name(r.query_name or ''))
|
|
324
|
+
if len(names) >= want or i >= max_reads:
|
|
325
|
+
break
|
|
326
|
+
return {'sketch': sorted(names), 'first': first}
|
|
327
|
+
except ImportError:
|
|
328
|
+
pass
|
|
329
|
+
except Exception:
|
|
330
|
+
return None
|
|
331
|
+
if kind == 'sam':
|
|
332
|
+
with opener(path)() as fh:
|
|
333
|
+
for i, line in enumerate(fh):
|
|
334
|
+
if line.startswith('@'):
|
|
335
|
+
continue
|
|
336
|
+
f = line.split('\t', 2)
|
|
337
|
+
if len(f) > 1 and f[1].isdigit() and int(f[1]) & 0x900:
|
|
338
|
+
continue
|
|
339
|
+
keep(normalise_read_name(f[0]))
|
|
340
|
+
if len(names) >= want or i >= max_reads:
|
|
341
|
+
break
|
|
342
|
+
return {'sketch': sorted(names), 'first': first}
|
|
343
|
+
if kind != 'bam' and kind != 'ubam':
|
|
344
|
+
return None
|
|
345
|
+
try:
|
|
346
|
+
with gzip.open(path, 'rb') as f:
|
|
347
|
+
if f.read(4) != b'BAM\x01':
|
|
348
|
+
return None
|
|
349
|
+
l_text = struct.unpack('<i', f.read(4))[0]; f.read(l_text)
|
|
350
|
+
n_ref = struct.unpack('<i', f.read(4))[0]
|
|
351
|
+
for _ in range(n_ref):
|
|
352
|
+
l_name = struct.unpack('<i', f.read(4))[0]; f.read(l_name + 4)
|
|
353
|
+
for i in range(max_reads):
|
|
354
|
+
b = f.read(4)
|
|
355
|
+
if len(b) < 4:
|
|
356
|
+
break
|
|
357
|
+
size = struct.unpack('<i', b)[0]
|
|
358
|
+
block = f.read(size)
|
|
359
|
+
l_name = block[8]
|
|
360
|
+
flag = struct.unpack_from('<H', block, 14)[0]
|
|
361
|
+
if flag & 0x900:
|
|
362
|
+
continue
|
|
363
|
+
keep(normalise_read_name(block[32:32 + l_name - 1].decode('utf-8', 'replace')))
|
|
364
|
+
if len(names) >= want:
|
|
365
|
+
break
|
|
366
|
+
except (OSError, EOFError, struct.error, IndexError):
|
|
367
|
+
return {'sketch': sorted(names), 'first': first} if first else None
|
|
368
|
+
return {'sketch': sorted(names), 'first': first}
|
|
369
|
+
|
|
370
|
+
|
|
371
|
+
# ---------------------------------------------------------------- read QC reports
|
|
372
|
+
|
|
373
|
+
def describe_fastqc(path):
|
|
374
|
+
text = ''
|
|
375
|
+
try:
|
|
376
|
+
if str(path).lower().endswith('.zip'):
|
|
377
|
+
import zipfile
|
|
378
|
+
with zipfile.ZipFile(path) as z:
|
|
379
|
+
member = next((m for m in z.namelist() if m.endswith('fastqc_data.txt')), None)
|
|
380
|
+
text = z.read(member).decode('utf-8', 'replace') if member else ''
|
|
381
|
+
else:
|
|
382
|
+
text = Path(path).read_text(errors='replace')
|
|
383
|
+
except Exception:
|
|
384
|
+
return {'integrity': 'invalid: unreadable FastQC report'}
|
|
385
|
+
fn = re.search(r'Filename\s*(?:</td><td>|\t)\s*([^<\t\n]+)', text)
|
|
386
|
+
tot = re.search(r'Total Sequences\s*(?:</td><td>|\t)\s*(\d+)', text)
|
|
387
|
+
return {'qc': {'reports_on': fn.group(1).strip() if fn else None, 'read_count': int(tot.group(1)) if tot else None}}
|
|
388
|
+
|
|
389
|
+
|
|
390
|
+
def describe_fastp(path):
|
|
391
|
+
try:
|
|
392
|
+
d = json.loads(Path(path).read_text(errors='replace'))
|
|
393
|
+
except ValueError:
|
|
394
|
+
return {'integrity': 'invalid: not JSON'}
|
|
395
|
+
before = d.get('summary', {}).get('before_filtering', {})
|
|
396
|
+
return {'qc': {'read_count': before.get('total_reads'), 'bases': before.get('total_bases'),
|
|
397
|
+
'paired': d.get('read2_before_filtering') is not None},
|
|
398
|
+
'claims': [d['command']] if d.get('command') else []}
|
|
399
|
+
|
|
400
|
+
|
|
401
|
+
def describe_nanostats(path):
|
|
402
|
+
text = Path(path).read_text(errors='replace')
|
|
403
|
+
m = re.search(r'(?:number_of_reads|Number of reads):?\s*([\d,.]+)', text)
|
|
404
|
+
b = re.search(r'(?:number_of_bases|Total bases):?\s*([\d,.]+)', text)
|
|
405
|
+
num = lambda x: int(float(x.replace(',', ''))) if x else None
|
|
406
|
+
return {'qc': {'read_count': num(m.group(1)) if m else None, 'bases': num(b.group(1)) if b else None}}
|
|
407
|
+
|
|
408
|
+
|
|
409
|
+
# ---------------------------------------------------------------- reference coordinate systems
|
|
410
|
+
|
|
411
|
+
def side(names=(), lengths=None, max_pos=None, digests=None, md5=None, labels=(), name=None):
|
|
412
|
+
return {'side': name, 'names': list(dict.fromkeys(names)), 'lengths': lengths or {}, 'max_pos': max_pos or {},
|
|
413
|
+
'digests': digests or {}, 'md5': md5 or {}, 'labels': list(labels)}
|
|
414
|
+
|
|
415
|
+
|
|
416
|
+
def describe_fai(path):
|
|
417
|
+
names, lengths = [], {}
|
|
418
|
+
for line in open(path, encoding='utf-8', errors='replace'):
|
|
419
|
+
f = line.rstrip('\n').split('\t')
|
|
420
|
+
if len(f) >= 2 and f[1].isdigit():
|
|
421
|
+
names.append(f[0]); lengths[f[0]] = int(f[1])
|
|
422
|
+
return {'sides': [side(names, lengths)], 'sidecar_of': _strip(path, ('.fai',))}
|
|
423
|
+
|
|
424
|
+
|
|
425
|
+
def describe_dict(path):
|
|
426
|
+
names, lengths, md5, labels = [], {}, {}, []
|
|
427
|
+
for line in open(path, encoding='utf-8', errors='replace'):
|
|
428
|
+
if line.startswith('@SQ'):
|
|
429
|
+
f = dict(x.split(':', 1) for x in line.rstrip('\n').split('\t')[1:] if ':' in x)
|
|
430
|
+
if 'SN' in f:
|
|
431
|
+
names.append(f['SN'])
|
|
432
|
+
if f.get('LN', '').isdigit():
|
|
433
|
+
lengths[f['SN']] = int(f['LN'])
|
|
434
|
+
if 'M5' in f:
|
|
435
|
+
md5[f['SN']] = f['M5'].lower()
|
|
436
|
+
if 'UR' in f:
|
|
437
|
+
labels.append(f['UR'])
|
|
438
|
+
return {'sides': [side(names, lengths, md5=md5, labels=labels)], 'sidecar_of': _strip(path, ('.dict',))}
|
|
439
|
+
|
|
440
|
+
|
|
441
|
+
def describe_bwa_ann(path):
|
|
442
|
+
names, lengths = [], {}
|
|
443
|
+
with open(path, encoding='utf-8', errors='replace') as fh:
|
|
444
|
+
head = fh.readline().split()
|
|
445
|
+
n = int(head[1]) if len(head) > 1 and head[1].isdigit() else 0
|
|
446
|
+
for _ in range(n):
|
|
447
|
+
a = fh.readline().split(); b = fh.readline().split()
|
|
448
|
+
if len(a) >= 2 and len(b) >= 2:
|
|
449
|
+
names.append(a[1]); lengths[a[1]] = int(b[1])
|
|
450
|
+
return {'sides': [side(names, lengths)], 'sidecar_of': _strip(path, ('.ann',))}
|
|
451
|
+
|
|
452
|
+
|
|
453
|
+
def describe_mmi(path):
|
|
454
|
+
names, lengths = [], {}
|
|
455
|
+
try:
|
|
456
|
+
with open(path, 'rb') as fh:
|
|
457
|
+
if fh.read(4) != b'MMI\x02':
|
|
458
|
+
return {'integrity': 'invalid: not a minimap2 index'}
|
|
459
|
+
w, k, b, n_seq, flag = struct.unpack('<5I', fh.read(20))
|
|
460
|
+
for _ in range(n_seq):
|
|
461
|
+
l = fh.read(1)[0]
|
|
462
|
+
name = fh.read(l).decode('utf-8', 'replace') if l else ''
|
|
463
|
+
length = struct.unpack('<I', fh.read(4))[0]
|
|
464
|
+
names.append(name); lengths[name] = length
|
|
465
|
+
except (OSError, struct.error, IndexError):
|
|
466
|
+
return {'integrity': 'truncated'}
|
|
467
|
+
return {'sides': [side(names, lengths)], 'sidecar_of': _strip(path, ('.mmi',))}
|
|
468
|
+
|
|
469
|
+
|
|
470
|
+
def describe_star(path):
|
|
471
|
+
names, lengths = [], {}
|
|
472
|
+
for line in open(path, encoding='utf-8', errors='replace'):
|
|
473
|
+
f = line.split()
|
|
474
|
+
if len(f) >= 2 and f[1].isdigit():
|
|
475
|
+
names.append(f[0]); lengths[f[0]] = int(f[1])
|
|
476
|
+
return {'sides': [side(names, lengths)]}
|
|
477
|
+
|
|
478
|
+
|
|
479
|
+
def describe_hts_index(path, project_files):
|
|
480
|
+
data = _strip(path, ('.bai', '.csi', '.crai', '.tbi', '.gzi'))
|
|
481
|
+
if data and not Path(data).exists():
|
|
482
|
+
alt = Path(str(path)[:-4] + '.bam') if str(path).endswith('.bai') else None
|
|
483
|
+
data = str(alt) if alt and alt.exists() else data
|
|
484
|
+
out = {'sidecar_of': data}
|
|
485
|
+
if data and Path(data).exists() and Path(path).stat().st_mtime < Path(data).stat().st_mtime - 1:
|
|
486
|
+
out['integrity'] = 'invalid: index is older than its data file'
|
|
487
|
+
return out
|
|
488
|
+
|
|
489
|
+
|
|
490
|
+
def describe_gfa(path):
|
|
491
|
+
names, lengths, digests = [], {}, {}
|
|
492
|
+
from .seqcol import sequence_digest
|
|
493
|
+
with opener(path)() as fh:
|
|
494
|
+
for line in fh:
|
|
495
|
+
if line.startswith('S\t'):
|
|
496
|
+
f = line.rstrip('\n').split('\t')
|
|
497
|
+
if len(f) < 3:
|
|
498
|
+
continue
|
|
499
|
+
if len(f) >= 4 and f[2].isdigit(): # GFA2: S sid slen sequence
|
|
500
|
+
names.append(f[1]); lengths[f[1]] = int(f[2])
|
|
501
|
+
if f[3] != '*':
|
|
502
|
+
digests[f[1]] = sequence_digest(f[3])
|
|
503
|
+
continue
|
|
504
|
+
names.append(f[1])
|
|
505
|
+
if f[2] != '*':
|
|
506
|
+
lengths[f[1]] = len(f[2]); digests[f[1]] = sequence_digest(f[2])
|
|
507
|
+
else:
|
|
508
|
+
ln = next((x[5:] for x in f[3:] if x.startswith('LN:i:')), None)
|
|
509
|
+
if ln and ln.isdigit():
|
|
510
|
+
lengths[f[1]] = int(ln)
|
|
511
|
+
return {'sides': [side(names, lengths, digests=digests)]}
|
|
512
|
+
|
|
513
|
+
|
|
514
|
+
def describe_assembly_info(path):
|
|
515
|
+
names, lengths = [], {}
|
|
516
|
+
for line in open(path, encoding='utf-8', errors='replace'):
|
|
517
|
+
if line.startswith('#'):
|
|
518
|
+
continue
|
|
519
|
+
f = line.split('\t')
|
|
520
|
+
if len(f) >= 2 and f[1].strip().isdigit():
|
|
521
|
+
names.append(f[0]); lengths[f[0]] = int(f[1])
|
|
522
|
+
return {'sides': [side(names, lengths)]}
|
|
523
|
+
|
|
524
|
+
|
|
525
|
+
def describe_bcf(path):
|
|
526
|
+
try:
|
|
527
|
+
with open(path, 'rb') as raw:
|
|
528
|
+
gz = raw.read(2) == b'\x1f\x8b'
|
|
529
|
+
with (gzip.open(path, 'rb') if gz else open(path, 'rb')) as f: # compression is optional (VCF 4.3 6.3)
|
|
530
|
+
if f.read(5) != b'BCF\x02\x02':
|
|
531
|
+
return {'integrity': 'invalid: not BCF 2.2'}
|
|
532
|
+
l_text = struct.unpack('<I', f.read(4))[0]
|
|
533
|
+
text = f.read(l_text).decode('utf-8', 'replace')
|
|
534
|
+
except (OSError, EOFError, struct.error):
|
|
535
|
+
return {'integrity': 'truncated'}
|
|
536
|
+
return vcf_header_sides(text.splitlines())
|
|
537
|
+
|
|
538
|
+
|
|
539
|
+
def vcf_header_sides(lines):
|
|
540
|
+
names, lengths, labels, claims = [], {}, [], []
|
|
541
|
+
for line in lines:
|
|
542
|
+
if line.startswith('##contig='):
|
|
543
|
+
m = re.search(r'ID=([^,>]+)', line); l = re.search(r'length=(\d+)', line)
|
|
544
|
+
if m:
|
|
545
|
+
names.append(m.group(1))
|
|
546
|
+
if l:
|
|
547
|
+
lengths[m.group(1)] = int(l.group(1))
|
|
548
|
+
elif line.startswith('##reference='):
|
|
549
|
+
labels.append(line.split('=', 1)[1].strip())
|
|
550
|
+
elif re.match(r'##\w*[Cc]ommand(Line)?[=.]', line):
|
|
551
|
+
claims.append(line.split('=', 1)[1].strip())
|
|
552
|
+
return {'sides': [side(names, lengths, labels=labels)], 'claims': claims}
|
|
553
|
+
|
|
554
|
+
|
|
555
|
+
def describe_bigwig(path):
|
|
556
|
+
"""Chromosome names and sizes from the B+ tree of a bigWig/bigBed file."""
|
|
557
|
+
try:
|
|
558
|
+
with open(path, 'rb') as fh:
|
|
559
|
+
head = fh.read(64)
|
|
560
|
+
magic = struct.unpack('<I', head[:4])[0]
|
|
561
|
+
endian = '<' if magic in (0x888FFC26, 0x8789F2EB) else '>'
|
|
562
|
+
chrom_tree = struct.unpack(endian + 'Q', head[8:16])[0]
|
|
563
|
+
fh.seek(chrom_tree)
|
|
564
|
+
tmagic, block, key_size, val_size, count = struct.unpack(endian + 'IIIIQ', fh.read(24))
|
|
565
|
+
fh.read(8)
|
|
566
|
+
names, lengths = [], {}
|
|
567
|
+
|
|
568
|
+
def node(offset):
|
|
569
|
+
fh.seek(offset)
|
|
570
|
+
is_leaf, _, n = struct.unpack(endian + 'BBH', fh.read(4))
|
|
571
|
+
children = []
|
|
572
|
+
for _ in range(n):
|
|
573
|
+
key = fh.read(key_size).rstrip(b'\x00').decode('utf-8', 'replace')
|
|
574
|
+
if is_leaf:
|
|
575
|
+
_, size = struct.unpack(endian + 'II', fh.read(8))
|
|
576
|
+
names.append(key); lengths[key] = size
|
|
577
|
+
else:
|
|
578
|
+
children.append(struct.unpack(endian + 'Q', fh.read(8))[0])
|
|
579
|
+
for c in children:
|
|
580
|
+
node(c)
|
|
581
|
+
node(chrom_tree + 32)
|
|
582
|
+
except (OSError, struct.error):
|
|
583
|
+
return {'integrity': 'invalid: unreadable bigWig/bigBed header'}
|
|
584
|
+
return {'sides': [side(names, lengths)]}
|
|
585
|
+
|
|
586
|
+
|
|
587
|
+
def describe_genbank(path):
|
|
588
|
+
from Bio import SeqIO
|
|
589
|
+
from .seqcol import sequence_digest
|
|
590
|
+
fmt = 'embl' if '.embl' in str(path).lower() else 'genbank'
|
|
591
|
+
names, lengths, digests = [], {}, {}
|
|
592
|
+
try:
|
|
593
|
+
with opener(path)() as fh:
|
|
594
|
+
for rec in SeqIO.parse(fh, fmt):
|
|
595
|
+
names.append(rec.id); lengths[rec.id] = len(rec.seq)
|
|
596
|
+
try:
|
|
597
|
+
s = str(rec.seq)
|
|
598
|
+
if s and set(s.upper()) - set('N'):
|
|
599
|
+
digests[rec.id] = sequence_digest(s)
|
|
600
|
+
except Exception: # records without sequence (CONTIG lines)
|
|
601
|
+
pass
|
|
602
|
+
except (ValueError, OSError) as exc:
|
|
603
|
+
return {'integrity': f'invalid: {exc}'}
|
|
604
|
+
return {'sides': [side(names, lengths, digests=digests)]}
|
|
605
|
+
|
|
606
|
+
|
|
607
|
+
def describe_ncbi_tbl(path):
|
|
608
|
+
names, max_pos, cur = [], {}, None
|
|
609
|
+
for line in open(path, encoding='utf-8', errors='replace'):
|
|
610
|
+
if line.startswith('>Feature'):
|
|
611
|
+
p = line.split()
|
|
612
|
+
cur = p[1] if len(p) > 1 else '' # verbatim; side matching also tries its last | field
|
|
613
|
+
names.append(cur)
|
|
614
|
+
elif cur and line[:1].isdigit() or (cur and line[:1] in '<>' and line[1:2].isdigit()):
|
|
615
|
+
for x in line.split('\t')[:2]:
|
|
616
|
+
x = x.strip('<> \n')
|
|
617
|
+
if x.isdigit():
|
|
618
|
+
max_pos[cur] = max(max_pos.get(cur, 0), int(x))
|
|
619
|
+
return {'sides': [side(names, max_pos=max_pos)]}
|
|
620
|
+
|
|
621
|
+
|
|
622
|
+
def describe_repeatmasker_out(path):
|
|
623
|
+
names, lengths, max_pos = [], {}, {}
|
|
624
|
+
for line in open(path, encoding='utf-8', errors='replace'):
|
|
625
|
+
f = line.split()
|
|
626
|
+
if len(f) < 8 or not f[0].isdigit():
|
|
627
|
+
continue
|
|
628
|
+
name, end, left = f[4], f[6], f[7].strip('()')
|
|
629
|
+
if end.isdigit() and left.isdigit():
|
|
630
|
+
names.append(name)
|
|
631
|
+
lengths[name] = int(end) + int(left)
|
|
632
|
+
max_pos[name] = max(max_pos.get(name, 0), int(end))
|
|
633
|
+
return {'sides': [side(names, lengths, max_pos)]}
|
|
634
|
+
|
|
635
|
+
|
|
636
|
+
def describe_repeatmasker_tbl(path):
|
|
637
|
+
text = Path(path).read_text(errors='replace')
|
|
638
|
+
fn = re.search(r'file name:\s*(\S+)', text)
|
|
639
|
+
n = re.search(r'sequences:\s*(\d+)', text)
|
|
640
|
+
t = re.search(r'total length:\s*(\d+)\s*bp', text)
|
|
641
|
+
d = {'sides': [side(labels=[fn.group(1)] if fn else [])]}
|
|
642
|
+
d['metrics'] = {k: int(m.group(1)) for k, m in (('contigs', n), ('total_bp', t)) if m}
|
|
643
|
+
return d
|
|
644
|
+
|
|
645
|
+
|
|
646
|
+
def describe_busco_table(path):
|
|
647
|
+
names, max_pos = [], {}
|
|
648
|
+
for line in open(path, encoding='utf-8', errors='replace'):
|
|
649
|
+
if line.startswith('#'):
|
|
650
|
+
continue
|
|
651
|
+
f = line.rstrip('\n').split('\t')
|
|
652
|
+
if len(f) >= 5 and f[1] in ('Complete', 'Duplicated', 'Fragmented', 'Single', 'Interspaced'): # BUSCO, compleasm
|
|
653
|
+
names.append(f[2])
|
|
654
|
+
for x in f[3:5]:
|
|
655
|
+
if x.isdigit():
|
|
656
|
+
max_pos[f[2]] = max(max_pos.get(f[2], 0), int(x))
|
|
657
|
+
return {'sides': [side(names, max_pos=max_pos)]}
|
|
658
|
+
|
|
659
|
+
|
|
660
|
+
def describe_merqury(path):
|
|
661
|
+
"""Merqury QV tables: the summary (one row per assembly label) or the per-scaffold table
|
|
662
|
+
(scaffold, error k-mers, total k-mers, QV, error rate), whose totals are length - k + 1."""
|
|
663
|
+
rows = []
|
|
664
|
+
for line in open(path, encoding='utf-8', errors='replace'):
|
|
665
|
+
f = line.rstrip('\n').split('\t')
|
|
666
|
+
if f and f[0].strip():
|
|
667
|
+
rows.append(f)
|
|
668
|
+
numeric = [f for f in rows if len(f) >= 4 and f[1].isdigit() and f[2].isdigit()]
|
|
669
|
+
if str(path).endswith('.qv') and len(numeric) >= 3 and len(numeric) == len(rows):
|
|
670
|
+
names = [f[0] for f in numeric]
|
|
671
|
+
return {'sides': [side(names)], 'kmer_totals': {f[0]: int(f[2]) for f in numeric}}
|
|
672
|
+
return {'sides': [side(labels=[f[0].strip() for f in rows][:20])]}
|
|
673
|
+
|
|
674
|
+
|
|
675
|
+
def describe_interproscan(path):
|
|
676
|
+
ids, md5, lengths = [], {}, {}
|
|
677
|
+
for line in open(path, encoding='utf-8', errors='replace'):
|
|
678
|
+
f = line.rstrip('\n').split('\t')
|
|
679
|
+
if len(f) >= 3 and re.fullmatch(r'[0-9a-f]{32}', f[1]) and f[2].isdigit():
|
|
680
|
+
ids.append(f[0]); md5[f[0]] = f[1]; lengths[f[0]] = int(f[2])
|
|
681
|
+
return {'proteins': {'ids': list(dict.fromkeys(ids)), 'md5': md5, 'lengths': lengths}}
|
|
682
|
+
|
|
683
|
+
|
|
684
|
+
def describe_chain(path):
|
|
685
|
+
t, q = side(name='target'), side(name='query')
|
|
686
|
+
with opener(path)() as fh:
|
|
687
|
+
for line in fh:
|
|
688
|
+
if line.startswith('chain'):
|
|
689
|
+
f = line.split()
|
|
690
|
+
if len(f) >= 12:
|
|
691
|
+
t['names'].append(f[2]); t['lengths'][f[2]] = int(f[3])
|
|
692
|
+
q['names'].append(f[7]); q['lengths'][f[7]] = int(f[8])
|
|
693
|
+
for s in (t, q):
|
|
694
|
+
s['names'] = list(dict.fromkeys(s['names']))
|
|
695
|
+
return {'sides': [t, q]}
|
|
696
|
+
|
|
697
|
+
|
|
698
|
+
def describe_delta(path):
|
|
699
|
+
t, q = side(name='reference'), side(name='query')
|
|
700
|
+
with open(path, encoding='utf-8', errors='replace') as fh:
|
|
701
|
+
files = fh.readline().split()
|
|
702
|
+
if len(files) == 2:
|
|
703
|
+
t['labels'].append(files[0]); q['labels'].append(files[1])
|
|
704
|
+
for line in fh:
|
|
705
|
+
if line.startswith('>'):
|
|
706
|
+
f = line[1:].split()
|
|
707
|
+
if len(f) == 4 and f[2].isdigit() and f[3].isdigit():
|
|
708
|
+
t['names'].append(f[0]); t['lengths'][f[0]] = int(f[2])
|
|
709
|
+
q['names'].append(f[1]); q['lengths'][f[1]] = int(f[3])
|
|
710
|
+
for s in (t, q):
|
|
711
|
+
s['names'] = list(dict.fromkeys(s['names']))
|
|
712
|
+
return {'sides': [t, q], 'claims': [' '.join(files)] if len(files) == 2 else []}
|
|
713
|
+
|
|
714
|
+
|
|
715
|
+
def describe_paf(path, max_lines=200000):
|
|
716
|
+
t, q = side(name='target'), side(name='query')
|
|
717
|
+
with opener(path)() as fh:
|
|
718
|
+
for i, line in enumerate(fh):
|
|
719
|
+
if i >= max_lines:
|
|
720
|
+
break
|
|
721
|
+
f = line.split('\t')
|
|
722
|
+
if len(f) >= 12 and f[1].isdigit() and f[6].isdigit():
|
|
723
|
+
q['names'].append(f[0]); q['lengths'][f[0]] = int(f[1])
|
|
724
|
+
t['names'].append(f[5]); t['lengths'][f[5]] = int(f[6])
|
|
725
|
+
for s in (t, q):
|
|
726
|
+
s['names'] = list(dict.fromkeys(s['names']))
|
|
727
|
+
if len(q['names']) > 5000: # reads, not a version: query side is not a coordinate system
|
|
728
|
+
return {'sides': [t]}
|
|
729
|
+
return {'sides': [t, q]}
|
|
730
|
+
|
|
731
|
+
|
|
732
|
+
def describe_agp(path):
|
|
733
|
+
obj, comp = side(name='object'), side(name='component')
|
|
734
|
+
for line in open(path, encoding='utf-8', errors='replace'):
|
|
735
|
+
if line.startswith('#'):
|
|
736
|
+
continue
|
|
737
|
+
f = line.rstrip('\n').split('\t')
|
|
738
|
+
if len(f) < 9 or f[4] in ('N', 'U'):
|
|
739
|
+
if len(f) >= 3 and f[2].isdigit():
|
|
740
|
+
obj['names'].append(f[0]); obj['max_pos'][f[0]] = max(obj['max_pos'].get(f[0], 0), int(f[2]))
|
|
741
|
+
continue
|
|
742
|
+
obj['names'].append(f[0])
|
|
743
|
+
if f[2].isdigit():
|
|
744
|
+
obj['max_pos'][f[0]] = max(obj['max_pos'].get(f[0], 0), int(f[2]))
|
|
745
|
+
comp['names'].append(f[5])
|
|
746
|
+
if f[7].isdigit():
|
|
747
|
+
comp['max_pos'][f[5]] = max(comp['max_pos'].get(f[5], 0), int(f[7]))
|
|
748
|
+
for s in (obj, comp):
|
|
749
|
+
s['names'] = list(dict.fromkeys(s['names']))
|
|
750
|
+
# AGP objects end exactly at their last component: the maximum coordinate is the length
|
|
751
|
+
obj['lengths'] = dict(obj['max_pos'])
|
|
752
|
+
return {'sides': [obj, comp]}
|
|
753
|
+
|
|
754
|
+
|
|
755
|
+
def describe_pairs(path):
|
|
756
|
+
names, lengths = [], {}
|
|
757
|
+
with opener(path)() as fh:
|
|
758
|
+
for line in fh:
|
|
759
|
+
if not line.startswith('#'):
|
|
760
|
+
break
|
|
761
|
+
if line.startswith('#chromsize:'):
|
|
762
|
+
f = line.split()
|
|
763
|
+
if len(f) >= 3 and f[2].isdigit():
|
|
764
|
+
names.append(f[1]); lengths[f[1]] = int(f[2])
|
|
765
|
+
return {'sides': [side(names, lengths)]}
|
|
766
|
+
|
|
767
|
+
|
|
768
|
+
def describe_bedgraph(path, max_lines=500000):
|
|
769
|
+
names, max_pos = [], {}
|
|
770
|
+
with opener(path)() as fh:
|
|
771
|
+
for i, line in enumerate(fh):
|
|
772
|
+
if i >= max_lines:
|
|
773
|
+
break
|
|
774
|
+
if line.startswith(('#', 'track', 'browser')):
|
|
775
|
+
continue
|
|
776
|
+
f = line.split()
|
|
777
|
+
if len(f) >= 3 and f[2].isdigit():
|
|
778
|
+
names.append(f[0]); max_pos[f[0]] = max(max_pos.get(f[0], 0), int(f[2]))
|
|
779
|
+
return {'sides': [side(list(dict.fromkeys(names)), max_pos=max_pos)]}
|
|
780
|
+
|
|
781
|
+
|
|
782
|
+
def _strip(path, suffixes):
|
|
783
|
+
s = str(path)
|
|
784
|
+
for x in suffixes:
|
|
785
|
+
if s.endswith(x):
|
|
786
|
+
return s[:-len(x)]
|
|
787
|
+
return None
|
|
788
|
+
|
|
789
|
+
|
|
790
|
+
# ---------------------------------------------------------------- workflow records
|
|
791
|
+
|
|
792
|
+
def logical_lines(text):
|
|
793
|
+
out, buf, start = [], [], None
|
|
794
|
+
for n, line in enumerate(text.splitlines(), 1):
|
|
795
|
+
if start is None:
|
|
796
|
+
start = n
|
|
797
|
+
s = line.rstrip()
|
|
798
|
+
if s.endswith('\\'):
|
|
799
|
+
buf.append(s[:-1]); continue
|
|
800
|
+
buf.append(s)
|
|
801
|
+
out.append((start, ' '.join(buf).strip()))
|
|
802
|
+
buf, start = [], None
|
|
803
|
+
if buf:
|
|
804
|
+
out.append((start, ' '.join(buf).strip()))
|
|
805
|
+
return out
|
|
806
|
+
|
|
807
|
+
|
|
808
|
+
def describe_workflow_text(path, max_bytes=20_000_000):
|
|
809
|
+
try:
|
|
810
|
+
size = Path(path).stat().st_size
|
|
811
|
+
with opener(path)() as fh:
|
|
812
|
+
text = fh.read(max_bytes)
|
|
813
|
+
except (OSError, EOFError):
|
|
814
|
+
return {'integrity': 'unreadable'}
|
|
815
|
+
claims = []
|
|
816
|
+
for n, line in logical_lines(text):
|
|
817
|
+
if not line or line.lstrip().startswith('#!'):
|
|
818
|
+
continue
|
|
819
|
+
if line.lstrip().startswith('#') and not line.lstrip().startswith('#SBATCH'):
|
|
820
|
+
continue
|
|
821
|
+
claims.append({'line': n, 'command': line[:4000]})
|
|
822
|
+
return {'claims': claims, 'truncated_read': size > max_bytes}
|
|
823
|
+
|
|
824
|
+
|
|
825
|
+
def describe_snakemake_record(path):
|
|
826
|
+
""".snakemake/metadata/<base64(output path)>: JSON with input files and shell command."""
|
|
827
|
+
try:
|
|
828
|
+
d = json.loads(Path(path).read_text(errors='replace'))
|
|
829
|
+
except ValueError:
|
|
830
|
+
return {'integrity': 'invalid: not JSON'}
|
|
831
|
+
p = Path(path)
|
|
832
|
+
parts = [p.name]
|
|
833
|
+
for parent in p.parents: # long ids are split into '@'-prefixed directories
|
|
834
|
+
if parent.name.startswith('@'):
|
|
835
|
+
parts.insert(0, parent.name[1:])
|
|
836
|
+
else:
|
|
837
|
+
break
|
|
838
|
+
name = ''.join(parts)
|
|
839
|
+
try:
|
|
840
|
+
output = base64.urlsafe_b64decode(name + '=' * (-len(name) % 4)).decode('utf-8', 'replace')
|
|
841
|
+
except Exception:
|
|
842
|
+
output = None
|
|
843
|
+
return {'record': {'output': output, 'input': d.get('input') or [], 'shellcmd': d.get('shellcmd'),
|
|
844
|
+
'rule': d.get('rule'), 'starttime': d.get('starttime'), 'endtime': d.get('endtime')}}
|
|
845
|
+
|
|
846
|
+
|
|
847
|
+
NEXTFLOW_OUTPUTS = 2000
|
|
848
|
+
|
|
849
|
+
|
|
850
|
+
def _file_identity(p):
|
|
851
|
+
"""(size, SHA-256) of a file up to 512 MB, as the scan records it; (size, None) beyond."""
|
|
852
|
+
size = p.stat().st_size
|
|
853
|
+
if size >= (512 << 20):
|
|
854
|
+
return [size, None]
|
|
855
|
+
h = hashlib.sha256()
|
|
856
|
+
with open(p, 'rb') as fh:
|
|
857
|
+
for b in iter(lambda: fh.read(1 << 20), b''):
|
|
858
|
+
h.update(b)
|
|
859
|
+
return [size, h.hexdigest()]
|
|
860
|
+
|
|
861
|
+
|
|
862
|
+
def describe_nextflow_task(path):
|
|
863
|
+
"""A Nextflow task directory (work/xx/hash/): its script, process name, exit code, staged inputs
|
|
864
|
+
(symlinks, resolved) and the files it wrote, with size and SHA-256 to find published copies."""
|
|
865
|
+
task = Path(path).parent
|
|
866
|
+
script = Path(path).read_text(errors='replace')
|
|
867
|
+
name = exitcode = None
|
|
868
|
+
run = task / '.command.run'
|
|
869
|
+
if run.is_file():
|
|
870
|
+
for line in open(run, errors='replace'):
|
|
871
|
+
m = re.match(r'#\s*NEXTFLOW TASK:\s*(.+)', line)
|
|
872
|
+
if m:
|
|
873
|
+
name = m.group(1).strip(); break
|
|
874
|
+
if (task / '.exitcode').is_file():
|
|
875
|
+
exitcode = (task / '.exitcode').read_text(errors='replace').strip()
|
|
876
|
+
inputs, outputs = [], {}
|
|
877
|
+
for p in sorted(task.iterdir()):
|
|
878
|
+
if p.name.startswith('.command') or p.name == '.exitcode':
|
|
879
|
+
continue
|
|
880
|
+
if p.is_symlink():
|
|
881
|
+
inputs.append([p.name, os.path.realpath(p)])
|
|
882
|
+
elif p.is_file():
|
|
883
|
+
outputs[str(p.resolve())] = _file_identity(p)
|
|
884
|
+
elif p.is_dir():
|
|
885
|
+
for q in sorted(p.rglob('*')):
|
|
886
|
+
if len(outputs) >= NEXTFLOW_OUTPUTS:
|
|
887
|
+
break
|
|
888
|
+
if q.is_file() and not q.is_symlink():
|
|
889
|
+
outputs[str(q.resolve())] = _file_identity(q)
|
|
890
|
+
return {'record': {'rule': name, 'shellcmd': script, 'task_dir': str(task), 'exitcode': exitcode,
|
|
891
|
+
'inputs_abs': inputs, 'outputs': outputs}}
|
|
892
|
+
|
|
893
|
+
|
|
894
|
+
def describe_tool_params(path):
|
|
895
|
+
try:
|
|
896
|
+
d = json.loads(Path(path).read_text(errors='replace'))
|
|
897
|
+
except ValueError:
|
|
898
|
+
return {'integrity': 'invalid: not JSON'}
|
|
899
|
+
found = []
|
|
900
|
+
|
|
901
|
+
def walk(x):
|
|
902
|
+
if isinstance(x, dict):
|
|
903
|
+
for v in x.values():
|
|
904
|
+
walk(v)
|
|
905
|
+
elif isinstance(x, list):
|
|
906
|
+
for v in x:
|
|
907
|
+
walk(v)
|
|
908
|
+
elif isinstance(x, str) and ('/' in x or '.' in x):
|
|
909
|
+
found.append(x)
|
|
910
|
+
walk(d)
|
|
911
|
+
return {'claims': [{'line': 0, 'command': ' '.join(found)}] if found else []}
|
|
912
|
+
|
|
913
|
+
|
|
914
|
+
# ---------------------------------------------------------------- generic contig tables
|
|
915
|
+
|
|
916
|
+
def sniff_table(path, all_names, max_lines=50000):
|
|
917
|
+
"""Contig-name column (and exact length column) of an arbitrary table, or None."""
|
|
918
|
+
rows = []
|
|
919
|
+
try:
|
|
920
|
+
with opener(path)() as fh:
|
|
921
|
+
for i, line in enumerate(fh):
|
|
922
|
+
if i >= max_lines:
|
|
923
|
+
break
|
|
924
|
+
if not line.strip() or line.startswith('#'):
|
|
925
|
+
continue
|
|
926
|
+
rows.append(line.rstrip('\r\n'))
|
|
927
|
+
except (OSError, EOFError, UnicodeError):
|
|
928
|
+
return None
|
|
929
|
+
if len(rows) < 1 or not all_names:
|
|
930
|
+
return None
|
|
931
|
+
delim = '\t' if sum('\t' in r for r in rows) > 0.8 * len(rows) else (',' if sum(',' in r for r in rows) > 0.8 * len(rows) else None)
|
|
932
|
+
table = [r.split(delim) if delim else r.split() for r in rows]
|
|
933
|
+
width = max(len(r) for r in table)
|
|
934
|
+
best = None
|
|
935
|
+
for j in range(width):
|
|
936
|
+
col = [r[j].strip() for r in table if len(r) > j]
|
|
937
|
+
hits = [c for c in col if c in all_names]
|
|
938
|
+
if len(hits) >= max(1, 0.9 * (len(col) - 1)) and len(set(hits)) >= min(3, len(all_names)):
|
|
939
|
+
if all(h.isdigit() for h in hits) and not re.search(r'chr|seq|contig|scaff|name|target|query|ref', rows[0], re.I):
|
|
940
|
+
continue
|
|
941
|
+
if best is None or len(hits) > best[1]:
|
|
942
|
+
best = (j, len(hits))
|
|
943
|
+
if best is None:
|
|
944
|
+
return None
|
|
945
|
+
j = best[0]
|
|
946
|
+
names = [r[j].strip() for r in table if len(r) > j and r[j].strip() in all_names]
|
|
947
|
+
numeric = {}
|
|
948
|
+
for k in range(width):
|
|
949
|
+
if k == j:
|
|
950
|
+
continue
|
|
951
|
+
vals = {}
|
|
952
|
+
for r in table:
|
|
953
|
+
if len(r) > max(j, k) and r[j].strip() in all_names and r[k].strip().isdigit():
|
|
954
|
+
vals.setdefault(r[j].strip(), int(r[k].strip()))
|
|
955
|
+
if len(vals) >= 0.9 * len(set(names)):
|
|
956
|
+
numeric[k] = vals
|
|
957
|
+
return {'names': list(dict.fromkeys(names)), 'numeric_columns': list(numeric.values())}
|