-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathfiltering_r.pl
More file actions
executable file
·2327 lines (2179 loc) · 129 KB
/
Copy pathfiltering_r.pl
File metadata and controls
executable file
·2327 lines (2179 loc) · 129 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 perl
use strict;
use warnings;
# Naming / family-discovery self-test (no data or reference files needed).
# perl filtering_r.pl --selftest
run_naming_selftest() if grep { $_ eq '--selftest' } @ARGV;
#############################################################################
# filtering_r.pl — clinical candidate filtering for trio/duo germline VCFs
# (robust successor of filtering_new.pl / filtering_b3.pl)
#
# Pipeline features
# -----------------
# * CSQ fields resolved BY NAME from each VCF's own CSQ header (no hard-coded
# indices). Critical fields are asserted at startup (loud failure, never
# silent). [#3]
# * Reads *.germline.vep.vcf.gz directly; auto-discovers families by filename
# using the role-suffix convention (see sample_role): <FAMILY>-P=proband,
# <FAMILY>-M=mother, <FAMILY>-F=father. A name with no -P/-M/-F suffix is
# ignored by discovery; if NO input has one, every sample is analyzed as a
# singleton proband.
# * Multiallelic input is assumed pre-split (vep_annotate.sh runs
# `bcftools norm -m-any`). Any residual multiallelic row is skipped+counted.
# [#2]
# * Structural gates (AND): MANE transcript + whitelisted consequence
# (matched per-&-atom) + panel gene + rare. Consequence is split on '&' so
# unanticipated compound terms are not silently dropped. A panel-gene variant
# that is ClinVar P/LP with >=1 review star is EXEMPT from the rarity and
# consequence gates (MANE + panel still required), so founder alleles above the
# AF ceiling and pathogenic non-coding/synonymous variants are not discarded
# before any evidence arm runs. [#1]
# * Frequency threshold is MOI-aware: recessive genes tolerate a higher
# gnomAD AF than dominant genes. [#6]
# * Inclusion (rescue) gate (OR): CADD>=25.3, AlphaMissense>=0.792, EVE path,
# REVEL>=0.644, Pangolin (>=0.2 for whitelisted splice consequences, >=0.5
# otherwise), ClinVar P/LP, PS1/PM5 (ClinVar AA match), LoF
# (LOFTEE HC or high-impact truncating consequence), AR_hom (see below). Each
# surviving row records which arm(s) fired in a `kept_by` column, using the
# tokens CADD/AM/EVE/REVEL/Pangolin/ClinVar/PS1/PM5/LoF/AR_hom. [#4,#8]
# * Genotype-aware: proband zygosity / DP / GQ / allele-balance columns from
# FORMAT; parent inheritance uses parental GT (carrier = non-ref), not mere
# site presence. [#5,#10]
# * One MANE row per variant: a variant annotating onto >1 MANE transcript
# (MANE Select + MANE Plus Clinical, or overlapping gene models) is collapsed to
# a single row — prefer panel-primary, then MANE Select, then most evidence arms.
# (--lookup consults still report every annotation.) [#3]
# * Per-gene recessive logic (recessive-capable genes only): homozygous and
# compound-het (trans where phaseable) flags. Purely dominant genes get no
# HOM/CompHet flag, so two independent hets are not mislabeled comp-het. [#6,#7]
# * Dual-inheritance genes (MOI lists BOTH AD and AR, e.g. "AD, AR") are treated
# as DOMINANT for the carrier drop: a solitary het passes through as a candidate
# (no recessive flag), while a genuine hom/comp-het still gets the recessive
# flag. Pure AR/XLR genes use the recessive path below. [#5]
# * Recessive carriers (DEFAULT = drop): a solitary het in a PURE recessive (AR/XLR)
# gene that is not biallelic is DROPPED (a single het can't explain recessive disease;
# carrier states are clinical noise). True comp-hets are unaffected — a gene with >=2
# gate-passing hets is a biallelic CompHet and kept. OPT-IN --keep-ar-carriers /
# KEEP_AR_CARRIERS=1 surfaces the STRONG such carriers (carrier-only tier: ClinVar
# P/LP >=1*, HC-LoF, or >=2 Moderate-calibrated predictors AM>=0.906/CADD>=28.1/EVE-path/
# REVEL>=0.773, not Benign/LB; flagged flags=carrier-only) for second-hit hunts. [#1,#2,#6]
# * ClinVar (fresh, via --custom), gnomAD nhomalt + FILTER surfaced as
# columns. [#4,#7]
# * ACMG SF secondary findings: the 81 ACMG SF v3.2 genes are ALWAYS scanned
# (independent of the candidate panel) with a STRICTER gate — ClinVar P/LP
# (>=1 star, frequency-agnostic) OR novel LOFTEE-HC OR >=2 Moderate-calibrated computational
# predictors (AM>=0.906, CADD>=28.1, EVE path, REVEL>=0.773); AR genes report
# biallelic only. These appear in the SAME candidatos output flagged with
# GDV=Incidental (Association/MOI from the ACMG table; kept_by = evidence tier).
# * Automated ACMG/AMP classification (TRIAGE ONLY): per-row acmg_class +
# acmg_points + acmg_criteria, combined per $COMBINER — Tavtigian-2020 points
# (DEFAULT: 8/4/2/1, class from the summed score) or categorical ACMG 2015.
# PP3/BP4 use a single CALIBRATED tool — AlphaMissense primary (Bergquist 2025),
# REVEL fallback (Pejaver 2022) — graded Supporting/Moderate/Strong with a REVEL
# direction-conflict veto; Pangolin >= 0.2 adds splice PP3_Supporting (never on
# top of full PVS1). PVS1: start_lost capped at Moderate (Tayoun 2018).
# PS2/PM6 require a dominant-capable panel MOI. PP2: missense in a gene with
# low benign-missense variation, from gnomAD v4.1.1 missense constraint (mis.oe <
# 0.6 on MANE, outliers excluded); counts independently of PP3, but suppressed when
# BP4 fired (no gene-level pathogenic support for a benign-predicted variant). Other
# criteria: PVS1, PS2/PM6, PM2/PM4, PP5, BA1/BS1/BS2/BP6/BP7. [#2]
# * Cohort recurrent-artifact filter (internal panel-of-normals): for a real
# cohort auto-analyzed together (>= $COHORT_MIN probands), a candidate carried by
# >= $COHORT_MAX_FRAC of samples AND absent from gnomAD (joint AC == 0) is
# a systematic technical artifact (paralog/low-complexity mismapping) and is
# dropped — both conditions required, so population bottlenecks / founder alleles
# (which carry a gnomAD footprint) are preserved. OFF for single-variant, forced/
# single-proband, and small runs. --keep-cohort-artifacts keeps+tags instead. [#11]
# * QC / artifact flags (in the consolidated `flags` column, after the recessive
# verdict): lowDP, lowGQ, AB_het/AB_hom, homopolymer, clinvar_conflict,
# (indels, via samtools+reference), inh_lowqual, DN_unconfirmed. [#6,#7]
# NOTE: parent VCFs are variant-only, so de-novo cannot be confirmed from
# parental reference depth — DN is flagged DN_unconfirmed by design. [#6]
# * Run summary printed per proband. [#9]
#
# Splicing (Pangolin) two-pass bridge
# -----------------------------------
# If <proband>.<panel>.pangolin.tsv is ABSENT, the script writes
# <proband>.<panel>.pangolin_input.csv (the structural-pass candidates) and
# stops for that proband. Run Pangolin (run_filtering.sh) to create the .tsv,
# then re-run to produce <proband>.<panel>.candidatos. (<panel> = panel
# basename, so different gene lists produce side-by-side outputs.)
#
# Single-variant lookup mode
# --------------------------
# Report EVERYTHING for one (or a few) variants with the panel / rarity /
# consequence / rescue gates and the recessive-carrier drop all BYPASSED
# (off-panel genes get Association/MOI/GDV = NA; kept_by lists whichever evidence
# arms fire, else "none"). MANE-only unless --all-transcripts. Genotype columns
# are blank (sites-only) and inheritance = NA.
# Output is the TRANSPOSED, human-readable view only — one "field <TAB> value"
# line per column (not the TSV candidatos table) — written to
# Lookup.<coords>.<panel>.candidatos and echoed to stdout.
# Two ways in:
# -v/--variant '<v>' resolve + annotate variant(s) from scratch (repeatable).
# --lookup <vcf.gz> analyze a pre-annotated *.germline.vep.vcf.gz directly.
# <v> is dashed/colon GRCh38 coords (chr2-166199981-A-G | 2:166199981:A:G, also
# the 5-field chr-start-end-ref-alt form), resolved offline, OR transcript-
# qualified HGVS (ENST…:c.…), recoded to coords via the Ensembl REST API (only the
# variant string is sent, never patient data).
# -v builds a sites-only VCF and runs vep_annotate.sh, removing the annotated
# VCF afterward unless --keep-vcf. The panel (Association/MOI/GDV columns) is the
# default g4e-2026 unless overridden with -l/--list <genes>.
#############################################################################
# ── Tunable thresholds (single source of truth) ──
my $INPUT_GLOB = '*.germline.vep.vcf.gz';
my $FREQ_AD = 0.01; # max gnomAD AF (%) for dominant genes (1 in 10,000)
my $FREQ_AR = 1.0; # max gnomAD AF (%) for recessive genes (carrier freq)
my $CADD_MIN = 25.3; # CADD PHRED rescue threshold
my $REVEL_MIN = 0.644; # REVEL rescue threshold (ClinGen PP3)
my $AM_MIN = 0.792; # AlphaMissense pathogenicity rescue threshold
my $SPLICE_MIN = 0.5; # Pangolin |delta| rescue threshold for DISCOVERY PROBES (and non-splice consequences)
my $SPLICE_SUPP = 0.2; # Pangolin splice-evidence boundary. At/above: an already-whitelisted
# splice consequence is rescued AND the row earns PP3_Supporting
# (SpliceAI-analogous 0.2 cutoff, Walker et al. AJHG 2023; no published
# Pangolin calibration supports more than Supporting). Below, a scored
# synonymous variant earns BP7. ONE constant for both sides, so the
# benign and pathogenic splice assertions can never overlap or leave
# the former 0.2-0.49 dead zone in which a whitelisted splice variant
# with no other arm was dropped outright.
# ── gnomAD resource footprint ──
# The custom gnomAD VCF is built from MANE-Select exons padded by this many bp
# (mane_select.exons.pad10 in the build command recorded in its header). It is also
# sites-only with AC_joint > 0, so "AN = 0" means "this allele has no record", which
# INSIDE the footprint reads as "absent from gnomAD" (legitimately rare) but OUTSIDE it
# means nothing at all: the position was never sliced in. A whitelisted splice
# consequence that far into the intron (splice_polypyrimidine_tract is -17..-3,
# splice_region reaches +8/-8) therefore passes every rarity ceiling unexamined. Found
# the hard way: two COMMON SNPs (rs9980730, gnomAD 97% major allele homozygous;
# rs2294560, AF 0.30) were rescued by Pangolin at 0.21-0.31 and reported as
# PM2_Supporting VUS. gnomad_uncovered() marks such rows; they are then held to the
# discovery-probe standard (Pangolin >= $SPLICE_MIN), PM2 is withheld, and the row is
# flagged `gnomAD_uncovered` so the curator knows the frequency was never checked.
# Rebuild the resource with a wider pad and raise this constant to match.
my $GNOMAD_INTRON_PAD = 10;
# ── Splice DISCOVERY probes [#5] ──
# typevar.txt has no bare `intron_variant` and no bare `synonymous_variant`, so a
# deep-intronic or exonic-synonymous splice-disrupting variant was dropped at Stage 1,
# never reached Pangolin, and the splice rescue arm could only ever UPGRADE a variant that
# was already whitelisted — never DISCOVER one. The classic pathogenic deep-intronic
# alleles (CFTR c.3718-2477C>T, USH2A c.7595-2144A>G) were structurally unreachable.
#
# Probes are scored by Pangolin and kept ONLY if the splice arm fires (>= $SPLICE_MIN).
# They are not candidates in their own right, so a probe that Pangolin scores low simply
# disappears — the probe set widens what can be FOUND without widening the table.
#
# VOLUME IS THE BINDING CONSTRAINT. Pangolin scores ~8 variants/s on one GPU, and a WGS
# proband carries ~155k rare intronic variants in panel genes. Two bounds keep it finite:
# (a) distance from the exon boundary, read from the HGVSc offset; and
# (b) a strict rarity ceiling applied to ALL genes — a pathogenic splice variant is rare
# regardless of the gene's mode of inheritance, so the permissive $FREQ_AR carrier
# ceiling (1%, meant for recessive coding candidates) is deliberately NOT used here.
# Set $SPLICE_PROBE = 0, or pass --no-splice-discovery, to restore the prior behaviour.
my $SPLICE_PROBE = $ENV{NO_SPLICE_DISCOVERY} ? 0 : 1;
my $INTRON_MAX_DIST = 300; # max |HGVSc intron offset| to probe (bp from exon boundary)
my $PROBE_FREQ_MAX = 0.01; # max gnomAD AF (%) for a probe, every gene
# Require the probe position to EXIST in the gnomAD resource (AN > 0). Default ON.
#
# MEASURED COST OF THIS SETTING. The custom VCF is gnomAD.joint.v4.1.**mane**, so intronic
# coverage is thin: on a real WGS proband the 300 bp window contains ~22,700 rare intronic
# variants, but only ~8 of them are gnomAD-covered. Requiring coverage therefore keeps the
# probe set almost free (8 probes/proband) — and keeps discovery confined to roughly the
# MANE footprint, so a classic deep-intronic allele (CFTR c.3718-2477C>T) is still out of
# reach. Turning it OFF (--probe-uncovered) probes all ~22,700: at ~8 variants/s that is
# ~48 min per proband of GPU time, and every rescued variant sits in territory where the
# rarity gate cannot work. PM2 is withheld on such rows (see acmg_classify) so the run at
# least does not invent a pathogenic criterion for them.
#
# The real unlock is rebuilding the custom gnomAD VCF with genome-wide coverage; then this
# flag stops mattering and the rarity gate works everywhere.
my $PROBE_REQUIRE_GNOMAD = $ENV{PROBE_UNCOVERED} ? 0 : 1;
# ── Cohort recurrent-artifact filter (internal panel-of-normals) [#11] ──
# Systematic technical artifacts — reference/mapping errors in paralog-rich or
# low-complexity genes (e.g. SYNE1, KMT2C) — recur across a large fraction of a
# cohort yet are ABSENT from gnomAD. That combination is the discriminator: a
# population bottleneck or an under-represented ancestry CANNOT produce it, because
# a real founder allele frequent enough to reach a quarter of the cohort would
# leave a footprint in gnomAD's large Admixed-American sample. So a variant is
# dropped ONLY when it is BOTH cohort-recurrent (>= $COHORT_MAX_FRAC of samples) AND
# wholly absent from gnomAD (joint AC == 0). Neither condition alone drops anything.
# Absence is tested as AC == 0 rather than against a frequency ceiling on purpose: a
# ceiling at or above $FREQ_AD is already implied by the Stage-1 rarity gate for
# dominant genes, which would leave recurrence as the only effective condition and
# strip the founder-safety the second condition exists to provide. Requiring a
# literal zero keeps that protection meaningful for every mode of inheritance —
# any gnomAD footprint at all, however small, spares the variant.
# Activates ONLY for a real cohort auto-analyzed together (>= $COHORT_MIN probands,
# no forced selection): single-variant (-v/--lookup) and single/forced-proband
# (--proband) runs never activate it, and trios/duos/small runs are untouched
# (a per-variant or per-proband consult has no cohort to compare against). Logged;
# --keep-cohort-artifacts (env KEEP_COHORT_ARTIFACTS=1) keeps them instead, tagged
# flags=cohort_artifact — for a founder-enriched cohort, review the drop log, as a
# genuinely private founder allele would surface there.
# THRESHOLDS (revised 2026-08). The filter previously needed >= 10 probands, which no
# real internal batch reaches — batches run 6-9 samples — so it had never once fired on
# a clinical run, and the recurrent KMT2C/SYNE1 mismapping artifacts reached every
# delivered table. Two changes make it work at the batch sizes actually used:
#
# 1. $COHORT_MIN 10 -> 5 samples. Five unrelated genomes are enough to tell a
# systematic artifact from a private allele when gnomAD-absence is also required.
# 2. A new ABSOLUTE floor, $COHORT_MIN_CARRIERS, on top of the fraction. At N=8 the
# 25% fraction alone means 2 carriers, and two unrelated Chilean probands sharing
# a gnomAD-absent allele is an ordinary founder/relatedness event, not evidence of
# a technical artifact. Requiring >= 3 carriers AND >= 25% keeps both ends honest:
# the floor binds on small batches, the fraction binds on large cohorts (at N=56,
# 25% = 14 carriers, well above the floor).
#
# Measured on batch4 (8 singleton probands), the carrier distribution is bimodal with a
# clean gap: the four artifacts sit at 5,6,7,8 of 8 carriers (63-100%) and the next most
# recurrent candidate is 2 of 8 (25%). Both new thresholds fall inside that gap.
my $COHORT_MIN = 5; # min samples to activate the filter (below -> OFF)
my $COHORT_MAX_FRAC = 0.25; # carried by >= this fraction of the cohort -> "recurrent"
my $COHORT_MIN_CARRIERS = 3; # ...AND by at least this many samples, whatever the fraction
# Ensembl REST endpoint for HGVS->coordinate recoding in -v variant mode
# (override with $ENSEMBL_REST; point at a private mirror on an air-gapped host).
my $ENSEMBL_REST = $ENV{ENSEMBL_REST} // 'https://rest.ensembl.org';
# High-impact loss-of-function consequences (LoF rescue arm; see inclusion gate).
my %LOF_CONS = map { $_ => 1 }
qw(frameshift_variant stop_gained splice_acceptor_variant splice_donor_variant start_lost);
# ── ACMG SF secondary findings (always evaluated; stricter than candidates) ──
# Emitted into the SAME candidatos output, flagged GDV=Incidental.
my $ACMG_FILE = 'acmg_sf_v3.2.txt';
my $SF_FREQ_MAX = 0.5; # max gnomAD AF (%) for the NOVEL SF tiers (LoF/computational)
my $SF_AM = 0.906; # AlphaMissense (ClinGen PP3_Moderate, Bergquist 2025 — the SF tier needs 2 together)
my $SF_CADD = 28.1; # CADD PHRED (PP3_Moderate, Pejaver 2022; CADD has no Strong interval)
my $SF_REVEL = 0.773; # REVEL (ClinGen PP3_moderate)
# ── QC / artifact flags [#7] and parental-quality de-novo confidence [#6] ──
my $QC_MIN_DP = 15; # depth below this -> lowDP
my $QC_MIN_GQ = 20; # genotype quality below this -> lowGQ
my $REF_FASTA = $ENV{REF_FASTA} // $ENV{PANGOLIN_FASTA} // ''; # set by site.sh; blank => check skipped
my $HAVE_REF = -e "$REF_FASTA.fai"; # samtools-indexed reference for homopolymer check
# ── Automated ACMG/AMP classification (InterVar-style, triage only) [#2] ──
my $PM2_AC_MAX = 1; # gnomAD AC at/below -> PM2 (absent=0 or singleton=1)
# ── Evidence combining ──
# 'points' (DEFAULT since 2026-08): the ClinGen/Tavtigian Bayesian points system
# (Tavtigian et al., Genet Med 2020): VeryStrong=8, Strong=4, Moderate=2,
# Supporting=1; benign mirror negative. Class: >=10 Pathogenic, 6..9
# Likely_pathogenic, 0..5 VUS, -1..-6 Likely_benign, <=-7 Benign.
# TRIAGE DEVIATION: BA1 is scored as -8 (Very-Strong benign) instead of the
# standard absolute exclusion — a ClinVar-P founder allele above the BA1
# ceiling must surface with its tension visible (clinvar_conflict flag), not
# be silently forced Benign before a curator sees it.
# The points class has no "Conflicting" verdict — opposing evidence nets out
# arithmetically; hard contradictions still raise flags=clinvar_conflict.
# 'categorical': ACMG 2015 Table 5 (the pre-2026-08 default), kept for
# comparison/audit. acmg_points is computed and reported in BOTH modes.
my $COMBINER = $ENV{ACMG_COMBINER} // 'points'; # 'points' | 'categorical'
# PM2 evidence strength FOLLOWS THE COMBINER. ClinGen SVI (2020) recommends
# Supporting — coherent under 'points', where PVS1(8) + PM2_Supporting(1) = 9
# still reaches Likely_pathogenic. Under 'categorical' the same downgrade is
# framework-mixing: ACMG 2015 has no "PVS1 + 1 supporting" pathway, so it
# silently demotes every gnomAD-absent LoF variant in a disease gene to VUS
# (measured on an internal batch: KCNT1, CUX2, RELN, HCN2). Hence the pairing
# below; override with env PM2_STRENGTH only if you understand that trade.
my $PM2_STRENGTH = $ENV{PM2_STRENGTH}
// ($COMBINER eq 'points' ? 'supporting' : 'moderate');
my $BS1_FREQ = 1.0; # gnomAD AF (%) at/above -> BS1 (too common for rare disease)
my $BA1_FREQ = 5.0; # gnomAD AF (%) at/above -> BA1 (benign standalone)
my $BS2_NHOM = 10; # gnomAD homozygotes at/above -> BS2
my $BP4_REVEL = 0.290; # REVEL at/below -> BP4 (computational benign, ClinGen)
my $PP2_MIS_OE = 0.6; # gnomAD v4.1.1 missense o/e below this -> gene is missense-
# constrained; a missense variant there earns PP2 (see acmg_classify)
my $CONSTRAINT_FILE = 'gnomad-mis-constraint.txt'; # gene -> mis.oe / mis.z / flags
#############################################################################
# Reference hashes
#############################################################################
# Cohort recurrent-artifact self-test (synthetic VCFs; no annotation stack needed).
# perl filtering_r.pl --selftest-cohort
run_cohort_selftest() if grep { $_ eq '--selftest-cohort' } @ARGV;
# ── Where the tracked reference data lives ──
# Resolve each reference file from the CURRENT directory first (so a run directory can
# drop in its own panel), then from the script's own directory. Without this every
# reference file was opened by bare relative name, so the documented $WORKDIR override
# only worked if you symlinked the whole repo into the run directory — which is exactly
# what the per-sample batch directories had been doing.
my $CF_REPO = $0;
$CF_REPO = ($CF_REPO =~ s{/[^/]+$}{}r);
$CF_REPO = "." if $CF_REPO eq $0 || $CF_REPO eq "";
sub ref_file {
my ($f) = @_;
return $f if -e $f;
return "$CF_REPO/$f" if -e "$CF_REPO/$f";
return $f; # let the caller's open() report the error
}
open MANE, "<", ref_file("mane-plus-clinical-names.txt") or die "mane: $!";
my %mane;
while (my $m = <MANE>) { chomp $m; my ($a,$b) = split /\t/, $m; $mane{$a} = $b; }
close MANE;
print "hash mane, listo!\n";
# gnomAD v4.1.1 missense constraint (MANE Select): gene -> mis.oe, for the ACMG PP2
# criterion. Genes flagged as missense-constraint outliers (outlier_mis / no_exp_mis)
# are skipped so they can never earn PP2. Optional file — absent -> PP2 simply never fires.
# gnomAD v4.1.1 predates several HGNC symbol changes, so a current panel/VEP symbol
# can miss its own constraint record and silently forfeit PP2. These five are confirmed
# renames where the OLD symbol is present in the constraint file (verified by lookup);
# every other panel gene absent from the file is genuinely absent (mitochondrial, snRNA/
# snoRNA, or not MANE Select in v4.1.1) and has no missense constraint to inherit.
my %GENE_ALIAS = (
GBA1 => 'GBA', # HGNC 2022
BMAL1 => 'ARNTL', # HGNC 2023
AFG2A => 'SPATA5', # HGNC 2022
AFG2B => 'SPATA5L1', # HGNC 2022
BLTP1 => 'KIAA1109', # HGNC 2023
);
my %mis_oe;
if (open my $mc, "<", ref_file($CONSTRAINT_FILE)) {
while (my $l = <$mc>) {
next if $l =~ /^#/ || $l !~ /\S/;
chomp $l;
my ($g,$oe,$z,$flags) = split /\t/, $l;
next unless defined $oe && $oe ne "";
next if defined $flags && $flags =~ /outlier_mis|no_exp_mis/;
$mis_oe{$g} = $oe + 0;
}
close $mc;
printf "missense constraint (PP2): %d MANE genes loaded (mis.oe < %s -> constrained)\n",
scalar keys %mis_oe, $PP2_MIS_OE;
} else {
warn "NOTE: $CONSTRAINT_FILE not found — ACMG PP2 disabled (missense constraint unavailable)\n";
}
# Missense o/e for a gene symbol, falling back to its pre-rename symbol. Returns
# undef when the gene has no constraint record (PP2 then simply never fires).
sub mis_oe_for {
my ($g) = @_;
return undef unless defined $g && $g ne "";
return $mis_oe{$g} if exists $mis_oe{$g};
my $alias = $GENE_ALIAS{$g};
return (defined $alias && exists $mis_oe{$alias}) ? $mis_oe{$alias} : undef;
}
# ── Argument parsing ──
# --proband NAME (repeatable) force NAME as a proband, overriding filename-
# based auto-discovery. NAME must have <NAME>.germline.vep.vcf.gz.
# -l/--list FILE candidate-gene panel override (replaces default g4e-2026).
# The ONLY way to set the panel (no positional form). Applies
# to normal runs and to -v/--lookup variant consults alike.
#
# Gene panel: gene -> "Association \t MOI \t GDV".
# Default source = g4e-2026.txt (4 columns). A genes-of-interest file given via
# -l/--list (one gene symbol per line; plain symbols -> Association/MOI/GDV =
# "NA", or full 4-column g4e format) overrides it. '#' comments/blanks skipped.
my (@force_probands, $GENES_FILE, $LOOKUP_FILE, @VARIANTS);
my ($LOOKUP, $ALL_TX, $KEEP_VCF, $NO_SPLICE) = (0, 0, 0, 0);
# Carrier opt-in. By DEFAULT a solitary het carrier of a pure recessive (AR/XLR) gene is
# DROPPED (biallelic-only; carrier states are clinical noise, and true comp-hets are kept
# independently via the CompHet flag). Set KEEP_AR_CARRIERS=1 or --keep-ar-carriers to
# SURFACE the strong such carriers (carrier-only tier: strong-evidence & not benign,
# flagged flags=carrier-only; see the [#1,#2] block) — e.g. to chase a possible
# missed second hit (deep-intronic, CNV) in a targeted investigation.
my $KEEP_AR_CARRIERS = $ENV{KEEP_AR_CARRIERS} ? 1 : 0;
# Keep (don't drop) cohort recurrent-artifact variants, tagging them flags=
# cohort_artifact instead. Env KEEP_COHORT_ARTIFACTS=1 or CLI --keep-cohort-artifacts.
my $KEEP_COHORT_ARTIFACTS = $ENV{KEEP_COHORT_ARTIFACTS} ? 1 : 0;
while (@ARGV) {
my $a = shift @ARGV;
if ($a eq '--keep-ar-carriers') { $KEEP_AR_CARRIERS = 1; }
elsif ($a eq '--keep-cohort-artifacts') { $KEEP_COHORT_ARTIFACTS = 1; }
elsif ($a eq '--proband' || $a eq '-p') { push @force_probands, (shift @ARGV // ''); }
elsif ($a =~ /^--proband=(.+)$/) { push @force_probands, $1; }
elsif ($a eq '--lookup') { $LOOKUP = 1; $LOOKUP_FILE = (shift @ARGV // ''); }
elsif ($a =~ /^--lookup=(.+)$/) { $LOOKUP = 1; $LOOKUP_FILE = $1; }
elsif ($a eq '--variant' || $a eq '-v') { push @VARIANTS, (shift @ARGV // ''); }
elsif ($a =~ /^--variant=(.+)$/) { push @VARIANTS, $1; }
elsif ($a eq '--list' || $a eq '-l') { $GENES_FILE = (shift @ARGV // ''); } # candidate-gene panel override
elsif ($a =~ /^--list=(.+)$/) { $GENES_FILE = $1; }
elsif ($a eq '--all-transcripts') { $ALL_TX = 1; }
elsif ($a eq '--keep-vcf') { $KEEP_VCF = 1; }
elsif ($a eq '--no-splice') { $NO_SPLICE = 1; } # -v: skip Pangolin splice scoring
elsif ($a eq '--no-splice-discovery') { $SPLICE_PROBE = 0; } # skip the intronic/synonymous probe set
elsif ($a eq '--probe-uncovered') { $PROBE_REQUIRE_GNOMAD = 0; } # probe outside the gnomAD footprint (SLOW)
else {
die "unknown argument: '$a'\n".
" set the candidate-gene panel with -l/--list FILE (no positional form);\n".
" a single variant with -v/--variant '<v>' , a pre-annotated VCF with --lookup FILE;\n".
" keep recessive carriers with --keep-ar-carriers , cohort artifacts with --keep-cohort-artifacts;\n".
" skip the splice-discovery probe set with --no-splice-discovery ,\n".
" or widen it past the gnomAD footprint (SLOW) with --probe-uncovered .\n";
}
}
my $PANEL = (defined $GENES_FILE && $GENES_FILE ne "") ? $GENES_FILE : "g4e-2026.txt";
my $custom_panel = (defined $GENES_FILE && $GENES_FILE ne "") ? 1 : 0;
# Output tag = panel basename without extension, minus any trailing year suffix
# (e.g. g4e-2026.txt -> g4e, my_genes.txt -> my_genes).
# All per-run outputs are namespaced by it so different panels don't overwrite.
my $PANEL_TAG = $PANEL;
$PANEL_TAG =~ s{.*/}{};
$PANEL_TAG =~ s/\.[^.]+$//;
$PANEL_TAG =~ s/-\d{4}$//; # drop trailing year suffix (g4e-2026 -> g4e)
open PANEL, "<", ref_file($PANEL) or die "gene panel '$PANEL': $!";
my %epigenes;
while (my $g = <PANEL>) {
$g =~ s/\r?\n$//;
$g =~ s/^\s+|\s+$//g;
next if $g eq "" || $g =~ /^#/;
my @f = split /\t/, $g;
my $sym = $f[0];
$epigenes{$sym} = (@f >= 4) ? join("\t", $f[1], $f[2], $f[3]) : "NA\tNA\tNA";
}
close PANEL;
printf "gene panel: %s (%d genes%s)\n", $PANEL, scalar(keys %epigenes),
$custom_panel ? ", custom — missing Association/MOI/GDV = NA" : "";
# PP2 coverage. A panel gene with no constraint record can never earn PP2, and the
# failure is otherwise invisible — report it once at startup instead of letting the
# criterion go quietly missing for part of the panel.
if (%mis_oe) {
my @no_constraint = sort grep { !defined mis_oe_for($_) } keys %epigenes;
printf "PP2 coverage: %d/%d panel genes have gnomAD missense constraint%s\n",
scalar(keys %epigenes) - scalar(@no_constraint), scalar(keys %epigenes),
@no_constraint ? " — no record for: ".join(" ", @no_constraint) : "";
}
# Consequence whitelist (atomic terms recommended; compound entries harmless).
open VAR, "<", ref_file("typevar.txt") or die "typevar: $!";
my %varfilter;
while (my $t = <VAR>) { chomp $t; next if $t =~ /^#/ || $t !~ /\S/; my ($c,$d) = split /\t/, $t; $varfilter{$c} = $d//""; }
close VAR;
print "hash var, listo!\n";
# ACMG SF v3.2 genes: gene -> "condition \t MOI \t report_category". Always loaded
# (independent of the candidate panel). Non-fatal if absent.
my %acmg;
if (open my $afh, "<", ref_file($ACMG_FILE)) {
while (my $g = <$afh>) {
chomp $g; next if $g =~ /^#/ || $g !~ /\S/;
my ($sym,$cond,$moi,$cat) = split /\t/, $g;
$acmg{$sym} = join("\t", $cond//"", $moi//"AD", $cat//"ALL_PLP");
}
close $afh;
printf "ACMG SF: %d genes (secondary findings, always evaluated)\n", scalar keys %acmg;
} else {
warn "WARN: $ACMG_FILE not found — secondary findings (Incidental) disabled\n";
}
# ── ClinVar amino-acid evidence for PS1/PM5 (optional; graceful if absent) ──
# Built from the MANE-missense split; override the directory with $CLINVAR_AA_DIR.
my $CLINVAR_AA_DIR = $ENV{CLINVAR_AA_DIR} // ''; # set CLINVAR_AA_DIR in site.env (README section 0.6)
my $PLP_resid = load_clinvar_aa("$CLINVAR_AA_DIR/clinvar.MANE_missense.PLP.tsv");
my $BLB_resid = load_clinvar_aa("$CLINVAR_AA_DIR/clinvar.MANE_missense.BLB.tsv");
my $CLINVAR_AA_ON = (keys %$PLP_resid) ? 1 : 0;
if ($CLINVAR_AA_ON) {
printf "ClinVar AA evidence (PS1/PM5): %d P/LP residues, %d B/LB residues\n",
scalar(keys %$PLP_resid), scalar(keys %$BLB_resid);
} else {
warn "WARN: ClinVar missense P/LP resource not found"
. ($CLINVAR_AA_DIR ? " under $CLINVAR_AA_DIR" : " (CLINVAR_AA_DIR unset)")
. " — PS1/PM5 disabled. See README section 0.6.\n";
}
#############################################################################
# Helpers
#############################################################################
sub open_vcf {
my ($file) = @_;
my $fh;
if ($file =~ /\.gz$/) { open($fh,"-|","gzip","-dc",$file) or die "gzip $file: $!"; }
else { open($fh,"<",$file) or die "$file: $!"; }
return $fh;
}
# CSQ field name -> column index, from the ##INFO=<ID=CSQ ... Format: ...> header.
sub csq_columns {
my ($file) = @_;
my $fh = open_vcf($file);
my %col;
while (my $line = <$fh>) {
last if $line =~ /^#CHROM/;
next unless $line =~ /ID=CSQ/;
if ($line =~ /Format:\s*([^"]+)"/) {
my @n = split /\|/, $1;
$col{$n[$_]} = $_ for 0 .. $#n;
}
last if %col;
}
close $fh;
return \%col;
}
# Resolve a logical field to a CSQ index: exact name(s) first, then regex.
sub resolve {
my ($col, @cand) = @_;
for my $name (@cand) { return $col->{$name} if exists $col->{$name}; }
# sorted so the regex fallback binds deterministically if >1 header field matches
for my $pat (@cand) {
for my $name (sort keys %$col) { return $col->{$name} if $name =~ /$pat/i; }
}
return undef;
}
sub field {
my ($row,$i) = @_;
return "" unless defined $i;
my $v = $row->[$i];
return defined($v) ? $v : "";
}
# Parse one sample's FORMAT:SAMPLE -> (GT, DP, GQ, AD_ref, AD_alt).
sub parse_call {
my ($fmt,$smp) = @_;
return ("","","","","") unless defined $fmt && defined $smp;
my @k = split /:/, $fmt;
my @v = split /:/, $smp;
my %h; @h{@k} = @v;
my $gt = defined $h{GT} ? $h{GT} : "";
my $dp = defined $h{DP} ? $h{DP} : "";
my $gq = defined $h{GQ} ? $h{GQ} : "";
my ($ar,$aa) = ("","");
if (defined $h{AD} && $h{AD} ne "" && $h{AD} ne ".") {
my @ad = split /,/, $h{AD};
($ar,$aa) = ($ad[0]//"", $ad[1]//"");
}
return ($gt,$dp,$gq,$ar,$aa);
}
# Zygosity from a GT string: hom (alt/alt), het (ref/alt), hem (haploid alt), ref,
# or "" (no-call).
# HAPLOID CALLS: DRAGEN (and GATK with -ploidy 1) emit a single-allele GT — "1" or
# "0" — for non-PAR chrX/chrY in males and for chrM. Requiring two alleles made those
# calls return "", which silently cost them their zygosity (no HOM flag, no AR_hom
# rescue, no AB_hom QC) and, worse, made a hemizygous parent invisible to load_parent
# so an INHERITED X-linked variant was reported as de novo. A hemizygous call is a
# complete genotype, not half a het: it is reported as "hem" and treated as biallelic-
# equivalent everywhere the recessive logic asks "is this genotype sufficient?".
sub zygosity {
my ($gt) = @_;
return "" unless defined $gt && $gt ne "";
my @a = split /[\/|]/, $gt;
return "" unless @a && !grep { $_ eq "." || $_ eq "" } @a;
my $n1 = grep { $_ eq "1" } @a;
return $n1 ? "hem" : "ref" if @a == 1; # haploid (non-PAR X/Y male, chrM)
return $n1 >= 2 ? "hom" : $n1 == 1 ? "het" : "ref";
}
# Is this genotype a complete (non-carrier) recessive genotype on its own?
# Homozygous alt, or hemizygous alt on a haploid contig — both leave no second
# wild-type allele, so neither is a "carrier" state.
sub zyg_biallelic { my $z = shift // ""; return ($z eq "hom" || $z eq "hem") ? 1 : 0; }
# Parent carrier map: chr-pos-ref-alt -> "gt:dp:gq" if the parent carries the ALT
# (GT contains a '1'); records with 0/0 or no-call are NOT carriers. The DP/GQ are
# kept so inherited calls can report parental call quality [#6].
sub load_parent {
my ($file) = @_;
my %carry;
return \%carry unless defined $file && -e $file;
my $fh = open_vcf($file);
while (my $line = <$fh>) {
next if $line =~ /^#/;
chomp $line;
my @c = split /\t/, $line;
my ($chr,$pos,$ref,$alt,$fmt,$smp) = @c[0,1,3,4,8,9];
next if $alt =~ /,/; # should be pre-split
my ($gt,$dp,$gq) = parse_call($fmt,$smp);
my $z = zygosity($gt);
# "hem" counts: a hemizygous father IS a carrier of the allele he transmits.
$carry{"$chr-$pos-$ref-$alt"} = "$gt:$dp:$gq" if $z eq "het" || $z eq "hom" || $z eq "hem";
}
close $fh;
return \%carry;
}
# Pangolin score map: "chr-pos-ref-alt <tab> score".
sub load_scores {
my ($file) = @_;
my %s;
open(my $fh,"<",$file) or die "$file: $!";
while (my $l = <$fh>) { chomp $l; my ($id,$v) = split /\t/, $l; $s{$id} = $v if defined $v; }
close $fh;
return \%s;
}
# ── Cohort recurrent-artifact tally (internal panel-of-normals) [#11] ──
# Scan every cohort VCF once (GENOTYPES ONLY — no CSQ parse, so it is cheap) and
# count, per chr-pos-ref-alt, how many distinct samples carry the ALT plus their
# zygosity breakdown. Returns (\%carriers, \%hom, \%het, $n_samples). Sites-only
# files (no sample column) contribute no carriers. Used only for large cohorts
# (see $COHORT_MIN); never called in lookup / single-proband runs.
sub build_cohort_tally {
my ($files) = @_;
my (%ac, %hom, %het);
my $n = 0;
for my $f (@$files) {
next unless defined $f && -e $f;
$n++;
my $fh = open_vcf($f);
while (my $line = <$fh>) {
next if $line =~ /^#/;
chomp $line; # else the last field keeps its newline
my @c = split /\t/, $line;
next unless @c >= 10; # need FORMAT + >=1 sample column
my ($chr,$pos,$ref,$alt,$fmt,$smp) = @c[0,1,3,4,8,9];
next if $alt =~ /,/; # pre-split; skip residual multiallelic
my ($gt) = parse_call($fmt,$smp);
my $z = zygosity($gt);
next unless $z eq "het" || $z eq "hom" || $z eq "hem";
my $id = "$chr-$pos-$ref-$alt";
$ac{$id}++;
zyg_biallelic($z) ? $hom{$id}++ : $het{$id}++;
}
close $fh;
}
return (\%ac, \%hom, \%het, $n);
}
# Pure artifact decision: carried by >= $COHORT_MAX_FRAC of the cohort AND absent
# from gnomAD (joint AC == 0), with the cohort large enough (>= $COHORT_MIN) to be
# meaningful. Kept pure (no I/O) so run_cohort_selftest can exercise it directly.
sub cohort_artifact_call {
my ($carriers, $n, $gnomad_ac) = @_;
return 0 unless defined $n && $n >= $COHORT_MIN;
$carriers ||= 0;
$gnomad_ac ||= 0;
return 0 if $carriers < $COHORT_MIN_CARRIERS; # absolute floor (small batches)
return (($carriers / $n) >= $COHORT_MAX_FRAC && $gnomad_ac <= 0) ? 1 : 0;
}
# Distance into an intron from the nearest exon boundary, taken from the HGVSc offset
# (c.1234+56A>G -> 56; c.1235-30A>G -> 30). A range keeps its closest endpoint
# (c.100+5_100+12del -> 5). Returns undef when the annotation carries no offset, which is
# the case for anything that is not intronic — so callers must also check the consequence.
sub intron_offset {
my ($hgvsc) = @_;
return undef unless defined $hgvsc && $hgvsc =~ /c\./;
(my $c = $hgvsc) =~ s/^.*c\.//;
my $min;
while ($c =~ /[+-](\d+)/g) { $min = $1 if !defined $min || $1 < $min; }
return $min;
}
# Is this intronic variant outside the gnomAD resource footprint (exon +/- $GNOMAD_INTRON_PAD)?
# Only intronic records can be: exonic/UTR positions are always sliced in. A missing or
# unparsable HGVSc offset is treated as covered (no assertion without evidence).
sub gnomad_uncovered {
my ($csq, $hgvsc) = @_;
return 0 unless $csq =~ /(?:^|&)intron_variant(?:&|$)/;
my $off = intron_offset($hgvsc);
return (defined $off && $off > $GNOMAD_INTRON_PAD) ? 1 : 0;
}
# Is a consequence whitelisted? Pass if ANY '&'-separated atom is in the list.
sub consequence_ok {
my ($csq) = @_;
for my $atom (split /&/, $csq) { return 1 if exists $varfilter{$atom}; }
return 0;
}
# ClinVar classification helpers (on a CLNSIG-style string).
sub clinvar_pathogenic {
my ($s) = @_;
return 0 unless defined $s && $s ne "";
return 0 if $s =~ /conflicting/i;
return 0 if $s =~ /benign/i;
return ($s =~ /pathogenic/i) ? 1 : 0;
}
sub clinvar_benign {
my ($s) = @_;
return 0 unless defined $s && $s ne "";
return ($s =~ /benign/i && $s !~ /pathogenic/i) ? 1 : 0;
}
# ClinVar review status -> star count (0-4). Handles both the VEP CLNREVSTAT
# underscore form ("criteria_provided,_single_submitter") and the ClinVar TSV
# space form ("criteria provided, single submitter"). The "no assertion criteria
# provided" string contains "criteria provided" — guarded explicitly to 0 stars.
sub clinvar_stars {
my ($s) = @_;
return 0 unless defined $s && $s ne "";
my $t = lc $s; $t =~ tr/_/ /;
return 4 if $t =~ /practice guideline/;
return 3 if $t =~ /expert panel/;
return 2 if $t =~ /multiple submitter/;
return 0 if $t =~ /no assertion|no classification|no interpretation/;
return 1 if $t =~ /single submitter|conflicting|criteria provided/;
return 0;
}
# ── Mode-of-inheritance predicates over a panel/ACMG MOI string ──────────────
# A gene is "recessive-capable" if its MOI mentions AR/XLR/recessive, and
# "dominant-capable" if it mentions AD/XLD/dominant. Dual-inheritance genes
# (e.g. "AD, AR") satisfy BOTH — handled explicitly by the callers.
#
# PLAIN "XL" satisfies BOTH, deliberately. It is the Genes4Epilepsy vocabulary for
# an X-linked gene whose mechanism is not split into XLD/XLR — 72 of the 1078 g4e-2026
# genes, including CDKL5, MECP2, ARX, IQSEC2, PCDH19, DDX3X, ATRX, SLC6A8 and FLNA.
# Matching neither predicate (the previous behaviour) was an oversight, not a policy:
# those genes got no HOM/CompHet flag, never qualified for the AR_hom rescue, and were
# held to the strict dominant AF ceiling. Treating XL as dual-inheritance is the
# clinically safe reading — dominant-capable keeps a solitary het (these genes act
# dominantly in heterozygous females), recessive-capable earns a hemizygous/homozygous
# call its HEM/HOM flag and the AR_hom rescue. Same rule the "AD, AR" genes use.
# "XLR"/"XLD" keep their specific meaning: \bXL\b cannot match either.
sub moi_recessive { my $m = shift; return (defined $m && $m =~ /\bAR\b|XLR|\bXL\b|recessiv/i) ? 1 : 0; }
sub moi_dominant { my $m = shift; return (defined $m && $m =~ /\bAD\b|XLD|\bXL\b|dominant/i) ? 1 : 0; }
# ── Carrier-only tier gate ───────────────────────────────────────────────────
# Strong-evidence bar for SURFACING a solitary heterozygous carrier of a PURE
# recessive (AR/XLR) gene instead of dropping it (flagged flags=carrier-only).
# Mirrors the ACMG-SF strong gate: ClinVar P/LP (>=1 star) OR LOFTEE HC OR
# >=2 strong computational predictors (AM/CADD/EVE/REVEL). Takes a row data hashref.
sub carrier_strong_evidence {
my ($d) = @_;
return 1 if clinvar_pathogenic($d->{clinvar_sig}) && ($d->{clinvar_stars} // 0) >= 1;
return 1 if ($d->{loftee} // "") eq "HC";
my $n = 0;
$n++ if defined $d->{am_score} && $d->{am_score} ne "" && $d->{am_score} >= $SF_AM;
$n++ if defined $d->{cadd} && $d->{cadd} ne "" && $d->{cadd} >= $SF_CADD;
$n++ if ($d->{eve_class} // "") =~ /athogenic/;
$n++ if defined $d->{revel} && $d->{revel} ne "" && $d->{revel} >= $SF_REVEL;
return $n >= 2 ? 1 : 0;
}
# A candidate whose only classification is Benign / Likely-benign (ACMG auto-class
# or a non-conflicting ClinVar B/LB that is not itself P/LP). Excluded from the
# carrier-only tier — a benign carrier is noise, not a candidate.
sub is_benign_class {
my ($d) = @_;
return 1 if lc($d->{acmg_class} // "") =~ /benign/;
my $cs = lc($d->{clinvar_sig} // "");
return 1 if $cs =~ /benign/ && $cs !~ /conflict/
&& !(clinvar_pathogenic($d->{clinvar_sig}) && ($d->{clinvar_stars} // 0) >= 1);
return 0;
}
# Lexicographic ">" over two equal-length numeric preference arrays (used by the
# one-row-per-variant dedup to pick the row to keep).
sub _key_gt {
my ($a, $b) = @_;
for my $k (0 .. $#$a) {
return 1 if $a->[$k] > $b->[$k];
return 0 if $a->[$k] < $b->[$k];
}
return 0;
}
# ClinVar amino-acid-level evidence for PS1/PM5, built from the MANE-missense
# split (clinvar.MANE_missense.{PLP,BLB}.tsv). Returns a hashref keyed by
# "GENE\tAApos\tRefAA" -> { AltAA => { chr-pos-ref-alt => stars } }, so a candidate's
# residue can be checked for the SAME change (PS1) or a DIFFERENT pathogenic change
# (PM5). The innermost level records WHICH variant contributed each classification,
# which is what lets PS1 exclude the candidate's own ClinVar record (see aa_best_stars). A
# single-codon in-frame deletion of that residue also triggers PM5 (it is a
# different protein change at the same P/LP residue) — see the call site.
sub load_clinvar_aa {
my ($file) = @_;
my %resid;
return \%resid unless defined $file && -e $file;
open(my $fh, "<", $file) or do { warn "WARN: cannot read $file: $!\n"; return \%resid; };
<$fh>; # header
while (my $l = <$fh>) {
chomp $l;
my @f = split /\t/, $l;
# 1-based cols: 8 GeneSymbol, 11 ReviewStatus, 23 BB_AApos, 24 BB_RefAA, 28 AltAA
my ($gene,$rev,$aapos,$refAA,$altAA) = @f[7,10,22,23,27];
next unless defined $gene && defined $aapos && defined $refAA && defined $altAA;
next if $gene eq "" || $aapos eq "" || $refAA eq "" || $altAA eq "" || $refAA eq $altAA;
my $st = clinvar_stars($rev);
my $k = "$gene\t$aapos\t$refAA";
# Keyed per SOURCE VARIANT (cols 3-6: Chr, PositionVCF, Ref, Alt), not just per
# amino-acid change. PS1 requires a PREVIOUSLY established variant, so the record
# belonging to the variant under classification has to be identifiable and
# excluded — otherwise a variant that is itself ClinVar P/LP matches its own
# submission and earns PS1 on top of PP5 from that one record.
my ($vchr,$vpos,$vref,$valt) = @f[2,3,4,5];
my $vid = (defined $vchr && defined $vpos && defined $vref && defined $valt)
? "$vchr-$vpos-$vref-$valt" : "";
my $cur = $resid{$k}{$altAA}{$vid};
$resid{$k}{$altAA}{$vid} = $st if !defined $cur || $st > $cur;
}
close $fh;
return \%resid;
}
# Best review-star count among the ClinVar records carrying one amino-acid change,
# ignoring the record that IS the variant being classified ($self, "chr-pos-ref-alt";
# pass "" to consider every record). Returns 0 when nothing qualifies, so a variant
# whose only support is its own submission cannot earn PS1.
sub aa_best_stars {
my ($by_variant, $self) = @_;
return 0 unless ref $by_variant eq 'HASH';
my $best = 0;
for my $vid (keys %$by_variant) {
next if defined $self && $self ne "" && $vid eq $self;
my $st = $by_variant->{$vid};
$best = $st if defined $st && $st > $best;
}
return $best;
}
# Is an INDEL in/adjacent to a homopolymer run (>=5)? Error-prone context. [#7]
my %hp_cache;
sub homopolymer_context {
my ($chr,$pos,$ref,$alt) = @_;
return 0 unless $HAVE_REF;
return 0 if length($ref) == length($alt); # SNV/MNV only flag indels
my $key = "$chr-$pos";
return $hp_cache{$key} if exists $hp_cache{$key};
my $a = $pos - 12; $a = 1 if $a < 1;
my $b = $pos + 12;
my $seq = qx(samtools faidx "$REF_FASTA" "$chr:$a-$b" 2>/dev/null);
$seq =~ s/^>.*\n//; $seq =~ s/\s+//g;
my $hp = ($seq ne "" && $seq =~ /(.)\1{4,}/) ? 1 : 0;
return $hp_cache{$key} = $hp;
}
# Calibrated PP3/BP4 thresholds — AlphaMissense (Bergquist et al., GIM 2025) and
# REVEL (Pejaver et al., AJHG 2022).
my %AMP = (
am_pp3_strong=>0.990, am_pp3_mod=>0.906, am_pp3_supp=>0.792, # AM PP3 (no BP4 strong)
am_bp4_mod =>0.099, am_bp4_supp=>0.169, # AM BP4
rv_pp3_strong=>0.932, rv_pp3_mod=>0.773, rv_pp3_supp=>0.644, # REVEL PP3
rv_bp4_strong=>0.016, rv_bp4_mod=>0.183, rv_bp4_supp=>0.290, # REVEL BP4
);
# Automated ACMG/AMP classification (TRIAGE ONLY — not a final clinical call).
# Criteria are combined per $COMBINER: Tavtigian-2020 points (default) or the
# categorical ACMG 2015 rules. PP3/BP4 come from a single CALIBRATED tool —
# AlphaMissense primary, REVEL fallback — graded Supporting/Moderate/Strong with
# a REVEL direction-conflict veto (categorical counting squashes BP4_Moderate to
# supporting-benign, since 2015 has no benign-Moderate tier; the points sum keeps
# its true -2). A Pangolin score >= $SPLICE_SUPP adds splice PP3_Supporting when
# no missense grade and no full PVS1 apply. Returns (class, criteria, points);
# points are computed in both modes. [#2]
sub acmg_classify {
my (%v) = @_;
my (@P,@B);
# Pathogenic criteria
# PVS1 with partial Tayoun-2018 granularity: start_lost caps at MODERATE
# (PVS1_Moderate) — translation can re-initiate at a downstream or alternative
# start, so a lost canonical start codon is weaker evidence than a mid-gene
# truncation. A compound consequence carrying another LoF atom (e.g.
# start_lost&splice_donor_variant) still earns full PVS1 through that atom.
# The remaining Tayoun granularity (last-exon/NMD-escape downgrades, gene
# LoF-mechanism check) stays with the curator.
my @lof_atoms = grep { $LOF_CONS{$_} } split /&/, ($v{consequence} // "");
my $lof_other = grep { $_ ne 'start_lost' } @lof_atoms;
my $pvs1 = ($v{loftee} eq "HC" || ($lof_other && $v{loftee} ne "LC")) ? 1 : 0;
my $pvs1_mod = (!$pvs1 && (grep { $_ eq 'start_lost' } @lof_atoms)
&& $v{loftee} ne "LC") ? 1 : 0;
push @P, "PVS1" if $pvs1;
push @P, "PVS1_Moderate" if $pvs1_mod;
# De novo: PS2 (confirmed-quality trio DN) / PM6 (assumed). BOTH now require a
# dominant-capable panel MOI (AD/XLD/XL/dual) — de novo occurrence of a het
# supports nothing under pure-recessive inheritance. The duo path always had
# this gate; the trio path previously skipped it. Under a panel with MOI=NA
# (plain-symbol custom list) neither fires, matching the documented PM6 rule.
if ($v{inh} eq "DN") { # trio de novo (relatedness assumed)
push @P, ($v{gt_clean} ? "PS2" : "PM6") if $v{de_novo_mech};
} elsif ($v{inh} =~ m{^DN/} && $v{de_novo_mech}) { push @P, "PM6"; }
# PM4 is evidence for a protein-length change; PVS1 already covers the loss-of-
# function reading of the same event. VEP compound terms make them collide
# (start_lost&inframe_deletion, frameshift_variant&stop_lost) because $lof_type is
# matched per '&'-atom while this regex matches the whole string — two ACMG lines
# from one protein-terminus effect, which pushes an LP call to Pathogenic.
push @P, "PM4" if !$pvs1 && !$pvs1_mod && $v{consequence} =~ /inframe_(insertion|deletion)|stop_lost/;
# PM2 at the configured strength (see $PM2_STRENGTH). Written as PM2_Supporting when
# downgraded so the criteria string says which reading produced the class.
# "Absent from gnomAD" is only assertable where gnomAD actually looked. A splice
# probe rescued from outside the MANE-restricted resource has AN=0 because the position
# is not IN the resource, not because the allele is unobserved — awarding PM2 there
# would manufacture pathogenic evidence out of an annotation gap. Scoped to probe rows
# and to whitelisted intronic rows beyond the footprint ($v{uncovered}, see
# $GNOMAD_INTRON_PAD), so ordinary candidates inside the footprint are unaffected.
my $ac_assertable = !(($v{probe} || $v{uncovered}) && ($v{an} // 0) <= 0);
push @P, ($PM2_STRENGTH eq 'moderate' ? "PM2" : "PM2_Supporting")
if $ac_assertable && $v{ac} ne "" && $v{ac} <= $PM2_AC_MAX; # absent or singleton
# PP5 requires >=1 review star, like the other ClinVar consumers in this file
# (Stage-1 exemption, ACMG-SF tier, carrier tier, BP6) — the one deliberate
# exception is the star-less ClinVar RESCUE arm, which only keeps a row for
# curation and asserts no ACMG criterion. Without the gate a single
# 0-star "no assertion criteria provided" submission — ~16% of the P/LP corpus —
# supplied the criterion that lifts an LP call to Pathogenic.
push @P, "PP5" if clinvar_pathogenic($v{clnsig}) && ($v{clnstar} // 0) >= 1;
# PS1 (same AA change P/LP) or PM5 (different change, same residue P/LP), from
# the ClinVar AA resource; conflicting matches are tagged but still counted (triage).
push @P, $v{aa_crit} . ($v{aa_conflict} ? "(conflicting)" : "") if $v{aa_crit};
# PP3 / BP4: single calibrated tool (AM primary, REVEL fallback), graded
# Supporting/Moderate/Strong, with a REVEL direction-conflict veto.
my ($am,$rv) = ($v{am_score}, $v{revel});
my ($pp3,$bp4) = ("","");
if ($am ne "") { # AlphaMissense primary
$pp3 = ($am >= $AMP{am_pp3_strong}) ? "strong"
: ($am >= $AMP{am_pp3_mod}) ? "moderate"
: ($am >= $AMP{am_pp3_supp}) ? "supporting" : "";
$bp4 = ($am <= $AMP{am_bp4_mod}) ? "moderate"
: ($am <= $AMP{am_bp4_supp}) ? "supporting" : "";
if ($rv ne "") { # REVEL direction-conflict veto
$pp3 = "" if $pp3 && $rv <= $AMP{rv_bp4_supp}; # secondary calls benign
$bp4 = "" if $bp4 && $rv >= $AMP{rv_pp3_supp}; # secondary calls pathogenic
}
} elsif ($rv ne "") { # REVEL fallback (AM absent)
$pp3 = ($rv >= $AMP{rv_pp3_strong}) ? "strong"
: ($rv >= $AMP{rv_pp3_mod}) ? "moderate"
: ($rv >= $AMP{rv_pp3_supp}) ? "supporting" : "";
$bp4 = ($rv <= $AMP{rv_bp4_strong}) ? "strong"
: ($rv <= $AMP{rv_bp4_mod}) ? "moderate"
: ($rv <= $AMP{rv_bp4_supp}) ? "supporting" : "";
}
# Splice PP3, SUPPORTING ONLY: Pangolin >= $SPLICE_SUPP is calibrated splice-
# damage evidence (SpliceAI-analogous 0.2, Walker 2023; no published Pangolin
# calibration supports a higher tier). Never stacked on full PVS1 — a canonical
# splice LoF is one splicing effect, not two evidence lines (ClinGen SVI).
# A missense-based PP3 grade keeps precedence (max, not sum), and a splice
# signal at/above the boundary vetoes computational-benign BP4, the same
# direction-conflict treatment the REVEL veto applies.
if (!$pvs1 && ($v{pangolin} // "") ne "" && $v{pangolin} >= $SPLICE_SUPP) {
$pp3 = "supporting" if !$pp3;
$bp4 = "";
}
push @P, "PP3_".ucfirst($pp3) if $pp3;
push @B, "BP4_".ucfirst($bp4) if $bp4;
# PM1: the variant falls in a PERv1 pathogenic-variant-enriched region naming
# THIS gene (Perez-Palma et al., Genome Res 2020, whose stated application is PM1).
# Two arms, both published:
# PERv1_direct — enrichment computed on this gene. Graded by its own fold
# enrichment at the Tavtigian-2018 calibration the paper cites:
# >= 18.7 counts at Strong, else Moderate.
# PERv1_paralog — enrichment computed across the paralog family alignment and
# assigned to every member, including members carrying none of
# the underlying variants. This is the paper's headline arm
# (1,252 genes vs 215) and the one its held-out de novo test
# validated. Capped at Moderate upstream: the transfer step
# costs a tier.
# Restricted to missense and in-frame indels, which is what the region was
# computed from -- a PER is a missense-burden statement, so it lends nothing to a
# splice, synonymous or LoF call (and PVS1 already covers the last).
# Deliberately NOT suppressed when BP4 fires: unlike PP2 (gene-level constraint),
# PM1 here is regional evidence independently validated against held-out de novo
# variants, so a benign computational prediction does not negate it.
# $1 is captured BEFORE the consequence match: a second successful regex with no
# capture groups clears it, which silently downgraded every PM1_Strong to PM1.
my $pm1_st = ($v{pm1} // "") =~ /^(Strong|Moderate)$/ ? $1 : "";
if ($pm1_st ne ""
&& $v{consequence} =~ /missense_variant|inframe_(?:insertion|deletion)/) {
push @P, ($pm1_st eq "Strong" ? "PM1_Strong" : "PM1");
}
# PP2: missense in a gene with a low rate of benign missense variation, from
# gnomAD v4.1.1 missense constraint (mis.oe < $PP2_MIS_OE on the MANE transcript;
# constraint outliers already excluded at load). PP2 counts INDEPENDENTLY of PP3
# (both are legitimate, separate ACMG lines — gene-level missense intolerance vs the
# variant-level predictor — and ACMG 2015 permits combining them). It is still
# suppressed when BP4 fired: a variant the calibrated tool predicts BENIGN must not
# also collect gene-level pathogenic support (a genuine contradiction, not just
# correlation). To let PP2 fire even alongside BP4, drop the "!$bp4" guard.
push @P, "PP2" if $v{consequence} =~ /missense/
&& defined $v{mis_oe} && $v{mis_oe} ne "" && $v{mis_oe} < $PP2_MIS_OE
&& !$bp4;
# Benign criteria
push @B, "BA1" if $v{freq} >= $BA1_FREQ;
push @B, "BS1" if $v{freq} >= $BS1_FREQ && $v{freq} < $BA1_FREQ;
push @B, "BS2" if $v{nhom} ne "" && $v{nhom} >= $BS2_NHOM;
push @B, "BP6" if clinvar_benign($v{clnsig}) && ($v{clnstar} // 0) >= 1;
# BP7 requires POSITIVE evidence of no splice impact, so it fires only when a
# Pangolin score actually exists. An unscored variant is unknown, not benign:
# treating a missing score as 0 would assert benign-supporting evidence on