-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathscore_mpact.py
More file actions
1565 lines (1350 loc) · 56.1 KB
/
Copy pathscore_mpact.py
File metadata and controls
1565 lines (1350 loc) · 56.1 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#!/usr/bin/env python3
"""
MPact m6A Scoring Pipeline - Strand-aware variant effect prediction.
Scores variants using the MPact model with strand-aware logic:
- Scans +/- N nt around each SNV for candidate A-centered windows
- Uses both reference and alternate allele sequence contexts
- Detects m6A disruptions, creations, and contextual changes
- Optional annotation against A-to-I editing sites (no filtering)
Input:
VCF(.vcf/.vcf.gz) or TSV with columns: #Chromosome, Position, Reference, Alteration
(optional: strand, transcript_id columns for strand inference)
Output:
- Scored TSV: detailed per-candidate predictions with m6A deltas
- Optional PNG histogram of delta distribution
Model:
- window_501: 501nt sequence context with 6-channel positional encoding
- Input: one-hot + sin/cos positional embeddings
- Output: sigmoid probability of m6A modification
"""
import argparse
import json
import math
import os
import re
import shutil
import subprocess
import sys
import gzip
import numpy as np
import pandas as pd
import tensorflow as tf
try:
import pysam
except ImportError:
pysam = None
import bisect
from annotation_features import (
AccessibilityCalculator,
ConservationTrack,
annotate_accessibility,
)
class AtoIFilter:
"""Index known A-to-I editing sites for fast overlap queries."""
def __init__(self, rediportal_gz_path):
"""
Load REDIportal hg38 A-to-I sites into memory-indexed structure.
Args:
rediportal_gz_path: Path to TABLE1_hg38_v3.txt.gz
"""
self.sites_by_chrom = defaultdict(list)
self._load(rediportal_gz_path)
def _load(self, path):
"""Parse REDIportal and index sites by chromosome."""
with gzip.open(path, "rt", errors="replace") as f:
header = f.readline().rstrip("\n").split("\t")
idx = {c: i for i, c in enumerate(header)}
chrom_idx = idx["Region"]
pos_idx = idx["Position"]
strand_idx = idx["Strand"]
for line in f:
fields = line.rstrip("\n").split("\t")
if len(fields) <= max(chrom_idx, pos_idx, strand_idx):
continue
chrom = fields[chrom_idx] # e.g. "chr1"
try:
pos = int(fields[pos_idx])
except (ValueError, IndexError):
continue
strand = fields[strand_idx]
# Store 1-based position and strand
self.sites_by_chrom[chrom].append((pos, strand))
# Sort and split into parallel position/strand arrays for fast bisect
self._pos_by_chrom = {} # chrom -> sorted list of int positions
self._strand_by_chrom = {} # chrom -> list of strands (same order)
for chrom, entries in self.sites_by_chrom.items():
entries.sort()
self._pos_by_chrom[chrom] = [e[0] for e in entries]
self._strand_by_chrom[chrom] = [e[1] for e in entries]
def overlaps_exact(self, chrom, pos, strand=None):
"""
Check if position exactly overlaps a known A-to-I site.
Uses binary search — O(log n) instead of O(n).
"""
if chrom not in self._pos_by_chrom:
return False
positions = self._pos_by_chrom[chrom]
strands = self._strand_by_chrom[chrom]
idx = bisect.bisect_left(positions, pos)
# check idx and neighbours (same pos may appear on both strands)
for i in range(max(0, idx - 1), min(len(positions), idx + 2)):
if positions[i] == pos:
if strand is None or strands[i] == strand:
return True
elif positions[i] > pos:
break
return False
def nearest_distance(self, chrom, pos, strand=None):
"""
Find distance to nearest A-to-I site (0 if exact overlap).
Uses binary search — O(log n) instead of O(n).
"""
if chrom not in self._pos_by_chrom:
return None
positions = self._pos_by_chrom[chrom]
strands = self._strand_by_chrom[chrom]
if strand is None:
# No strand filter: candidates are just the two neighbours of bisect
idx = bisect.bisect_left(positions, pos)
best = None
for i in (idx - 1, idx):
if 0 <= i < len(positions):
d = abs(positions[i] - pos)
if best is None or d < best:
best = d
return best
else:
# Strand filter: expand outward from insertion point until distance
# exceeds current best (early-exit scan — still O(k) but k is tiny).
idx = bisect.bisect_left(positions, pos)
best = None
# scan right
for i in range(idx, len(positions)):
d = positions[i] - pos
if best is not None and d >= best:
break
if strands[i] == strand:
best = d if best is None else min(best, d)
# scan left
for i in range(idx - 1, -1, -1):
d = pos - positions[i]
if best is not None and d >= best:
break
if strands[i] == strand:
best = d if best is None else min(best, d)
return best
def nearby_sites_within(self, chrom, pos, radius_nt=5, strand=None):
"""
Return A-to-I sites within radius_nt bp.
Uses binary search to jump directly to the window — O(log n + k).
"""
if chrom not in self._pos_by_chrom:
return []
positions = self._pos_by_chrom[chrom]
strands = self._strand_by_chrom[chrom]
lo = bisect.bisect_left(positions, pos - radius_nt)
hi = bisect.bisect_right(positions, pos + radius_nt)
result = []
for i in range(lo, hi):
if strand is not None and strands[i] != strand:
continue
result.append((positions[i], strands[i], abs(positions[i] - pos)))
return sorted(result, key=lambda x: x[2])
from collections import defaultdict
HALF = 250
MIN_SCAN_CONTEXT_NT = 5
MAX_SCAN_CONTEXT_NT = 21
ACCESSIBILITY_SUFFIXES = (
"unpaired_probability_1nt",
"accessibility_5nt",
"accessibility_10nt",
"accessibility_20nt",
)
CODING_CONSEQUENCES = {
"coding_sequence_variant",
"frameshift_variant",
"inframe_deletion",
"inframe_insertion",
"missense_variant",
"protein_altering_variant",
"start_lost",
"start_retained_variant",
"stop_gained",
"stop_lost",
"stop_retained_variant",
"synonymous_variant",
"incomplete_terminal_codon_variant",
"splice_acceptor_variant",
"splice_donor_variant",
"splice_region_variant",
}
class ReduceSumAxis1(tf.keras.layers.Layer):
"""Custom layer for proper serialization of reduce_sum operations."""
def call(self, inputs):
return tf.reduce_sum(inputs, axis=1)
def compute_output_shape(self, input_shape):
return (input_shape[0], input_shape[2])
_COMP = str.maketrans("ACGTN", "TGCAN")
def reverse_complement(seq):
return seq.translate(_COMP)[::-1]
def complement_base(base):
return reverse_complement(str(base).upper())
def scan_context_half_width(scan_radius):
"""Return the half-width for the reported ref/alt scan sequence context."""
context_nt = (2 * int(scan_radius)) + 1
context_nt = max(MIN_SCAN_CONTEXT_NT, min(MAX_SCAN_CONTEXT_NT, context_nt))
if context_nt % 2 == 0:
context_nt += 1
return context_nt // 2
def open_text_maybe_gzip(path):
if str(path).endswith(".gz"):
return gzip.open(path, "rt")
return open(path, "r")
# ── Genome / annotation version helpers ──────────────────────────────────────
_GENOME_BUILD_ALIASES = {
# Ensembl-style -> canonical label
"grch38": "GRCh38", "hg38": "GRCh38",
"grch37": "GRCh37", "hg19": "GRCh37", "hg37": "GRCh37",
"mm10": "mm10", "grcm38": "mm10",
"mm39": "mm39", "grcm39": "mm39",
}
def _canonical_build(token):
return _GENOME_BUILD_ALIASES.get(token.lower())
def parse_genome_version(path):
"""Extract genome build and, for GTF, the annotation release from a filepath.
Returns (build_label, release_str) where release_str is None for FASTA.
Examples:
Homo_sapiens.GRCh38.110.gtf.gz -> ('GRCh38', '110')
hg38.fa -> ('GRCh38', None)
"""
import re as _re
stem = os.path.basename(str(path)).lower()
build = None
release = None
for token in _re.split(r'[._\-]+', stem):
if build is None:
b = _canonical_build(token)
if b:
build = b
elif _re.fullmatch(r'\d+', token) and release is None:
release = token # first bare integer after build = release number
return build, release
def check_fasta_gtf_version_consistency(fasta_path, gtf_path):
"""Warn if FASTA and GTF appear to use different genome builds."""
if not fasta_path or not gtf_path:
return
fb, _ = parse_genome_version(fasta_path)
gb, gr = parse_genome_version(gtf_path)
if fb and gb and fb != gb:
print(
f"WARNING: Genome build mismatch detected!\n"
f" FASTA -> {os.path.basename(fasta_path)}: build={fb}\n"
f" GTF -> {os.path.basename(gtf_path)}: build={gb}\n"
f" Strand annotation may be incorrect if reference coordinates differ."
)
else:
build_label = gb or fb or "unknown"
release_label = f" release={gr}" if gr else ""
print(f"Genome version check: build={build_label}{release_label} [FASTA and GTF consistent]")
def gtf_version_label(gtf_path):
"""Return a short human-readable label for the GTF, e.g. 'GRCh38.110'."""
build, release = parse_genome_version(gtf_path)
parts = [p for p in (build, release) if p]
return ".".join(parts) if parts else os.path.basename(str(gtf_path))
def parse_gtf_attributes(attr_text):
attrs = {}
for part in attr_text.strip().split(";"):
part = part.strip()
if not part or " " not in part:
continue
key, val = part.split(" ", 1)
attrs[key] = val.strip().strip('"')
return attrs
def load_transcript_strand_map(gtf_path):
"""Load transcript -> strand mapping from GTF file."""
tx2strand = {}
if not gtf_path:
return tx2strand
if not os.path.exists(gtf_path):
print(f"WARNING: GTF not found: {gtf_path}")
return tx2strand
with open_text_maybe_gzip(gtf_path) as handle:
for line in handle:
if not line or line.startswith("#"):
continue
f = line.rstrip("\n").split("\t")
if len(f) < 9:
continue
strand = f[6]
if strand not in {"+", "-"}:
continue
attrs = parse_gtf_attributes(f[8])
tx = attrs.get("transcript_id")
if not tx:
continue
tx2strand[tx] = strand
tx2strand[tx.split(".")[0]] = strand
print(f"Loaded transcript strands for {len(tx2strand)} transcript keys from {gtf_path}")
return tx2strand
def extract_enst_from_sample(sample_value):
if sample_value is None:
return None
m = re.search(r"(ENST\d+(?:\.\d+)?)", str(sample_value))
if m:
return m.group(1)
return None
def normalize_strand_value(v):
s = str(v).strip()
return s if s in {"+", "-"} else None
class FastaFetcher:
"""FASTA accessor with fast in-process backend and samtools fallback."""
def __init__(self, fasta_path):
self.fasta_path = fasta_path
self.samtools_path = shutil.which("samtools") or "/apps/samtools/1.22/bin/samtools"
self.backend = "samtools"
self._fa = None
if pysam is not None:
try:
self._fa = pysam.FastaFile(fasta_path)
self.backend = "pysam"
except Exception:
self._fa = None
def _chrom_candidates(self, chrom):
c = str(chrom)
if c.startswith("chr"):
return [c, c[3:]]
return [c, "chr" + c]
def fetch(self, chrom, start1, end1):
"""Fetch sequence for 1-based inclusive [start1, end1]."""
if start1 < 1 or end1 < start1:
return ""
expected = end1 - start1 + 1
if self.backend == "pysam" and self._fa is not None:
for cand in self._chrom_candidates(chrom):
try:
seq = self._fa.fetch(cand, start1 - 1, end1).upper()
except Exception:
continue
if len(seq) == expected:
return seq
return ""
region = f"{chrom}:{start1}-{end1}"
r = subprocess.run(
[self.samtools_path, "faidx", self.fasta_path, region],
capture_output=True,
text=True,
check=False,
)
if r.returncode != 0:
return ""
lines = r.stdout.strip().splitlines()
if len(lines) < 2:
return ""
seq = "".join(lines[1:]).upper()
return seq if len(seq) == expected else ""
def encode_with_position(seqs, center_index=None, window_size=None):
"""Encode sequences with one-hot + positional embeddings (sin/cos).
Fully vectorized with NumPy.
"""
n = len(seqs)
if window_size is None:
L = len(seqs[0]) if seqs else 501
else:
L = int(window_size)
if center_index is None:
center_index = L // 2
if any(len(seq) != L for seq in seqs):
raise ValueError(f"All sequences must be {L} nt for model input")
# Build lookup: ord(char) -> 4-element one-hot row
_lut = np.zeros((256, 4), dtype=np.float32)
_lut[ord('A')] = [1, 0, 0, 0]
_lut[ord('C')] = [0, 1, 0, 0]
_lut[ord('G')] = [0, 0, 1, 0]
_lut[ord('T')] = [0, 0, 0, 1]
# Convert all sequences to a uint8 array at once
arr = np.frombuffer((''.join(seqs)).encode('ascii'), dtype=np.uint8).reshape(n, L)
onehot = _lut[arr] # shape (n, L, 4)
# Pre-compute positional embeddings (same for every sequence)
rel = np.arange(L, dtype=np.float32) - center_index
pos_e = np.stack([np.sin(rel / 10.0),
np.cos(rel / 10.0)], axis=-1) # shape (L, 2)
pos_e = np.broadcast_to(pos_e, (n, L, 2))
return np.concatenate([onehot, pos_e], axis=-1) # shape (n, L, 6)
def normalize_chrom(c):
c = str(c).strip()
if not c.startswith("chr"):
return "chr" + c
return c
def parse_vcf_info(info_text):
info = {}
for item in str(info_text).split(";"):
if not item:
continue
if "=" in item:
key, value = item.split("=", 1)
info[key] = value
else:
info[item] = True
return info
def parse_gene_symbols_from_geneinfo(geneinfo_text):
"""Extract gene symbols from ClinVar GENEINFO field."""
symbols = []
raw = str(geneinfo_text or "").strip()
if not raw or raw in {".", "NA", "N/A"}:
return symbols
for entry in raw.split("|"):
entry = entry.strip()
if not entry:
continue
symbol = entry.split(":", 1)[0].strip()
if symbol:
symbols.append(symbol)
return symbols
def load_gtf_strand_interval_index(gtf_path, include_features=None, bin_size=1_000_000):
"""Load a lightweight genomic interval index for strand inference.
The index is keyed by chromosome and coarse bins; each entry stores
(start1, end1, strand, gene_name_upper, gene_id_upper).
"""
if include_features is None:
include_features = {"gene"}
if not gtf_path:
return {}
if not os.path.exists(gtf_path):
print(f"WARNING: GTF not found for interval strand inference: {gtf_path}")
return {}
include_features = {str(v).strip().lower() for v in include_features}
idx = {}
n_added = 0
with open_text_maybe_gzip(gtf_path) as handle:
for line in handle:
if not line or line.startswith("#"):
continue
f = line.rstrip("\n").split("\t")
if len(f) < 9:
continue
feature = f[2].strip().lower()
if feature not in include_features:
continue
chrom = normalize_chrom(f[0].strip())
strand = f[6].strip()
if strand not in {"+", "-"}:
continue
try:
start1 = int(f[3])
end1 = int(f[4])
except Exception:
continue
if end1 < start1:
continue
attrs = parse_gtf_attributes(f[8])
gene_name = str(attrs.get("gene_name", "") or "").strip().upper()
gene_id = str(attrs.get("gene_id", "") or "").strip().upper()
b0 = max(0, start1 // bin_size)
b1 = max(0, end1 // bin_size)
chr_bins = idx.setdefault(chrom, {})
rec = (start1, end1, strand, gene_name, gene_id)
for b in range(b0, b1 + 1):
chr_bins.setdefault(b, []).append(rec)
n_added += 1
print(
f"Loaded GTF interval strand index: {n_added} features across {len(idx)} chromosomes "
f"(bin_size={bin_size})"
)
return idx
def infer_strand_from_gtf_intervals(chrom, pos1, interval_index, gene_symbols=None, bin_size=1_000_000):
"""Infer strand at a genomic position from overlapping GTF intervals.
If gene_symbols is provided, hits are constrained to matching gene_name/gene_id
when possible. Returns '+', '-', or None if ambiguous/unresolved.
"""
if not interval_index:
return None
chr_bins = interval_index.get(normalize_chrom(chrom))
if not chr_bins:
return None
b = max(0, int(pos1) // bin_size)
hits = []
for rec in chr_bins.get(b, []):
start1, end1, strand, gene_name, gene_id = rec
if start1 <= pos1 <= end1:
hits.append(rec)
if not hits:
return None
if gene_symbols:
gset = {str(x).strip().upper() for x in gene_symbols if str(x).strip()}
if gset:
constrained = [
rec for rec in hits
if (rec[3] and rec[3] in gset) or (rec[4] and rec[4] in gset)
]
if constrained:
hits = constrained
strands = {rec[2] for rec in hits}
if len(strands) == 1:
return next(iter(strands))
return None
def is_genic_from_clinvar_info(info_text):
"""Infer genic status from ClinVar-style INFO tags (MC/GENEINFO)."""
info = parse_vcf_info(info_text)
# Prefer molecular consequence if present.
mc_val = str(info.get("MC", "") or "")
if mc_val:
tokens = []
for item in mc_val.split(","):
item = item.strip()
if not item:
continue
# Common ClinVar form: SO:0001583|missense_variant
if "|" in item:
item = item.split("|", 1)[1]
tokens.append(item.strip().lower())
if "intron_variant" in tokens:
return True
if any("utr_variant" in t for t in tokens):
return True
if any(t in CODING_CONSEQUENCES for t in tokens):
return True
# Fallback: gene annotation present implies non-intergenic.
geneinfo = str(info.get("GENEINFO", "") or "").strip()
if geneinfo and geneinfo not in {".", "NA", "N/A"}:
return True
return False
def parse_vcf_annotation_fields(header_line, info_id):
marker = f'ID={info_id}'
if marker not in header_line:
return None
m = re.search(r'Format: ([^\"]+)', header_line)
if not m:
return None
return [field.strip() for field in m.group(1).split("|")]
def first_annotation_value(annotation_fields, annotation_values, candidates):
for candidate in candidates:
if candidate not in annotation_fields:
continue
index = annotation_fields.index(candidate)
if index >= len(annotation_values):
continue
value = annotation_values[index].strip()
if value:
return value
return None
def extract_transcript_id_from_info(info_text, csq_fields=None, ann_fields=None):
info = parse_vcf_info(info_text)
if csq_fields and info.get("CSQ"):
for entry in str(info["CSQ"]).split(","):
values = entry.split("|")
feature_type = first_annotation_value(csq_fields, values, ["Feature_type", "BIOTYPE"])
transcript_id = first_annotation_value(
csq_fields,
values,
["Feature", "Transcript", "Transcript_ID", "transcript_id"],
)
if transcript_id and (feature_type in {None, "Transcript", "transcript", "mRNA"}):
return transcript_id
if ann_fields and info.get("ANN"):
for entry in str(info["ANN"]).split(","):
values = entry.split("|")
feature_type = first_annotation_value(ann_fields, values, ["Feature_Type"])
transcript_id = first_annotation_value(
ann_fields,
values,
["Feature_ID", "Transcript_ID", "transcript_id"],
)
if transcript_id and (feature_type in {None, "transcript", "Transcript", "mRNA"}):
return transcript_id
return None
def load_variants_input(input_path, genic_only=False):
"""Load variants from VCF(.gz) or TSV into a dataframe."""
lp = str(input_path).lower()
if lp.endswith(".vcf") or lp.endswith(".vcf.gz"):
rows = []
total_records = 0
total_alt_alleles = 0
kept_snv_alleles = 0
csq_fields = None
ann_fields = None
with open_text_maybe_gzip(input_path) as fin:
for line in fin:
if not line:
continue
if line.startswith("##INFO=<ID=CSQ"):
csq_fields = parse_vcf_annotation_fields(line, "CSQ")
continue
if line.startswith("##INFO=<ID=ANN"):
ann_fields = parse_vcf_annotation_fields(line, "ANN")
continue
if line.startswith("#"):
continue
fields = line.rstrip("\n").split("\t")
if len(fields) < 8:
continue
total_records += 1
chrom, pos, vid, ref, alt_field, _, _, info_text = fields[:8]
ref = str(ref).upper()
alts = [a.strip().upper() for a in str(alt_field).split(",")]
total_alt_alleles += len(alts)
if len(ref) != 1 or ref not in {"A", "C", "G", "T"}:
continue
info_map = parse_vcf_info(info_text)
transcript_id = extract_transcript_id_from_info(info_text, csq_fields=csq_fields, ann_fields=ann_fields)
is_genic = is_genic_from_clinvar_info(info_text)
gene_symbols = parse_gene_symbols_from_geneinfo(info_map.get("GENEINFO", ""))
for alt in alts:
if len(alt) != 1 or alt not in {"A", "C", "G", "T"}:
continue
kept_snv_alleles += 1
if genic_only and not is_genic:
continue
rows.append(
{
"#Chromosome": chrom,
"Position": pos,
"Reference": ref,
"Alteration": alt,
"VariantID": vid,
"transcript_id": transcript_id,
"gene_symbols": "|".join(gene_symbols),
}
)
dropped_non_snv = total_alt_alleles - kept_snv_alleles
n_before_genic = kept_snv_alleles
if genic_only:
dropped_non_genic = n_before_genic - len(rows)
print(
f"VCF genic filter: kept={len(rows)}, dropped_non_genic={dropped_non_genic}"
)
df = pd.DataFrame(rows)
print(
f"VCF parse summary: records={total_records}, alt_alleles={total_alt_alleles}, "
f"kept_snv={kept_snv_alleles}, dropped_non_snv={dropped_non_snv}"
)
return df, list(df.columns), "vcf"
df = pd.read_csv(input_path, sep="\t", dtype=str)
return df, list(df.columns), "tsv"
def iter_input_chunks(input_path, genic_only=False, chunk_size=10000):
"""Yield input dataframe chunks for bounded-memory processing."""
lp = str(input_path).lower()
if lp.endswith(".vcf") or lp.endswith(".vcf.gz"):
df, input_cols, input_kind = load_variants_input(input_path, genic_only=genic_only)
yield df, input_cols, input_kind
return
for chunk in pd.read_csv(input_path, sep="\t", dtype=str, chunksize=int(chunk_size)):
yield chunk, list(chunk.columns), "tsv"
def resolve_required_columns(df):
"""Resolve key variant columns from common aliases and standardize names."""
def first_present(cands):
for c in cands:
if c in df.columns:
return c
return None
chrom_col = first_present(["#Chromosome", "Chromosome", "CHROM", "chrom", "chr"])
pos_col = first_present(["Position", "POS", "pos", "Start", "start"])
ref_col = first_present(["Reference", "REF", "ref"])
alt_col = first_present(["Alteration", "ALT", "alt", "Alternate"])
missing = []
if chrom_col is None:
missing.append("#Chromosome/CHROM")
if pos_col is None:
missing.append("Position/POS")
if ref_col is None:
missing.append("Reference/REF")
if alt_col is None:
missing.append("Alteration/ALT")
if missing:
raise ValueError(
"Input is missing required variant columns: "
+ ", ".join(missing)
+ f". Available columns: {list(df.columns)}"
)
if "#Chromosome" not in df.columns:
df["#Chromosome"] = df[chrom_col]
if "Position" not in df.columns:
df["Position"] = df[pos_col]
if "Reference" not in df.columns:
df["Reference"] = df[ref_col]
if "Alteration" not in df.columns:
df["Alteration"] = df[alt_col]
return df
def class_predictions(pred):
"""Return the classification output from a Keras prediction."""
if isinstance(pred, dict):
if "class_output" in pred:
pred = pred["class_output"]
elif pred:
pred = next(iter(pred.values()))
else:
return np.asarray([], dtype=np.float32)
elif isinstance(pred, (list, tuple)):
pred = pred[0] if pred else np.asarray([], dtype=np.float32)
return np.asarray(pred).reshape(-1)
def add_delta_stats(df):
"""Add z-score and p-value columns to delta scores."""
delta = df["mpact_delta_alt_minus_ref"].astype(float).to_numpy()
mu = float(delta.mean())
sd = float(delta.std(ddof=0))
if sd == 0.0:
z = np.zeros_like(delta)
else:
z = (delta - mu) / sd
root2 = math.sqrt(2.0)
pvals = np.array([math.erfc(abs(float(v)) / root2) for v in z], dtype=float)
df["delta_zscore"] = z
df["delta_p_two_sided"] = pvals
return mu, sd
def compute_delta_stats_from_tsv(tsv_path, chunk_size=250000):
"""Compute mean/std for mpact deltas from a large TSV without loading it all."""
n = 0
s = 0.0
ss = 0.0
for part in pd.read_csv(
tsv_path,
sep="\t",
usecols=["mpact_delta_alt_minus_ref"],
chunksize=int(chunk_size),
):
arr = part["mpact_delta_alt_minus_ref"].astype(float).to_numpy()
if arr.size == 0:
continue
n += int(arr.size)
s += float(arr.sum())
ss += float((arr * arr).sum())
if n == 0:
return 0.0, 0.0
mu = s / n
var = max(0.0, (ss / n) - (mu * mu))
sd = math.sqrt(var)
return mu, sd
def predict_scores_in_batches(model, seqs, batch_size, window_size):
"""Predict classification scores in bounded-memory batches."""
n = len(seqs)
class_out = np.zeros(n, dtype=np.float32)
if n == 0:
return class_out
for i in range(0, n, batch_size):
j = min(i + batch_size, n)
X = encode_with_position(seqs[i:j], window_size=window_size)
pred = model.predict(X, batch_size=batch_size, verbose=0)
class_pred = class_predictions(pred)
class_out[i:j] = class_pred
return class_out
def z_and_p_from_delta(delta, mu, sd):
"""Compute z-scores and two-sided p-values from delta vector and global stats."""
delta = np.asarray(delta, dtype=float)
if sd == 0.0:
z = np.zeros_like(delta)
else:
z = (delta - mu) / sd
root2 = math.sqrt(2.0)
pvals = np.array([math.erfc(abs(float(v)) / root2) for v in z], dtype=float)
return z, pvals
def plot_delta_hist(delta_values, out_png):
"""Generate histogram of m6A delta distribution."""
try:
import matplotlib
matplotlib.use("Agg")
import matplotlib.pyplot as plt
if isinstance(delta_values, pd.DataFrame):
delta = delta_values["mpact_delta_alt_minus_ref"].astype(float).to_numpy()
else:
delta = np.asarray(delta_values, dtype=float)
if delta.size == 0:
print("WARNING: no delta values available for histogram")
return
plt.figure(figsize=(8, 5))
plt.hist(delta, bins=80, color="#2f6db3", alpha=0.9)
plt.axvline(0.0, color="black", linestyle="--", linewidth=1)
plt.xlabel("m6A-delta (ALT - REF)")
plt.ylabel("Count")
plt.title("MPact m6A score delta distribution")
plt.tight_layout()
plt.savefig(out_png, dpi=200)
plt.close()
print(f"Delta histogram saved: {out_png}")
except Exception as e:
print(f"WARNING: could not render plot: {e}")
def main():
p = argparse.ArgumentParser(
description="Score variants with MPact m6A model using strand-aware scanning"
)
p.add_argument(
"--input",
required=True,
help="Input variants file (.tsv, .vcf, or .vcf.gz)"
)
p.add_argument(
"--output-tsv",
required=True,
help="Output TSV with MPact predictions"
)
p.add_argument(
"--fasta",
required=True,
help="Reference FASTA (indexed with samtools faidx)"
)
p.add_argument(
"--model-path",
required=True,
help="Path to MPact model (HDF5 format)"
)
p.add_argument(
"--window-size",
type=int,
default=501,
help="Model input window size in nt (default: 501; use 101 or 201 with matching bundled models)"
)
p.add_argument(
"--output-plot",
default="",
help="Optional: output PNG histogram of delta scores"
)
p.add_argument(
"--gtf",
default="Homo_sapiens.GRCh38.110.gtf.gz",
required=False,
help="GTF/GTF.gz for Gencode strand inference (REQUIRED for strand certainty; default: bundled Ensembl GRCh38.110)"
)
p.add_argument(
"--gtf-interval-features",
default="gene",
help="Comma-separated GTF feature types to index for interval strand fallback (default: gene; genic-locus based)",
)
gtf_geneinfo_group = p.add_mutually_exclusive_group()
gtf_geneinfo_group.add_argument(
"--gtf-interval-use-geneinfo",
dest="gtf_interval_use_geneinfo",
action="store_true",
default=True,
help="When falling back to GTF interval strand inference, constrain overlaps by GENEINFO symbols when present (default: on)",
)
gtf_geneinfo_group.add_argument(
"--no-gtf-interval-use-geneinfo",
dest="gtf_interval_use_geneinfo",
action="store_false",
help="Disable GENEINFO-constrained interval strand inference",
)
p.add_argument(
"--rediportal-gz",
default="TABLE1_hg38_v3.txt.gz",
help="REDIportal A-to-I sites file for annotation (required; bundled local symlink by default)"
)
p.add_argument(
"--scan-radius",
type=int,
default=5,
help="Scanning radius around SNV for candidate A sites (default: 5 nt)"
)
p.add_argument(
"--batch-size",
type=int,
default=1024,
help="Batch size for model prediction (default: 1024 in optimized version)"
)
p.add_argument(
"--input-chunk-size",
type=int,
default=50000,
help="Rows per input chunk for streaming mode (default: 50000 in optimized version)"
)
p.add_argument(
"--resume",
action="store_true",
help="Resume from a previous interrupted run using checkpoint + temporary scored TSV"
)
p.add_argument(