gcheck 0.4.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.

Potentially problematic release.


This version of gcheck might be problematic. Click here for more details.

gcheck/__init__.py ADDED
@@ -0,0 +1,1030 @@
1
+ #!/usr/bin/env python3
2
+ """gcheck: check that genome input files agree with each other.
3
+
4
+ Give it every file of an analysis; it works out which is which:
5
+
6
+ gcheck genome.fa genes.gtf peaks.bed calls.vcf.gz sample.bam
7
+
8
+ Every file is checked against the reference genome FASTA for: chromosome
9
+ names (chr1 vs 1, NC_000001.11 with --alias), chromosome lengths and order,
10
+ sequence content (VCF REF alleles, BAM @SQ M5 checksums), coordinates past
11
+ the chromosome end, 0- vs 1-based mistakes, duplicate and missing IDs,
12
+ transcripts split across chromosomes, malformed or corrupted lines, plain
13
+ gzip where bgzip is needed, stale indexes, and transcript IDs between a GTF
14
+ and a transcriptome FASTA.
15
+
16
+ Exit code: 0 all PASS, 1 any ERROR, 2 bad usage.
17
+ """
18
+ import argparse
19
+ import gzip
20
+ import hashlib
21
+ import json
22
+ import os
23
+ import re
24
+ import shutil
25
+ import struct
26
+ import subprocess
27
+ import sys
28
+ import zlib
29
+ from collections import Counter
30
+
31
+ __version__ = "0.4.0"
32
+ MAX_SHOWN = 5
33
+
34
+ KINDS = {
35
+ "fasta": (".fa", ".fasta", ".fna", ".fas", ".faa", ".ffn", ".fai"),
36
+ "gtf": (".gtf",),
37
+ "gff": (".gff", ".gff3"),
38
+ "bed": (".bed", ".narrowpeak", ".broadpeak", ".bedgraph", ".bdg"),
39
+ "vcf": (".vcf",),
40
+ "bcf": (".bcf",),
41
+ "bam": (".bam",),
42
+ "cram": (".cram",),
43
+ "sam": (".sam",),
44
+ }
45
+ # files that sit next to inputs and are fine to ignore when a whole folder is passed
46
+ SIDECARS = (".tbi", ".csi", ".bai", ".crai", ".amb", ".ann", ".bwt", ".pac", ".sa", ".dict", ".gzi", ".md5")
47
+ INDEXES = {"bam": (".bai", ".csi"), "cram": (".crai",), "vcf": (".tbi", ".csi"), "bcf": (".csi",),
48
+ "gtf": (".tbi", ".csi"), "gff": (".tbi", ".csi"), "bed": (".tbi", ".csi")}
49
+ BUILDS_TSV = os.path.join(os.path.dirname(os.path.abspath(__file__)), "builds.tsv")
50
+ MODEL_CAP = 5000 # transcripts sampled per file for the splice-site/codon test
51
+ STARTS, STOPS = ("ATG", "GTG", "TTG"), ("TAA", "TAG", "TGA")
52
+ COMP = str.maketrans("ACGTN", "TGCAN")
53
+ PARENT = re.compile(r"(?:^|;)\s*Parent=([^;,]+)")
54
+ GFF_ID = re.compile(r"(?:^|;)\s*ID=([^;,]+)")
55
+ # alt haplotypes, fix/novel patches, unplaced/unlocalised scaffolds, decoys: often absent from analysis-set FASTAs
56
+ MINOR_CONTIG = re.compile(r"_alt$|_fix$|_random$|^chrUn|^Un_|_hap\d|decoy|^HLA-|^(GL|KI|KN|KQ|KV|KZ|ML|MU|JH)\d+", re.I)
57
+ BGZF_EOF = bytes.fromhex("1f8b08040000000000ff0600424302001b0003000000000000000000")
58
+ GENE_ID = re.compile(r'(?:^|;)\s*gene_id\s+(?:"([^"]*)"|([^;\s]*))')
59
+ TX_ID = re.compile(r'(?:^|;)\s*transcript_id\s+(?:"([^"]*)"|([^;\s]*))')
60
+
61
+
62
+ def kind_of(path):
63
+ p = path.lower()
64
+ for z in (".gz", ".bgz", ".bgzf"):
65
+ if p.endswith(z):
66
+ p = p[: -len(z)]
67
+ for kind, exts in KINDS.items():
68
+ if p.endswith(exts):
69
+ return kind
70
+ return None
71
+
72
+
73
+ def gz_type(path):
74
+ """None for uncompressed, 'bgzf' for bgzip, 'gzip' for plain gzip (judged by content)."""
75
+ with open(path, "rb") as f:
76
+ h = f.read(18)
77
+ if h[:2] != b"\x1f\x8b":
78
+ return None
79
+ return "bgzf" if len(h) >= 14 and h[3] & 4 and h[12:14] == b"BC" else "gzip"
80
+
81
+
82
+ def opener(path):
83
+ # newline="" keeps line numbers identical to sed/awk (a lone \r is not a line break)
84
+ if gz_type(path):
85
+ return gzip.open(path, "rt", errors="replace", newline="")
86
+ return open(path, errors="replace", newline="")
87
+
88
+
89
+ def text_lines(rep, src, f):
90
+ """Numbered lines; stops with one ERROR at the first binary/corrupted line or a cut-off .gz."""
91
+ i = 0
92
+ try:
93
+ for i, line in enumerate(f, 1):
94
+ if "\x00" in line or "�" in line:
95
+ rep.add("ERROR", src, f"file is corrupted or binary from line {i} on (truncated download? "
96
+ "uncompressed .gz?); stopped reading")
97
+ return
98
+ yield i, line
99
+ except (EOFError, OSError, zlib.error) as e:
100
+ rep.add("ERROR", src, f"compressed data ends or breaks after line {i} (truncated download?): {e}")
101
+
102
+
103
+ def attr(regex, text):
104
+ m = regex.search(text)
105
+ return None if m is None else (m.group(1) if m.group(1) is not None else m.group(2))
106
+
107
+
108
+ def revcomp(s):
109
+ return s.translate(COMP)[::-1]
110
+
111
+
112
+ def load_builds():
113
+ """{build: {"sizes": {ucsc_name: length}, "alias": {any_name: ucsc_name}, "lens": set}} from bundled UCSC tables."""
114
+ builds = {}
115
+ with open(BUILDS_TSV) as f:
116
+ for line in f:
117
+ if line.startswith("#") or not line.strip():
118
+ continue
119
+ b, n, ln, al = line.rstrip("\n").split("\t")
120
+ d = builds.setdefault(b, {"sizes": {}, "alias": {}, "lens": set()})
121
+ d["sizes"][n] = int(ln)
122
+ d["lens"].add(int(ln))
123
+ for a in [n] + [x for x in al.split(",") if x]:
124
+ d["alias"][a] = n
125
+ return builds
126
+
127
+
128
+ def identify_build(builds, lengths):
129
+ """Known build whose lengths match >= 90% of the sequences >= 1 Mb (names ignored); None if unclear."""
130
+ big = [l for l in lengths.values() if l and l >= 1000000]
131
+ if not big or not builds:
132
+ return None
133
+ best = max(builds, key=lambda b: sum(l in builds[b]["lens"] for l in big))
134
+ return best if sum(l in builds[best]["lens"] for l in big) >= 0.9 * len(big) else None
135
+
136
+
137
+ def norm(name):
138
+ """Name with style differences removed: chr1/Chr1/1 -> 1, chrM/MT -> M."""
139
+ n = re.sub(r"^chr", "", name, flags=re.I)
140
+ return "M" if n.upper() in ("M", "MT") else n
141
+
142
+
143
+ def strip_version(tx):
144
+ return re.sub(r"\.\d+$", "", tx.split("|")[0])
145
+
146
+
147
+ def int_or_none(s):
148
+ try:
149
+ return int(s)
150
+ except ValueError:
151
+ return None
152
+
153
+
154
+ class Report:
155
+ def __init__(self):
156
+ self.issues, self.errors, self.bad_files = [], 0, set()
157
+ self.ref, self.genome, self.alias = {}, None, {}
158
+ self.builds, self.ref_build, self.ucsc_to_ref = {}, None, {}
159
+ self.stats = {} # per-file measurements, shown with --json
160
+
161
+ def set_reference(self, genome):
162
+ self.genome, self.ref = genome, genome.lengths if genome else {}
163
+ try:
164
+ self.builds = load_builds()
165
+ except OSError:
166
+ self.builds = {} # tables missing (e.g. run from a bare copy): name/length checks still work
167
+ self.ref_build = identify_build(self.builds, self.ref)
168
+ if self.ref_build:
169
+ alias = self.builds[self.ref_build]["alias"]
170
+ self.ucsc_to_ref = {alias[n]: n for n in self.ref if n in alias}
171
+
172
+ def add(self, level, src, msg, examples=()):
173
+ examples = [str(e) for e in examples]
174
+ self.issues.append({"level": level, "file": src.split(" (")[0], "where": src, "message": msg,
175
+ "count": len(examples), "examples": examples[:MAX_SHOWN]})
176
+ self.errors += level == "ERROR"
177
+ self.bad_files.add(src.split(" (")[0])
178
+
179
+ def text(self):
180
+ for it in self.issues:
181
+ msg = it["message"]
182
+ if it["examples"]:
183
+ more = f" (+{it['count'] - MAX_SHOWN} more)" if it["count"] > MAX_SHOWN else ""
184
+ msg += ": " + ", ".join(it["examples"]) + more
185
+ yield f"{it['level']:5} {it['where']}: {msg}"
186
+
187
+
188
+ # ---------- reference genome ----------
189
+
190
+ class Genome:
191
+ """Sequence names and lengths in FASTA order, plus random access to bases when possible."""
192
+ MAX_IN_MEMORY = 300 * 2 ** 20 # compressed FASTAs up to this size are loaded for base checks
193
+
194
+ def __init__(self, path, rep=None):
195
+ self.path, self.lengths, self.index, self.seqs, self._fh = path, {}, {}, None, None
196
+ self._rep, self._src = rep, os.path.basename(path)
197
+ if path.endswith(".fai"):
198
+ self._read_fai(path, offsets=False)
199
+ return
200
+ gz, fai = gz_type(path), path + ".fai"
201
+ fai_ok = os.path.exists(fai)
202
+ if fai_ok and os.path.getmtime(fai) < os.path.getmtime(path):
203
+ self._warn("WARN", ".fai is older than the FASTA; ignored it and read the FASTA")
204
+ fai_ok = False
205
+ if gz:
206
+ # .fai offsets point into the uncompressed text, so compressed files are read whole instead
207
+ if os.path.getsize(path) <= self.MAX_IN_MEMORY or not fai_ok:
208
+ self._scan(load=os.path.getsize(path) <= self.MAX_IN_MEMORY)
209
+ else:
210
+ self._read_fai(fai, offsets=False)
211
+ elif fai_ok:
212
+ self._read_fai(fai, offsets=True)
213
+ else:
214
+ self._scan(load=False)
215
+ self._check_alphabet()
216
+
217
+ def _check_alphabet(self):
218
+ """A protein FASTA passed as the genome: letters outside the nucleotide IUPAC codes."""
219
+ first = next(iter(self.lengths), None)
220
+ sample = self.fetch(first, 0, 10000) if first is not None and self.can_fetch else None
221
+ if sample:
222
+ odd = sum(ch not in "ACGTUNRYSWKMBDHV-*" for ch in sample.upper())
223
+ if odd > len(sample) * 0.1:
224
+ self._warn("ERROR", f"looks like a protein FASTA, not a nucleotide genome "
225
+ f"({odd} of the first {len(sample)} letters are not nucleotide codes)")
226
+
227
+ def _warn(self, level, msg, examples=()):
228
+ if self._rep:
229
+ self._rep.add(level, self._src, msg, examples)
230
+
231
+ def _read_fai(self, fai, offsets):
232
+ with open(fai) as f:
233
+ for line in f:
234
+ c = line.rstrip("\r\n").split("\t")
235
+ if len(c) >= 2 and c[1].isdigit():
236
+ self.lengths[c[0]] = int(c[1])
237
+ if offsets and len(c) >= 5 and all(x.isdigit() for x in c[2:5]):
238
+ self.index[c[0]] = (int(c[2]), int(c[3]), int(c[4]))
239
+
240
+ def _scan(self, load):
241
+ """Read the FASTA once: lengths, a faidx-style index (uncompressed only), sanity checks."""
242
+ gz = gz_type(self.path)
243
+ seqs = {} if load else None
244
+ dups, bad_chars, cur, off = [], [], None, 0
245
+ with (gzip.open if gz else open)(self.path, "rb") as f:
246
+ for raw in self._guard_eof(f):
247
+ if raw[:1] == b">":
248
+ self._close(cur, gz)
249
+ name = raw[1:].split()[0].decode(errors="replace") if raw[1:].strip() else ""
250
+ if name in self.lengths:
251
+ dups.append(name)
252
+ self.lengths[name] = 0
253
+ cur = {"name": name, "off": off + len(raw), "lb": None, "lw": None, "short": False, "ok": True}
254
+ if load:
255
+ seqs[name] = []
256
+ elif cur is not None:
257
+ s = raw.rstrip(b"\r\n")
258
+ n = len(s)
259
+ if n:
260
+ if cur["lb"] is None:
261
+ cur["lb"], cur["lw"] = n, len(raw)
262
+ elif cur["short"] or n > cur["lb"] or (n == cur["lb"] and len(raw) != cur["lw"]):
263
+ cur["ok"] = False # uneven line lengths: samtools faidx would refuse too
264
+ elif n < cur["lb"]:
265
+ cur["short"] = True
266
+ t = s.translate(None, b"*-.") # stop and gap symbols are legal
267
+ if t and not t.isalpha():
268
+ bad_chars.append(cur["name"])
269
+ self.lengths[cur["name"]] += n
270
+ if load:
271
+ seqs[cur["name"]].append(s)
272
+ else:
273
+ cur["short"] = True # blank line inside a sequence
274
+ elif raw.strip():
275
+ self._warn("ERROR", "text before the first '>' header (not a FASTA file?)")
276
+ return
277
+ off += len(raw)
278
+ self._close(cur, gz)
279
+ if load:
280
+ self.seqs = {k: b"".join(v).decode(errors="replace") for k, v in seqs.items()}
281
+ if dups:
282
+ self._warn("ERROR", f"{len(dups)} duplicate sequence names (indexers will fail)", dups)
283
+ empty = [n for n, l in self.lengths.items() if l == 0]
284
+ if empty:
285
+ self._warn("WARN", f"{len(empty)} empty sequences", empty)
286
+ if "" in self.lengths:
287
+ self._warn("ERROR", "a '>' header line has no name")
288
+ if bad_chars:
289
+ self._warn("ERROR", "sequence lines contain characters that are not letters (spaces, digits?)",
290
+ sorted(set(bad_chars)))
291
+ uneven = [n for n in self.lengths if n not in self.index] if not gz else []
292
+ if uneven:
293
+ self._warn("WARN", "uneven line lengths; samtools faidx will refuse to index", uneven)
294
+
295
+ def _guard_eof(self, f):
296
+ try:
297
+ yield from f
298
+ except (EOFError, OSError, zlib.error) as e:
299
+ self._warn("ERROR", f"compressed data ends early (truncated download?); later sequences missing: {e}")
300
+
301
+ def _close(self, cur, gz):
302
+ if cur and cur["ok"] and not gz:
303
+ self.index[cur["name"]] = (cur["off"], cur["lb"] or 0, cur["lw"] or 0)
304
+
305
+ @property
306
+ def can_fetch(self):
307
+ return self.seqs is not None or bool(self.index)
308
+
309
+ def fetch(self, name, start, end):
310
+ """Bases [start, end) 0-based, or None when not available."""
311
+ if self.seqs is not None:
312
+ s = self.seqs.get(name)
313
+ return None if s is None else s[start:end]
314
+ ix = self.index.get(name)
315
+ if not ix or not ix[1]:
316
+ return None
317
+ off, lb, lw = ix
318
+ end = min(end, self.lengths[name])
319
+ if start >= end:
320
+ return ""
321
+ if self._fh is None:
322
+ self._fh = open(self.path, "rb")
323
+ pos = lambda x: off + (x // lb) * lw + x % lb
324
+ self._fh.seek(pos(start))
325
+ return self._fh.read(pos(end - 1) - pos(start) + 1).replace(b"\n", b"").replace(b"\r", b"").decode(errors="replace")
326
+
327
+ def close(self):
328
+ if self._fh:
329
+ self._fh.close()
330
+ self._fh = None
331
+
332
+ def md5(self, name):
333
+ s = self.fetch(name, 0, self.lengths.get(name, 0))
334
+ return None if s is None else hashlib.md5(s.upper().encode()).hexdigest()
335
+
336
+
337
+ # ---------- shared checks ----------
338
+
339
+ def check_names(rep, src, names, lengths=None):
340
+ """Names missing from the reference, split into: a rename fixes it (--alias, bundled UCSC alias
341
+ tables for the FASTA's build, chr/MT style, or a unique same-length sequence), the name belongs
342
+ to a different known build, or the name is unknown."""
343
+ ref = rep.ref
344
+ missing = [n for n in names if n not in ref]
345
+ if not missing:
346
+ return
347
+ by_norm = {norm(r): r for r in ref}
348
+ ref_alias = rep.builds[rep.ref_build]["alias"] if rep.ref_build else {}
349
+ renames, other_build, absent, minor = [], [], [], []
350
+ for n in missing:
351
+ target = (next((a for a in sorted(rep.alias.get(n, ())) if a in ref), None)
352
+ or rep.ucsc_to_ref.get(ref_alias.get(n)) or by_norm.get(norm(n)))
353
+ if not target and lengths and lengths.get(n):
354
+ same = [r for r, l in ref.items() if l == lengths[n]]
355
+ target = same[0] if len(same) == 1 else None
356
+ if target:
357
+ renames.append(f"{n}->{target}")
358
+ continue
359
+ builds = [b for b, d in rep.builds.items() if b != rep.ref_build and n in d["alias"]]
360
+ if MINOR_CONTIG.search(n):
361
+ minor.append(n) # a contig analysis-set FASTAs often leave out: tools skip features on it
362
+ elif rep.ref_build and builds and n not in ref_alias: # a name of this build is just missing, not foreign
363
+ other_build.append(f"{n} ({builds[0]})")
364
+ else:
365
+ absent.append(n)
366
+ if renames:
367
+ rep.add("ERROR", src, f"{len(renames)} chromosome names differ from the FASTA (rename)", renames)
368
+ if other_build:
369
+ rep.add("ERROR", src, f"{len(other_build)} chromosome names belong to another genome build, the FASTA is "
370
+ f"{rep.ref_build}: renaming will not fix this", other_build)
371
+ if minor:
372
+ rep.add("WARN", src, f"{len(minor)} alt/patch/unplaced contigs are not in the FASTA; features on them "
373
+ "will be ignored by most tools", minor)
374
+ if absent:
375
+ hint = " (none match: wrong reference, or try --alias)" if len(absent) == len(names) else ""
376
+ rep.add("ERROR", src, f"{len(absent)} chromosomes not in the FASTA{hint}", absent)
377
+
378
+
379
+ def check_lengths(rep, src, declared):
380
+ bad = [f"{n} {l}!={rep.ref[n]}" for n, l in declared.items() if n in rep.ref and l and l != rep.ref[n]]
381
+ if bad:
382
+ file_build = identify_build(rep.builds, declared)
383
+ which = f" (file is {file_build}, FASTA is {rep.ref_build})" if file_build and rep.ref_build else ""
384
+ rep.add("ERROR", src, f"chromosome lengths differ from the FASTA: different genome build{which}", bad)
385
+
386
+
387
+ def check_order(rep, src, names):
388
+ common = set(names) & set(rep.ref)
389
+ if [n for n in names if n in common] != [n for n in rep.ref if n in common]:
390
+ rep.add("WARN", src, "chromosome order differs from the FASTA (GATK/Picard require the same order)")
391
+
392
+
393
+ def report_common(rep, src, chroms, past_end, malformed, lengths=None):
394
+ check_names(rep, src, sorted(chroms), lengths)
395
+ if past_end:
396
+ rep.add("ERROR", src, f"{len(past_end)} features end past the chromosome end (wrong build?)", past_end)
397
+ if malformed:
398
+ rep.add("ERROR", src, f"{len(malformed)} malformed lines", malformed)
399
+
400
+
401
+ def check_file_level(rep, path, kind):
402
+ """Compression and index problems that tools hit before reading a single record."""
403
+ src = os.path.basename(path)
404
+ gz = gz_type(path)
405
+ if gz == "bgzf" or kind in ("bam", "bcf"):
406
+ with open(path, "rb") as f:
407
+ f.seek(max(0, os.path.getsize(path) - len(BGZF_EOF)))
408
+ if f.read() != BGZF_EOF:
409
+ rep.add("ERROR", src, "no BGZF end-of-file marker: the file is truncated (incomplete copy or "
410
+ "download, or the writing program crashed)")
411
+ if kind in ("vcf", "gtf", "gff", "bed", "fasta") and gz == "gzip":
412
+ rep.add("WARN", src, "compressed with plain gzip, not bgzip: tabix/samtools faidx cannot index it "
413
+ "(fix: zcat FILE | bgzip > FILE.gz)")
414
+ for ext in INDEXES.get(kind, ()):
415
+ for idx in {path + ext, os.path.splitext(path)[0] + ext}:
416
+ if os.path.exists(idx) and os.path.getmtime(idx) < os.path.getmtime(path):
417
+ rep.add("WARN", src, f"index {os.path.basename(idx)} is older than the file; re-index it")
418
+
419
+
420
+ # ---------- sequence checks for annotations (no sequence of their own) ----------
421
+
422
+ def add_model(models, key, chrom, strand, part, start0, end0):
423
+ """Collect exon/CDS parts per transcript (0-based half-open), sampling at most MODEL_CAP transcripts."""
424
+ if key and (key in models or len(models) < MODEL_CAP):
425
+ m = models.setdefault(key, (chrom, strand, [], []))
426
+ if m[0] == chrom and m[1] == strand:
427
+ m[2 if part == "exon" else 3].append((start0, end0))
428
+
429
+
430
+ def check_models(rep, src, models):
431
+ """Gene models against the genome: introns should read GT..AG and CDSs start ATG/GTG/TTG and end in a stop.
432
+ A correct annotation scores ~90-99%, a wrong build or assembly ~5-20%. Signals tied to feature
433
+ start coordinates and to end coordinates are scored separately at shifts -1/0/+1, which pinpoints
434
+ 0- vs 1-based mistakes on either side."""
435
+ g = rep.genome
436
+ if not models or not g:
437
+ return
438
+ if not g.can_fetch:
439
+ rep.add("WARN", src, "splice-site/codon check skipped: the FASTA is a large compressed file or has uneven "
440
+ "lines (use an uncompressed FASTA with a .fai)")
441
+ return
442
+ tests = [] # (side, chrom, positions, k, accepted): side "s" depends on starts, "e" on ends
443
+ for chrom, strand, exons, cds in models:
444
+ if chrom not in rep.ref or strand not in ("+", "-"):
445
+ continue
446
+ ex = sorted(exons)
447
+ for (_, e1), (s2, _) in zip(ex, ex[1:]):
448
+ if s2 - e1 < 20:
449
+ continue # too short to be a real intron
450
+ plus = strand == "+"
451
+ tests.append(("e", chrom, (e1,), 2, ("GT", "GC") if plus else ("CT",)))
452
+ tests.append(("s", chrom, (s2 - 2,), 2, ("AG",) if plus else ("AC", "GC")))
453
+ if cds:
454
+ s, e = min(c[0] for c in cds), max(c[1] for c in cds)
455
+ if e - s < 6:
456
+ continue
457
+ if strand == "+": # stop codon may be inside or just after the CDS (GTF excludes it, GFF3 includes it)
458
+ tests += [("s", chrom, (s,), 3, STARTS), ("e", chrom, (e - 3, e), 3, STOPS)]
459
+ else:
460
+ tests += [("e", chrom, (e - 3,), 3, tuple(map(revcomp, STARTS))),
461
+ ("s", chrom, (s, s - 3), 3, tuple(map(revcomp, STOPS)))]
462
+ rates = {}
463
+ for side in "se":
464
+ for shift in (-1, 0, 1):
465
+ ok = n = 0
466
+ for t_side, chrom, poss, k, acc in tests:
467
+ if t_side != side:
468
+ continue
469
+ seqs = [g.fetch(chrom, p + shift, p + shift + k) for p in poss if p + shift >= 0]
470
+ seqs = [x.upper() for x in seqs if x and len(x) == k and "N" not in x.upper()]
471
+ if seqs:
472
+ n += 1
473
+ ok += any(x in acc for x in seqs)
474
+ rates[side, shift] = (ok / n if n else 0.0, n)
475
+ usable = [s for s in "se" if rates[s, 0][1] >= 20]
476
+ if not usable:
477
+ return
478
+ name = {"s": "start", "e": "end"}
479
+ rep.stats.setdefault(src, {})["gene_model_match"] = {
480
+ f"feature_{name[s]}s": {"rate": round(rates[s, 0][0], 3), "tested": rates[s, 0][1]} for s in usable}
481
+ detail = ", ".join(f"{rates[s, 0][0]:.0%} of {rates[s, 0][1]} at feature {name[s]}s" for s in usable)
482
+ shifted = {}
483
+ for s in usable:
484
+ best = max((-1, 0, 1), key=lambda sh: rates[s, sh][0])
485
+ if best and rates[s, best][0] >= 0.6 and rates[s, best][0] - rates[s, 0][0] >= 0.3:
486
+ shifted[s] = best
487
+ if shifted:
488
+ parts = [f"{name[s]} coordinates are 1 too {'low' if sh == 1 else 'high'} "
489
+ f"({rates[s, sh][0]:.0%} match after shifting)" for s, sh in shifted.items()]
490
+ rep.add("ERROR", src, "splice sites/codons only line up after shifting: " + "; ".join(parts)
491
+ + " (0-based vs 1-based mix-up)")
492
+ elif max(rates[s, 0][0] for s in usable) < 0.3:
493
+ rep.add("ERROR", src, f"gene models do not match the genome sequence (canonical splice sites/codons: "
494
+ f"{detail}; expected ~90-99%): wrong genome build or assembly?")
495
+ elif min(rates[s, 0][0] for s in usable) < 0.7:
496
+ rep.add("WARN", src, f"few canonical splice sites/codons ({detail}; expected ~90-99%): "
497
+ "partly wrong build, or unusual annotation?")
498
+
499
+
500
+ def check_gaps(rep, src, intervals):
501
+ """Intervals that lie entirely in assembly gaps (all N): no read or gene can be there in the right build."""
502
+ g = rep.genome
503
+ if not intervals or not g or not g.can_fetch:
504
+ return
505
+ gaps, n = [], 0
506
+ for chrom, s, e in intervals:
507
+ seq = g.fetch(chrom, s, e)
508
+ if seq:
509
+ n += 1
510
+ if not seq.upper().strip("N"):
511
+ gaps.append(f"{chrom}:{s}-{e}")
512
+ # right build: ~0 (nothing maps in N); wrong build: ~0.5%; > 50% means a gap/blacklist track itself
513
+ if len(gaps) >= 5 and 0.002 * n <= len(gaps) <= 0.5 * n:
514
+ rep.add("WARN", src, f"{len(gaps)} of {n} intervals lie entirely in assembly gaps (all N): "
515
+ "wrong genome build?", gaps)
516
+
517
+
518
+ # ---------- per-format checks ----------
519
+
520
+ def check_features(rep, path, gff3):
521
+ """GTF or GFF3: 1-based closed coordinates, 9 tab-separated columns."""
522
+ src, ref = os.path.basename(path), rep.ref
523
+ chroms, past_end, zero_start, bad_order, malformed, bad_strand, bad_phase = set(), [], [], [], [], [], []
524
+ no_gene, no_gene_lines, no_tx, empty_id, feats = Counter(), [], [], [], Counter()
525
+ ids = {"gene": Counter(), "transcript": Counter()}
526
+ tx_where, split_tx, tx_with_exon = {}, set(), set()
527
+ models = {}
528
+ with opener(path) as f:
529
+ for i, line in text_lines(rep, src, f):
530
+ if gff3 and line.startswith("##FASTA"):
531
+ break
532
+ if line.startswith("#") or not line.strip():
533
+ continue
534
+ c = line.rstrip("\r\n").split("\t")
535
+ start, end = (int_or_none(c[3]), int_or_none(c[4])) if len(c) >= 9 else (None, None)
536
+ if start is None or end is None:
537
+ malformed.append(f"line {i}")
538
+ continue
539
+ chrom, feat = c[0], c[2]
540
+ chroms.add(chrom)
541
+ feats[feat] += 1
542
+ if start < 1:
543
+ zero_start.append(f"line {i}")
544
+ if start > end:
545
+ bad_order.append(f"line {i}")
546
+ if chrom in ref and end > ref[chrom]:
547
+ past_end.append(f"{chrom}:{end}")
548
+ if c[6] not in ("+", "-", ".", "?"):
549
+ bad_strand.append(f"line {i} '{c[6]}'")
550
+ if c[7] not in ("0", "1", "2", "."):
551
+ bad_phase.append(f"line {i} '{c[7]}'")
552
+ if feat in ("exon", "CDS") and chrom in ref:
553
+ if gff3: # exons/CDS hang off their transcript via Parent; bare prokaryote CDSs only have ID
554
+ m = PARENT.search(c[8]) or GFF_ID.search(c[8])
555
+ key = m.group(1) if m else None
556
+ else:
557
+ key = attr(TX_ID, c[8])
558
+ add_model(models, key, chrom, c[6], feat, start - 1, end)
559
+ if gff3: # GFF3 IDs legally repeat across lines of one feature, so no ID checks
560
+ continue
561
+ gid, tid = attr(GENE_ID, c[8]), attr(TX_ID, c[8])
562
+ if gid is None:
563
+ no_gene[feat] += 1
564
+ no_gene_lines.append(f"line {i}")
565
+ if feat == "exon" and tid is None:
566
+ no_tx.append(f"line {i}")
567
+ if gid == "" or (tid == "" and feat != "gene"):
568
+ empty_id.append(f"line {i}")
569
+ if tid:
570
+ if tx_where.setdefault(tid, (chrom, c[6])) != (chrom, c[6]):
571
+ split_tx.add(tid)
572
+ if feat == "exon":
573
+ tx_with_exon.add(tid)
574
+ fid = gid if feat == "gene" else tid if feat == "transcript" else None
575
+ if fid:
576
+ ids[feat][fid] += 1
577
+ report_common(rep, src, chroms, past_end, malformed)
578
+ check_models(rep, src, models.values())
579
+ if zero_start:
580
+ rep.add("ERROR", src, "start < 1; GTF/GFF are 1-based (0-based coordinates pasted in?)", zero_start)
581
+ if bad_order:
582
+ rep.add("ERROR", src, "start > end", bad_order)
583
+ if bad_strand:
584
+ rep.add("ERROR", src, "strand (column 7) must be +, -, . or ?", bad_strand)
585
+ if bad_phase:
586
+ rep.add("ERROR", src, "phase/frame (column 8) must be 0, 1, 2 or .", bad_phase)
587
+ if no_gene:
588
+ kinds = ", ".join(f"{n} {k}" for k, n in no_gene.most_common())
589
+ rep.add("ERROR", src, f"rows without gene_id ({kinds}); GTF requires it on every row, "
590
+ f"featureCounts fails on them", no_gene_lines)
591
+ if not gff3 and feats and "exon" not in feats:
592
+ rep.add("WARN", src, f"no 'exon' rows (has {', '.join(k for k, _ in feats.most_common(4))}); STAR and "
593
+ "featureCounts use exon rows by default")
594
+ elif not gff3 and set(tx_where) - tx_with_exon:
595
+ no_exon = sorted(set(tx_where) - tx_with_exon)
596
+ rep.add("WARN", src, f"{len(no_exon)} of {len(tx_where)} transcripts have no exon rows; STAR and "
597
+ "featureCounts -t exon will give them zero counts", no_exon)
598
+ if no_tx:
599
+ rep.add("ERROR", src, f"{len(no_tx)} exon rows without transcript_id (STAR/salmon need it)", no_tx)
600
+ if empty_id:
601
+ rep.add("ERROR", src, f"{len(empty_id)} rows with an empty gene_id or transcript_id \"\"", empty_id)
602
+ if split_tx:
603
+ rep.add("ERROR", src, f"{len(split_tx)} transcript_ids used on more than one chromosome or strand",
604
+ sorted(split_tx))
605
+ for feat, cnt in ids.items():
606
+ dups = [k for k, v in cnt.items() if v > 1]
607
+ if dups:
608
+ rep.add("ERROR", src, f"{len(dups)} {feat}_id values used on more than one '{feat}' row", dups)
609
+ return set(tx_where)
610
+
611
+
612
+ def add_bed12(models, i, chrom, start, c):
613
+ """BED12 gene model: blocks are exons, thickStart..thickEnd is the CDS."""
614
+ try:
615
+ sizes = [int(x) for x in c[10].split(",") if x]
616
+ offsets = [int(x) for x in c[11].split(",") if x]
617
+ thick = (int(c[6]), int(c[7]))
618
+ except ValueError:
619
+ return
620
+ for size, off in zip(sizes, offsets):
621
+ add_model(models, i, chrom, c[5], "exon", start + off, start + off + size)
622
+ if thick[1] > thick[0]:
623
+ add_model(models, i, chrom, c[5], "CDS", thick[0], thick[1])
624
+
625
+
626
+ def check_bed(rep, path):
627
+ src, ref = os.path.basename(path), rep.ref
628
+ has_strand = not path.lower().replace(".gz", "").endswith((".bedgraph", ".bdg"))
629
+ chroms, past_end, one_based, neg, bad_order, malformed, bad_strand = set(), [], [], [], [], [], []
630
+ whole_but_first, models, intervals = [], {}, []
631
+ strand_used = False # BED-like tables (e.g. UCSC simpleRepeat) put other data in column 6
632
+ with opener(path) as f:
633
+ for i, line in text_lines(rep, src, f):
634
+ if line.startswith(("#", "track", "browser")) or not line.strip():
635
+ continue
636
+ c = line.rstrip("\r\n").split("\t")
637
+ if len(c) < 3:
638
+ c = line.split() # some BED files are space-separated
639
+ start, end = (int_or_none(c[1]), int_or_none(c[2])) if len(c) >= 3 else (None, None)
640
+ if start is None or end is None:
641
+ if i == 1:
642
+ continue # untagged column-header line
643
+ malformed.append(f"line {i}")
644
+ continue
645
+ chrom = c[0]
646
+ chroms.add(chrom)
647
+ if start < 0:
648
+ neg.append(f"line {i}")
649
+ if start > end:
650
+ bad_order.append(f"line {i}")
651
+ if has_strand and len(c) >= 6:
652
+ if c[5] in ("+", "-"):
653
+ strand_used = True
654
+ elif c[5] != ".":
655
+ bad_strand.append(f"line {i} '{c[5]}'")
656
+ if chrom in ref and end > ref[chrom]:
657
+ # end exactly one past the length is the classic 1-based off-by-one
658
+ (one_based if end == ref[chrom] + 1 else past_end).append(f"{chrom}:{end}")
659
+ elif chrom in ref and start == 1 and end == ref[chrom]:
660
+ whole_but_first.append(f"line {i} {chrom}:1-{end}")
661
+ if chrom in ref and 0 <= start < end <= ref[chrom]:
662
+ if end - start <= 100000 and len(intervals) < 20000:
663
+ intervals.append((chrom, start, end))
664
+ if len(c) >= 12 and c[5] in ("+", "-"):
665
+ add_bed12(models, i, chrom, start, c)
666
+ report_common(rep, src, chroms, past_end, malformed)
667
+ check_models(rep, src, models.values())
668
+ check_gaps(rep, src, intervals)
669
+ if one_based:
670
+ rep.add("ERROR", src, "end = chromosome length + 1; looks 1-based, BED is 0-based half-open", one_based)
671
+ if whole_but_first:
672
+ rep.add("WARN", src, "a whole-chromosome record starts at 1, not 0: converted from GFF/GTF/VCF "
673
+ "without start-1? (BED is 0-based)", whole_but_first)
674
+ if neg:
675
+ rep.add("ERROR", src, "negative start", neg)
676
+ if bad_order:
677
+ rep.add("ERROR", src, "start > end", bad_order)
678
+ if bad_strand and strand_used:
679
+ rep.add("ERROR", src, "strand (column 6) must be +, - or .", bad_strand)
680
+
681
+
682
+ def bases_match(a, b):
683
+ """Same length and equal at every A/C/G/T position (N and other IUPAC codes match anything)."""
684
+ return len(a) == len(b) and all(x == y or x not in "ACGT" or y not in "ACGT" for x, y in zip(a, b))
685
+
686
+
687
+ def check_vcf_lines(rep, src, lines):
688
+ ref, genome = rep.ref, rep.genome
689
+ header, chroms, past_end, zero_pos, malformed = {}, set(), [], [], []
690
+ ids = Counter()
691
+ checked, mismatched = 0, []
692
+ can_fetch = genome is not None and genome.can_fetch
693
+ for i, line in text_lines(rep, src, lines):
694
+ if line.startswith("##contig"):
695
+ m = re.search(r"ID=([^,>]+)", line)
696
+ ln = re.search(r"length=(\d+)", line)
697
+ if m:
698
+ header[m.group(1)] = int(ln.group(1)) if ln else None
699
+ continue
700
+ if line.startswith("#") or not line.strip():
701
+ continue
702
+ c = line.rstrip("\r\n").split("\t", 5)
703
+ pos = int_or_none(c[1]) if len(c) >= 5 else None
704
+ if pos is None:
705
+ malformed.append(f"line {i}")
706
+ continue
707
+ chrom, vid, ref_allele = c[0], c[2], c[3].upper()
708
+ chroms.add(chrom)
709
+ if pos < 1:
710
+ zero_pos.append(f"line {i}")
711
+ elif chrom in ref and pos > ref[chrom]:
712
+ past_end.append(f"{chrom}:{pos}")
713
+ elif can_fetch and chrom in ref and ref_allele.isalpha():
714
+ fa = genome.fetch(chrom, pos - 1, pos - 1 + len(ref_allele))
715
+ if fa is not None:
716
+ checked += 1
717
+ if not bases_match(ref_allele, fa.upper()):
718
+ mismatched.append(f"{chrom}:{pos} REF={ref_allele[:10]} FASTA={fa.upper()[:10]}")
719
+ if vid != ".":
720
+ for v in vid.split(";"):
721
+ ids[v] += 1
722
+ hsrc = src + " (##contig header)"
723
+ check_names(rep, hsrc, list(header), header)
724
+ check_lengths(rep, hsrc, header)
725
+ check_order(rep, hsrc, list(header))
726
+ report_common(rep, src, chroms, past_end, malformed, header)
727
+ if zero_pos:
728
+ rep.add("ERROR", src, "POS < 1; VCF is 1-based", zero_pos)
729
+ if mismatched:
730
+ rep.add("ERROR", src, f"{len(mismatched)} of {checked} REF alleles ({100 * len(mismatched) / checked:.1f}%) "
731
+ "differ from the FASTA (wrong build or shifted positions?)", mismatched)
732
+ if chroms and not can_fetch:
733
+ rep.add("WARN", src, "REF alleles not compared: the FASTA is a large compressed file or has uneven "
734
+ "lines (use an uncompressed FASTA with a .fai)")
735
+ dups = [k for k, v in ids.items() if v > 1]
736
+ if dups:
737
+ rep.add("WARN", src, f"{len(dups)} variant IDs used more than once", dups)
738
+
739
+
740
+ def check_vcf(rep, path):
741
+ with opener(path) as f:
742
+ check_vcf_lines(rep, os.path.basename(path), f)
743
+
744
+
745
+ _TOOL_OK = {}
746
+
747
+
748
+ def tool_problem(name):
749
+ """None if the tool runs; otherwise why not (missing, or installed but broken, e.g. a missing library)."""
750
+ if name not in _TOOL_OK:
751
+ if not shutil.which(name):
752
+ _TOOL_OK[name] = f"needs '{name}' on PATH"
753
+ else:
754
+ try:
755
+ r = subprocess.run([name, "--version"], capture_output=True, text=True, errors="replace", timeout=60)
756
+ _TOOL_OK[name] = None if r.returncode == 0 else \
757
+ f"'{name}' on PATH does not run ({(r.stderr.strip().splitlines() or ['exit %d' % r.returncode])[0][:150]})"
758
+ except (OSError, subprocess.TimeoutExpired) as e:
759
+ _TOOL_OK[name] = f"'{name}' on PATH does not run ({e})"
760
+ return _TOOL_OK[name]
761
+
762
+
763
+ def run_tool(rep, src, cmd):
764
+ """Run an optional external tool; None (with a WARN) if it is missing, broken or fails."""
765
+ problem = tool_problem(cmd[0])
766
+ if problem:
767
+ rep.add("WARN", src, f"{problem}; skipped")
768
+ return None
769
+ r = subprocess.run(cmd, capture_output=True, text=True, errors="replace")
770
+ if r.returncode:
771
+ rep.add("ERROR", src, f"{cmd[0]} could not read it: {r.stderr.strip()[:200]}")
772
+ return None
773
+ return r.stdout
774
+
775
+
776
+ def check_bcf(rep, path):
777
+ """Records are decoded by bcftools and streamed through the VCF checks (no full copy in memory)."""
778
+ src = os.path.basename(path)
779
+ problem = tool_problem("bcftools")
780
+ if problem:
781
+ rep.add("WARN", src, f"{problem}; skipped")
782
+ return
783
+ with subprocess.Popen(["bcftools", "view", path], stdout=subprocess.PIPE, stderr=subprocess.PIPE,
784
+ text=True, errors="replace") as p:
785
+ check_vcf_lines(rep, src, p.stdout)
786
+ err = p.stderr.read()
787
+ if p.returncode:
788
+ rep.add("ERROR", src, f"bcftools could not read it: {err.strip()[:200]}")
789
+
790
+
791
+ def bam_header(path):
792
+ """(header text, {name: length}) from a BAM; pure Python (BGZF is gzip)."""
793
+ with gzip.open(path, "rb") as f:
794
+ if f.read(4) != b"BAM\x01":
795
+ raise ValueError("not a BAM file (bad magic)")
796
+ (l_text,) = struct.unpack("<i", f.read(4))
797
+ text = f.read(l_text).rstrip(b"\0").decode(errors="replace")
798
+ (n_ref,) = struct.unpack("<i", f.read(4))
799
+ refs = {}
800
+ for _ in range(n_ref):
801
+ (l_name,) = struct.unpack("<i", f.read(4))
802
+ name = f.read(l_name).rstrip(b"\0").decode()
803
+ (refs[name],) = struct.unpack("<i", f.read(4))
804
+ return text, refs
805
+
806
+
807
+ def sq_tags(text):
808
+ """{SN: {tag: value}} from @SQ header lines, in order."""
809
+ sq = {}
810
+ for line in text.splitlines():
811
+ if line.startswith("@SQ"):
812
+ tags = dict(t.split(":", 1) for t in line.split("\t")[1:] if ":" in t)
813
+ if "SN" in tags:
814
+ sq[tags["SN"]] = tags
815
+ return sq
816
+
817
+
818
+ def check_alignments(rep, path, kind):
819
+ src = os.path.basename(path)
820
+ try:
821
+ if kind == "bam":
822
+ text, lengths = bam_header(path)
823
+ else:
824
+ if kind == "sam":
825
+ with opener(path) as f:
826
+ text = "".join(iter(lambda: _header_line(f), ""))
827
+ else:
828
+ text = run_tool(rep, src, ["samtools", "view", "-H", path])
829
+ if text is None:
830
+ return
831
+ lengths = {n: int_or_none(t.get("LN", "")) or 0 for n, t in sq_tags(text).items()}
832
+ except (OSError, ValueError, struct.error, EOFError) as e:
833
+ rep.add("ERROR", src, f"could not read the header: {e}")
834
+ return
835
+ if not lengths:
836
+ rep.add("WARN", src, "no reference sequences in the header (unaligned file?)")
837
+ return
838
+ hsrc = src + " (@SQ header)"
839
+ check_names(rep, hsrc, list(lengths), lengths)
840
+ check_lengths(rep, hsrc, lengths)
841
+ check_order(rep, hsrc, list(lengths))
842
+ genome, bad = rep.genome, []
843
+ for name, tags in sq_tags(text).items():
844
+ if "M5" in tags and name in rep.ref and genome and genome.can_fetch:
845
+ m = genome.md5(name)
846
+ if m and m != tags["M5"].lower():
847
+ bad.append(name)
848
+ if bad:
849
+ rep.add("ERROR", hsrc, "same names but different sequence content (M5 checksum differs)", bad)
850
+
851
+
852
+ def _header_line(f):
853
+ line = f.readline()
854
+ return line if line.startswith("@") else ""
855
+
856
+
857
+ def check_transcripts(rep, path, gtf_tx):
858
+ src = os.path.basename(path)
859
+ fa = set(Genome(path).lengths)
860
+ if not gtf_tx:
861
+ rep.add("WARN", src, "no GTF with transcript_id given; transcript check skipped")
862
+ return
863
+ only_fa, only_gtf = fa - gtf_tx, gtf_tx - fa
864
+ if only_fa and {strip_version(x) for x in fa} & {strip_version(x) for x in gtf_tx}:
865
+ rep.add("ERROR", src, "transcript IDs match the GTF only after removing version or '|' suffixes",
866
+ sorted(only_fa))
867
+ elif only_fa:
868
+ rep.add("ERROR", src, f"{len(only_fa)} transcripts not in the GTF", sorted(only_fa))
869
+ elif only_gtf:
870
+ rep.add("WARN", src, f"{len(only_gtf)} GTF transcripts missing from this FASTA", sorted(only_gtf))
871
+
872
+
873
+ # ---------- driver ----------
874
+
875
+ def read_alias(path):
876
+ """Each line lists equivalent names (UCSC chromAlias.txt, NCBI-style tables, or a 2-column map)."""
877
+ alias = {}
878
+ with opener(path) as f:
879
+ for line in f:
880
+ if line.startswith("#") or not line.strip():
881
+ continue
882
+ names = [n for n in re.split(r"[\t,]", line.rstrip("\r\n")) if n and n != "na"]
883
+ for n in names:
884
+ alias.setdefault(n, set()).update(names)
885
+ return alias
886
+
887
+
888
+ def expand(paths):
889
+ """Files as given, plus recognised files inside any folders given."""
890
+ out = []
891
+ for p in paths:
892
+ if os.path.isdir(p):
893
+ for root, _, names in os.walk(p):
894
+ out += [os.path.join(root, n) for n in sorted(names)
895
+ if kind_of(n) and not n.lower().endswith(".fai")]
896
+ else:
897
+ out.append(p)
898
+ return out
899
+
900
+
901
+ def gtf_transcript_ids(paths):
902
+ tx = set()
903
+ for g in paths:
904
+ with opener(g) as f:
905
+ for line in f:
906
+ t = attr(TX_ID, line.split("\t", 8)[-1]) if line.count("\t") >= 8 else None
907
+ if t:
908
+ tx.add(t)
909
+ return tx
910
+
911
+
912
+ def looks_like_transcriptome(path, gtf_tx):
913
+ names = set(Genome(path).lengths)
914
+ stripped = {strip_version(t) for t in gtf_tx}
915
+ hits = sum(n in gtf_tx or strip_version(n) in stripped for n in names)
916
+ return bool(names) and hits > len(names) / 2
917
+
918
+
919
+ def main(argv=None):
920
+ p = argparse.ArgumentParser(prog="gcheck", description=__doc__,
921
+ formatter_class=argparse.RawDescriptionHelpFormatter)
922
+ p.add_argument("files", nargs="*", help="any mix of FASTA, GTF, GFF, BED, VCF, BCF, BAM, CRAM, SAM, or folders")
923
+ p.add_argument("--fasta", help="the reference genome, when more than one FASTA is given")
924
+ p.add_argument("--transcripts", help="transcriptome FASTA to match against GTF transcript_ids")
925
+ p.add_argument("--alias", help="chromosome alias table, e.g. UCSC chromAlias.txt (maps NC_000001.11 to chr1)")
926
+ p.add_argument("--json", action="store_true", help="machine-readable output")
927
+ p.add_argument("-q", "--quiet", action="store_true", help="print only problems")
928
+ p.add_argument("-V", "--version", action="version", version=f"gcheck {__version__}")
929
+ a = p.parse_args(argv)
930
+
931
+ files = {k: [] for k in KINDS}
932
+ for f in expand(a.files):
933
+ if not os.path.isfile(f):
934
+ p.error(f"no such file: {f}")
935
+ k = kind_of(f)
936
+ if k is None:
937
+ if f.lower().endswith(SIDECARS):
938
+ continue
939
+ p.error(f"unknown file type: {f} (expected one of "
940
+ f"{', '.join(sorted(set(x for v in KINDS.values() for x in v)))}, optionally .gz)")
941
+ files[k].append(f)
942
+ for extra in (a.fasta, a.transcripts, a.alias):
943
+ if extra and not os.path.isfile(extra):
944
+ p.error(f"no such file: {extra}")
945
+
946
+ rep = Report()
947
+ if a.alias:
948
+ rep.alias = read_alias(a.alias)
949
+ fastas = [f for f in files["fasta"] if f not in (a.fasta, a.transcripts)]
950
+ transcripts = [a.transcripts] if a.transcripts else []
951
+ if a.fasta:
952
+ genome = a.fasta
953
+ transcripts += fastas # with the genome named, any other FASTA is a transcriptome
954
+ else:
955
+ if files["gtf"] and len(fastas) > 1:
956
+ try:
957
+ tx = gtf_transcript_ids(files["gtf"])
958
+ transcripts += [f for f in fastas if tx and looks_like_transcriptome(f, tx)]
959
+ except (OSError, EOFError, zlib.error):
960
+ pass # unreadable files are reported by the main checks below
961
+ fastas = [f for f in fastas if f not in transcripts]
962
+ if len(fastas) != 1:
963
+ p.error("give exactly one reference genome FASTA (or pick one with --fasta); found: "
964
+ + (", ".join(fastas) or "none"))
965
+ genome = fastas[0]
966
+
967
+ def guarded(path, fn, *args):
968
+ try:
969
+ return fn(*args)
970
+ except Exception as e: # one unreadable file must not stop the run; the type name keeps bugs visible
971
+ rep.add("ERROR", os.path.basename(path), f"could not be read: {type(e).__name__}: {e}")
972
+
973
+ rep.set_reference(guarded(genome, Genome, genome, rep))
974
+ if not rep.ref:
975
+ rep.add("ERROR", os.path.basename(genome), "no sequences found")
976
+ guarded(genome, check_file_level, rep, genome, "fasta")
977
+ tx = set()
978
+ for k, fs in files.items():
979
+ for f in fs:
980
+ if k != "fasta":
981
+ guarded(f, check_file_level, rep, f, k)
982
+ for f in files["gtf"]:
983
+ tx |= guarded(f, check_features, rep, f, False) or set()
984
+ for f in files["gff"]:
985
+ guarded(f, check_features, rep, f, True)
986
+ for f in files["bed"]:
987
+ guarded(f, check_bed, rep, f)
988
+ for f in files["vcf"]:
989
+ guarded(f, check_vcf, rep, f)
990
+ for f in files["bcf"]:
991
+ guarded(f, check_bcf, rep, f)
992
+ for k in ("bam", "sam", "cram"):
993
+ for f in files[k]:
994
+ guarded(f, check_alignments, rep, f, k)
995
+ for f in transcripts:
996
+ guarded(f, check_transcripts, rep, f, tx)
997
+
998
+ if rep.genome:
999
+ rep.genome.close()
1000
+ checked = [genome] + [f for k, v in files.items() if k != "fasta" for f in v] + transcripts
1001
+ status = {os.path.basename(f): ("FAIL" if any(i["file"] == os.path.basename(f) and i["level"] == "ERROR"
1002
+ for i in rep.issues) else "PASS") for f in checked}
1003
+ if a.json:
1004
+ print(json.dumps({"result": "FAIL" if rep.errors else "PASS", "errors": rep.errors,
1005
+ "reference": os.path.basename(genome), "sequences": len(rep.ref), "build": rep.ref_build,
1006
+ "files": status, "stats": rep.stats, "issues": rep.issues}, indent=2))
1007
+ else:
1008
+ for line in rep.text():
1009
+ print(line)
1010
+ if not a.quiet:
1011
+ for f in checked:
1012
+ if os.path.basename(f) not in rep.bad_files:
1013
+ print(f"PASS {os.path.basename(f)}")
1014
+ print(f"\n{len(checked)} files, {rep.errors} errors -> {'FAIL' if rep.errors else 'PASS'}"
1015
+ f" (reference: {os.path.basename(genome)}, {len(rep.ref)} sequences"
1016
+ f"{', build ' + rep.ref_build if rep.ref_build else ''})")
1017
+ return 1 if rep.errors else 0
1018
+
1019
+
1020
+ def cli():
1021
+ try:
1022
+ sys.exit(main())
1023
+ except KeyboardInterrupt:
1024
+ sys.exit(130)
1025
+ except BrokenPipeError:
1026
+ sys.exit(0)
1027
+
1028
+
1029
+ if __name__ == "__main__":
1030
+ cli()