-
Notifications
You must be signed in to change notification settings - Fork 115
Expand file tree
/
Copy pathadd_annotations.py
More file actions
2641 lines (2297 loc) · 108 KB
/
add_annotations.py
File metadata and controls
2641 lines (2297 loc) · 108 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 python
import argparse
import hail as hl
import logging
import re
import sys
import numpy as np
import sys, os
sys.path.append('/home/jupyter/')
from collections import Counter
from textwrap import dedent
from gnomad.utils.annotations import age_hists_expr
from gnomad.utils.reference_genome import add_reference_sequence
from gnomad.utils.slack import slack_notifications
from gnomad.utils.vep import vep_struct_to_csq
from gnomad_qc.v3.resources.meta import meta # pylint: disable=import-error
from gnomad.resources.grch38.gnomad import POPS
from gnomad.resources.grch38.reference_data import dbsnp, _import_dbsnp
from gnomad_mitochondria.pipeline.annotation_descriptions import (
add_descriptions,
adjust_descriptions,
)
from generate_mtdna_call_mt.merging_constants import *
# Github repo locations for imports:
# gnomad: https://github.com/broadinstitute/gnomad_methods
# gnomad_qc: https://github.com/broadinstitute/gnomad_qc
# Include NA in POPS to account for cases where population annotations are missing
POPS = POPS["v3"]["genomes"]
POPS.append("NA")
#hl.init(tmp_dir="file:///tmp")
#hl.init(tmp_dir=f"{os.environ['WORKSPACE_BUCKET']}/tmp",
# local_tmpdir="file:///tmp",
# spark_conf={"spark.local.dir": "file:///tmp"})
RESOURCE_PATH = 'gcp-public-data--gnomad/resources/mitochondria'
RESOURCES = {
"variant_context": f"gs://{RESOURCE_PATH}/variant_context/chrM_pos_ref_alt_context_categories.txt",
"phylotree": f"gs://{RESOURCE_PATH}/phylotree/rCRS-centered_phylo_vars_final_update.txt",
"pon_mt_trna": f"gs://{RESOURCE_PATH}/trna_predictions/pon_mt_trna_predictions_08_27_2020.txt",
"mitotip": f"gs://{RESOURCE_PATH}/trna_predictions/mitotip_scores_08_27_2020.txt",
}
logging.basicConfig(
format="%(asctime)s (%(name)s %(lineno)s): %(message)s",
datefmt="%m/%d/%Y %I:%M:%S %p",
)
logger = logging.getLogger("add annotations")
logger.setLevel(logging.INFO)
_HAIL_VERSION_MINOR = int(hl.version().split('-')[0].split('.')[2])
def add_genotype(mt_path: str, min_hom_threshold: float = 0.95) -> hl.MatrixTable:
"""
STABLE
Add in genotype annotation based on heteroplasmy level.
If the heteroplasmy level is above the min_hom_threshold, set the genotype to 1/1.
If the heteroplasmy level is less than the min_hom_threshold, but greater than 0, set the genotype to 0/1.
Otherwise set the genotype to 0/0.
:param mt_path: Path to the MatrixTable (this MatrixTable can be generated by running combine_vcfs.py)
:param min_hom_threshold: Minimum heteroplasmy level to define a variant as homoplasmic
:return: MatrixTable with GT field added
"""
logger.info("Reading in MT...")
mt = hl.read_matrix_table(mt_path)
# Add in genotype (GT) based on min_hom_threshold
mt = mt.annotate_entries(
GT=(
hl.case()
.when((mt.HL < min_hom_threshold) & (mt.HL > 0.0), hl.parse_call("0/1"))
.when(mt.HL >= min_hom_threshold, hl.parse_call("1/1"))
.when(mt.HL == 0, hl.parse_call("0/0"))
.default(hl.missing(hl.tcall))
),
)
return mt
def add_variant_context(input_mt: hl.MatrixTable) -> hl.MatrixTable:
"""
STABLE
Add variant context annotations to the MatrixTable.
This fucntion adds in information on regions/strand for SNPs that can be useful for determining mutational signatures.
:param input_mt: MatrixTable
:return: MatrixTable with variant context information added
"""
# Read in variant context data
vc_ht = hl.import_table(RESOURCES["variant_context"], impute=True)
# Split columns into separate annotations
vc_ht = vc_ht.annotate(
ref=vc_ht["POS.REF.ALT"].split(r"\.")[1],
alt=vc_ht["POS.REF.ALT"].split(r"\.")[2],
strand=vc_ht.Context_category.split("_")[-1],
variant=vc_ht.Context_category.split("_")[0],
)
# Rename and select certain columns
vc_ht = vc_ht.rename({"MT_POS": "pos", "Annotation": "region"})
vc_ht = vc_ht.select("pos", "ref", "alt", "strand", "region", "variant")
# Key by locus and allele
vc_ht = vc_ht.key_by(
locus=hl.locus("MT", vc_ht.pos, reference_genome="GRCh37"),
alleles=[vc_ht.ref, vc_ht.alt],
)
# Annotate original mt with variant context information
input_mt = input_mt.annotate_rows(**vc_ht[input_mt.locus, input_mt.alleles])
input_mt = input_mt.annotate_rows(
variant_context=hl.str(input_mt.variant) + "_" + hl.str(input_mt.strand)
)
input_mt = input_mt.drop("pos", "ref", "alt", "strand", "variant")
return input_mt
def add_gnomad_metadata(input_mt: hl.MatrixTable) -> hl.MatrixTable:
"""
Add select gnomAD metadata to the MatrixTable.
:param input_mt: MatrixTable
:return: MatrixTable with select gnomAD metadata added
"""
# TODO: Add option here to accomodate non-gnomAD metadata
genome_meta_ht = meta.versions["3.1"].ht()
genome_meta_struct = genome_meta_ht[input_mt.s]
input_mt = input_mt.annotate_cols(
release=genome_meta_struct.release,
hard_filters=genome_meta_struct.sample_filters.hard_filters,
research_project=genome_meta_struct.project_meta.research_project,
project_id=genome_meta_struct.project_meta.project_id,
product=genome_meta_struct.project_meta.product,
sample_pi=genome_meta_struct.project_meta.sample_pi,
sex_karyotype=genome_meta_struct.sex_imputation.sex_karyotype,
age=hl.if_else(
hl.is_defined(genome_meta_struct.project_meta.age),
genome_meta_struct.project_meta.age,
genome_meta_struct.project_meta.age_alt,
),
broad_external=genome_meta_struct.project_meta.broad_external,
pop=genome_meta_struct.population_inference.pop,
)
return input_mt
def add_age_and_pop(input_mt: hl.MatrixTable, participant_data: str) -> hl.MatrixTable:
"""
STABLE
Add sample-level metadata for age and pop to `input_mt`.
:param input_mt: MatrixTable
:param participant_data: Path to metadata file downloaded from Terra that contains sample age and pop information
:return: MatrixTable with select age and pop annotations added
"""
ht = hl.import_table(
participant_data,
types={"age": hl.tint32, "pop": hl.tstr},
missing=["", "NA", "NaN", "nan"],
).key_by("s")
ht = ht.select("age", "pop")
input_mt = input_mt.annotate_cols(**ht[input_mt.col_key])
# If a sample doesn't have an annotated population, set it to the string "NA"
input_mt = input_mt.annotate_cols(
pop=hl.if_else(hl.is_missing(input_mt.pop), "NA", input_mt.pop)
)
return input_mt
def filter_by_hom_overlap(input_mt: hl.MatrixTable, keep_all_samples: bool, sample_stats: str):
stat_ht = hl.import_table(sample_stats, impute=True, key='s', types={'s':hl.tstr})
input_mt = input_mt.annotate_cols(num_mt_overlaps = stat_ht[input_mt.col_key].mtdna_consensus_overlaps)
n_removed = input_mt.aggregate_cols(hl.agg.count_where(input_mt.num_mt_overlaps > 0))
if not keep_all_samples:
input_mt = input_mt.filter_cols(input_mt.num_mt_overlaps == 0)
return input_mt.drop('num_mt_overlaps'), n_removed
def filter_by_copy_number(
input_mt: hl.MatrixTable, keep_all_samples: bool = False, max_cn: int = 500
) -> hl.MatrixTable:
"""
Calculate the mitochondrial copy number based on mean mitochondrial coverage and median nuclear coverage. Filter out samples with more extreme copy numbers.
Note that median and mean coverage for mitochondria are very similar. Mean mitochondria coverage was used based on metrics available at the time, but releases will switch to using median mitochondria coverage.
:param hl.MatrixTable input_mt: MatrixTable
:param keep_all_samples: If True, keep all samples (calculate mitochondrial copy number, but do not filter any samples based on this metric)
:return: MatrixTable filtered to samples with a copy number of at least 50 and less than 500, number samples below 50 removed, number samples above 500 removed
"""
# Calculate mitochondrial copy number, if median autosomal coverage is not present default to a wgs_median_coverage of 30x
input_mt = input_mt.annotate_cols(
mito_cn=2
* input_mt.mt_mean_coverage
/ hl.if_else(
hl.is_missing(input_mt.wgs_median_coverage),
30,
input_mt.wgs_median_coverage,
)
)
n_removed_below_cn = input_mt.aggregate_cols(
hl.agg.count_where(input_mt.mito_cn < 50)
)
n_removed_above_cn = input_mt.aggregate_cols(
hl.agg.count_where(input_mt.mito_cn > max_cn)
)
if not keep_all_samples:
# Remove samples with a mitochondrial copy number below 50 or greater than 500
input_mt = input_mt.filter_cols(
(input_mt.mito_cn >= 50) & (input_mt.mito_cn <= max_cn)
)
input_mt = input_mt.filter_rows(hl.agg.any(input_mt.HL > 0))
return input_mt, n_removed_below_cn, n_removed_above_cn
def filter_by_contamination(
input_mt: hl.MatrixTable, output_dir: str, keep_all_samples: bool = False
) -> hl.MatrixTable:
"""
Calculate contamination based on internal algorithm and filter out samples with contamination above 2%.
Contamination takes into account:
a) mitochondria contamination output by HaploCheck
b) nuclear contamination (freemix) output by VerifyBamID
c) an internal algorithm with utilizes the PASS haplogroup-defining variants which should be homoplasmic (100% alternate alleles), but in contaminated samples show multiple alleles with heteroplasmy 85-99.8%
:param input_mt: MatrixTable
:param output_dir: Output directory to which results should be written
:param keep_all_samples: If True, keep all samples (calculate contamination, but do not filter any samples based on this metric)
:return: MatrixTable filtered to samples without contamination, number of contaminated samples removed
"""
# Generate expression for genotypes with >= 85% heteroplasmy and no FT filters at haplogroup-defining sites that are not filtered as artifact-prone sites
over_85_expr = (
(input_mt.HL >= 0.85)
& (input_mt.FT == {"PASS"})
& input_mt.hap_defining_variant
& ~hl.str(input_mt.filters).contains("artifact_prone_site")
)
input_mt = input_mt.annotate_cols(
over_85_mean=hl.agg.filter(over_85_expr, hl.agg.mean(input_mt.HL)),
over_85_count=hl.agg.filter(
over_85_expr, hl.agg.count_where(hl.is_defined(input_mt.HL))
),
bt_85_and_99_mean=hl.agg.filter(
over_85_expr & (input_mt.HL <= 0.998), hl.agg.mean(input_mt.HL)
),
bt_85_and_99_count=hl.agg.filter(
over_85_expr & (input_mt.HL <= 0.998),
hl.agg.count_where(hl.is_defined(input_mt.HL)),
),
)
input_mt = input_mt.annotate_cols(
contam_high_het=hl.if_else(
input_mt.bt_85_and_99_count >= 3,
1 - input_mt.bt_85_and_99_mean,
1 - input_mt.over_85_mean,
)
)
# If contam_high_het is nan, set to 0 (to avoid filtering out missing values which would be more common with haplogroups closer to the reference haplogroup)
input_mt = input_mt.annotate_cols(
contam_high_het=hl.if_else(
hl.is_nan(input_mt.contam_high_het), 0, input_mt.contam_high_het
)
)
# Find samples on border of .02 that may flip between < 0.02 and > 0.02 from issues with floating point precision and mark these samples for removal
epsilon = 0.000001
border_samples = input_mt.aggregate_cols(
hl.agg.filter(
(input_mt.contam_high_het > (0.02 - epsilon))
& (input_mt.contam_high_het < (0.02 + epsilon)),
hl.agg.collect((input_mt.s)),
)
)
border_samples = (
hl.literal(border_samples) if border_samples else hl.empty_array(hl.tstr)
)
# Add annotation to keep only samples with a contamination less than 2%
input_mt = input_mt.annotate_cols(freemix_percentage_imp = hl.if_else(hl.is_missing(input_mt.freemix_percentage), 0, input_mt.freemix_percentage))
input_mt = input_mt.annotate_cols(
keep=(input_mt.contamination < 0.02)
& (input_mt.freemix_percentage_imp < 2)
& (input_mt.contam_high_het < 0.02)
& ~border_samples.contains(input_mt.s)
)
# Save sample contamination information to separate file
n_contaminated = input_mt.aggregate_cols(hl.agg.count_where(~input_mt.keep))
sample_data = input_mt.select_cols(
"contamination",
"freemix_percentage",
"contam_high_het",
"over_85_mean",
"over_85_count",
"bt_85_and_99_mean",
"bt_85_and_99_count",
"keep",
)
data_export = sample_data.cols()
data_export.export(f"{output_dir}/sample_contamination.tsv")
if not keep_all_samples:
logger.info(
"Removing %d samples with contamination above 2 percent", n_contaminated
)
input_mt = input_mt.filter_cols(input_mt.keep)
input_mt = input_mt.drop("keep")
input_mt = input_mt.filter_rows(hl.agg.any(input_mt.HL > 0))
return input_mt, n_contaminated
def add_terra_metadata(
input_mt: hl.MatrixTable, participant_data: str
) -> hl.MatrixTable:
"""
STABLE
Add Terra metadata to the MatrixTable.
The participant_data file can be obtained by downloading the participant data after running Mutect2 in Terra. This file should contain the following columns:
- entity:participant_id: Participant ID uploaded to Terra by user
- s: Sample ID uploaded to Terra by user
- contamination: Output by Mutect2, gives the estimate of mitochondrial contamination
- freemix_percentage: Uploaded to Terra by user, can be calculated with VerifyBamID
- major_haplogroup: Output by Mutect2 which utilizes Haplogrep
- wgs_median_coverage: Uploaded to Terra by user, can be calculated with Picard's CollectWgsMetrics
- mt_mean_coverage: Output by Mutect2, gives the mean mitochondrial coverage
:param input_mt: MatrixTable
:param participant_data: Path to metadata file downloaded from Terra
:return: MatrixTable with Terra metadata annotations added
"""
# Add haplogroup and Mutect2/Terra output annotations
ht = hl.import_table(
participant_data,
types={
"contamination": hl.tfloat64,
"freemix_percentage": hl.tfloat64,
"mt_mean_coverage": hl.tfloat64,
"wgs_median_coverage": hl.tfloat64,
},
missing=["","NA"],
).key_by("s")
ht = ht.rename({"entity:participant_id": "participant_id"})
ht = ht.select(
"participant_id",
"contamination",
"freemix_percentage",
"major_haplogroup",
"wgs_median_coverage",
"mt_mean_coverage",
)
input_mt = input_mt.annotate_cols(**ht[input_mt.s])
# Annotate the high level haplogroup by taking the first letter, with the exception of H and L haplogroups which are more commonly referred to using the first two letters
input_mt = input_mt.annotate_cols(
hap=hl.if_else(
input_mt.major_haplogroup.startswith("HV")
| input_mt.major_haplogroup.startswith("L"),
input_mt.major_haplogroup[0:2],
input_mt.major_haplogroup[0],
)
)
return input_mt
def fill_missing_mt_mean_coverage_from_covdb(
input_mt: hl.MatrixTable,
coverage_h5_path: str | None,
position_block_size: int = 1024,
logger: logging.Logger | None = None,
) -> hl.MatrixTable:
"""Fill missing mt_mean_coverage using coverage.h5 (covdb) block reads.
This reuses the same covdb read strategy as finalize and avoids loading
the full (sample × position) matrix into Hail.
"""
if not coverage_h5_path:
return input_mt
log = logger if logger is not None else logging.getLogger(__name__)
ht_cols = input_mt.cols()
ht_cols = ht_cols.select(mt_mean_coverage=ht_cols.mt_mean_coverage)
col_rows = ht_cols.collect()
missing_samples = [r.s for r in col_rows if r.mt_mean_coverage is None]
if not missing_samples:
return input_mt
from generate_mtdna_call_mt.covdb_utils import open_covdb_index, read_covdb_block
log.info(
"Filling mt_mean_coverage for %d samples using covdb %s",
len(missing_samples),
coverage_h5_path,
)
idx = open_covdb_index(coverage_h5_path)
missing_indices = []
missing_lookup = []
for s in missing_samples:
cov_i = idx.sample_to_index.get(s)
if cov_i is None:
raise ValueError(
f"Sample {s} missing from coverage.h5 /sample_id"
)
missing_indices.append(int(cov_i))
missing_lookup.append(s)
ht_rows = input_mt.rows()
pos_ht = (
ht_rows.select(pos=hl.int32(ht_rows.locus.position))
.distinct()
.order_by("pos")
)
positions = [int(r.pos) for r in pos_ht.collect()]
if not positions:
return input_mt
pos_to_covdb_col = {p: idx.pos_to_index.get(p) for p in positions}
missing_pos = [p for p, ci in pos_to_covdb_col.items() if ci is None]
if missing_pos:
raise ValueError(
f"{len(missing_pos)} MT positions missing from coverage.h5 /pos (first 5: {missing_pos[:5]})"
)
sample_indices = np.array(missing_indices, dtype=np.int64)
sums = np.zeros(len(sample_indices), dtype=np.float64)
total_positions = 0
for start in range(0, len(positions), position_block_size):
block = positions[start : start + position_block_size]
covdb_cols_block = np.array(
[pos_to_covdb_col[p] for p in block], dtype=np.int64
)
cov_block = read_covdb_block(
h5_path=coverage_h5_path,
sample_indices=sample_indices,
pos_indices=covdb_cols_block,
)
sums += cov_block.sum(axis=1)
total_positions += cov_block.shape[1]
if total_positions == 0:
return input_mt
mean_cov = (sums / float(total_positions)).tolist()
mt_mean_by_sample = {
s: float(m) for s, m in zip(missing_lookup, mean_cov)
}
mean_cov_hl = hl.literal(mt_mean_by_sample)
input_mt = input_mt.annotate_cols(
mt_mean_coverage=hl.if_else(
hl.is_missing(input_mt.mt_mean_coverage),
mean_cov_hl.get(input_mt.s),
input_mt.mt_mean_coverage,
)
)
return input_mt
def add_hap_defining(input_mt: hl.MatrixTable) -> hl.MatrixTable:
"""
STABLE
Add bool on whether or not a variant is a haplogroup-defining variant to the MatrixTable.
Haplogroup-defining annotations were obtained from PhyloTree Build 17.
:param input_mt: MatrixTable
:return: MatrixTable with annotation on whether or not the variant is haplogroup-defining added
"""
# TODO: move dataset location
hap_defining_variants = hl.import_table(RESOURCES["phylotree"])
hap_defining = hl.literal(set(hap_defining_variants.variant.collect()))
input_mt = input_mt.annotate_rows(
variant_collapsed=input_mt.alleles[0]
+ hl.str(input_mt.locus.position)
+ input_mt.alleles[1]
)
input_mt = input_mt.annotate_rows(
hap_defining_variant=hap_defining.contains(input_mt.variant_collapsed)
) # set hap_defining_variant to True or False
return input_mt
def add_trna_predictions(input_mt: hl.MatrixTable, avoid_fasta_workaround: bool) -> hl.MatrixTable:
"""
STABLE
Add tRNA predictions on pathogenicity from PON-mt-tRNA and MitoTIP to the MatrixTable.
:param input_mt: MatrixTable
:param avoid_fasta_workaround: bool
:return: MatrixTable with tRNA predictions of pathogenicity added
"""
# Add PON-mt-tRNA predictions
pon_predictions = hl.import_table(RESOURCES["pon_mt_trna"])
# If reference allele from fasta doesn't match Reference_nucleotide, PON-mt-tRNA is reporting the allele of opposite strand and need to get reverse complement for ref and alt
if not avoid_fasta_workaround:
# as a workaround for some hail weirdness, we are going to manually grab the GRCh37 sequence
tab_workaround = hl.import_table(RESOURCES['variant_context'])
tab_workaround = tab_workaround.select(pos = hl.int(tab_workaround.MT_POS),
REF = tab_workaround["POS.REF.ALT"].split('\.')[1])
tab_workaround = tab_workaround.key_by('pos','REF').distinct()
tab_workaround = tab_workaround.key_by('pos')
pon_predictions = pon_predictions.annotate(
ref=tab_workaround[hl.int(pon_predictions.mtDNA_position)].REF
)
# confirm that the workaround produces the correct results
#add_reference_sequence(hl.get_reference("GRCh37"))
#tab_workaround = tab_workaround.annotate(REF_corr = hl.get_sequence('MT', tab_workaround.pos, reference_genome='GRCh37'))
#tab_workaround.filter(tab_workaround.REF_corr != tab_workaround.REF).count() # > 0
else:
add_reference_sequence(hl.get_reference("GRCh37"))
pon_predictions = pon_predictions.annotate(
ref=hl.get_sequence(
"MT", hl.int(pon_predictions.mtDNA_position), reference_genome='GRCh37'
)
)
n_miss_ref = pon_predictions.filter(~hl.is_defined(pon_predictions.ref)).count()
if n_miss_ref != 0:
raise ValueError('ERROR: pon predictions table has undefined reference sequences.')
pon_predictions = pon_predictions.annotate(
alt=hl.if_else(
pon_predictions.Reference_nucleotide == pon_predictions.ref,
pon_predictions.New_nucleotide,
hl.reverse_complement(pon_predictions.New_nucleotide),
)
)
pon_predictions = pon_predictions.key_by(
variant_id=pon_predictions.ref
+ hl.str(pon_predictions.mtDNA_position)
+ pon_predictions.alt
)
input_mt = input_mt.annotate_rows(
pon_mt_trna_prediction=pon_predictions[input_mt.variant_collapsed]
.Classification.lower()
.replace(" ", "_"),
pon_ml_probability_of_pathogenicity=hl.float(
pon_predictions[input_mt.variant_collapsed].ML_probability_of_pathogenicity
),
)
# Add MitoTIP predictions
mitotip_predictions = hl.import_table(RESOURCES["mitotip"])
mitotip_predictions = mitotip_predictions.key_by(
variant_id=mitotip_predictions.rCRS
+ hl.str(mitotip_predictions.Position)
+ mitotip_predictions.Alt
)
input_mt = input_mt.annotate_rows(
mitotip_score=hl.float(
mitotip_predictions[input_mt.variant_collapsed].MitoTIP_Score
)
)
# Set pathogenicity based on MitoTIP scores, classifications obtained from MitoTIP's website
input_mt = input_mt.annotate_rows(
mitotip_trna_prediction=(
hl.case()
.when(input_mt.mitotip_score > 16.25, "likely_pathogenic")
.when(
(input_mt.mitotip_score <= 16.25) & (input_mt.mitotip_score > 12.66),
"possibly_pathogenic",
)
.when(
(input_mt.mitotip_score <= 12.66) & (input_mt.mitotip_score >= 8.44),
"possibly_benign",
)
.when((input_mt.mitotip_score < 8.44), "likely_benign")
.or_missing()
)
)
return input_mt
def get_indel_expr(input_mt: hl.MatrixTable) -> hl.expr.BooleanExpression:
"""
Generate expression for filtering to indels that should be used to evaluate indel stacks.
To be considered a variant to be used to evaluate indel stacks, the variant should:
a) be an indel
b) have a heteroplasmy level >= 0.01 and <= 0.95
c) have a PASS genotype
:param input_mt: MatrixTable
:return: Expression to be used for determining if a variant is an indel that should to be used to evaluate indel stacks
"""
indel_expr = (
hl.is_indel(input_mt.alleles[0], input_mt.alleles[1])
& (input_mt.HL <= 0.95)
& (input_mt.HL >= 0.01)
& (input_mt.FT == {"PASS"})
)
return indel_expr
def generate_expressions(
input_mt: hl.MatrixTable, min_hom_threshold: float = 0.95
) -> hl.MatrixTable:
"""
STABLE
Create expressions to use for annotating the MatrixTable.
The expressions include AC, AN, AF, filtering allele frequency (FAF) split by homplasmic/heteroplasmic, haplgroup, and population.
Also includes calcuations of mean DP, MQ, and TLOD.
:param input_mt: MatrixTable
:param min_hom_threshold: Minimum heteroplasmy level to define a variant as homoplasmic
:return: Tuple of hail expressions
"""
# Calculate AC and AN
AC = hl.agg.count_where((input_mt.HL > 0.0))
AN = hl.agg.count_where(hl.is_defined(input_mt.HL))
# Note: if AN is zero, AFs will evaluate to NaN, which may need to be converted to zero for downstream tools
AF = AC / AN
# Calculate AC for het and hom variants, and histogram for HL
AC_hom = hl.agg.count_where(input_mt.HL >= min_hom_threshold)
AC_het = hl.agg.count_where((input_mt.HL < min_hom_threshold) & (input_mt.HL > 0.0))
HL_hist = hl.agg.filter(input_mt.HL > 0, hl.agg.hist(input_mt.HL, 0, 1, 10))
DP_hist_alt = hl.agg.filter(
input_mt.GT.is_non_ref(), hl.agg.hist(input_mt.DP, 0, 2000, 10)
)
DP_hist_all = hl.agg.hist(input_mt.DP, 0, 2000, 10)
DP_mean = hl.agg.mean(input_mt.DP)
MQ_mean = hl.agg.mean(input_mt.MQ)
TLOD_mean = hl.agg.mean(input_mt.TLOD)
# Calculate AF
# Note: if AN is zero, AFs will evaluate to NaN, which may need to be converted to zero for downstream tools
AF_hom = AC_hom / AN
AF_het = AC_het / AN
# Calculate max individual heteroplasmy
max_HL = hl.agg.max(input_mt.HL)
# Haplogroup annotations
pre_hap_AC = hl.agg.group_by(input_mt.hap, AC)
pre_hap_AN = hl.agg.group_by(input_mt.hap, AN)
pre_hap_AF = hl.agg.group_by(input_mt.hap, AF)
pre_hap_AC_het = hl.agg.group_by(input_mt.hap, AC_het)
pre_hap_AC_hom = hl.agg.group_by(input_mt.hap, AC_hom)
pre_hap_AF_hom = hl.agg.group_by(input_mt.hap, AF_hom)
pre_hap_AF_het = hl.agg.group_by(input_mt.hap, AF_het)
pre_hap_HL_hist = hl.agg.group_by(input_mt.hap, HL_hist.bin_freq)
pre_hap_FAF = hl.agg.group_by(
input_mt.hap,
hl.experimental.filtering_allele_frequency(hl.int32(AC), hl.int32(AN), 0.95),
)
pre_hap_FAF_hom = hl.agg.group_by(
input_mt.hap,
hl.experimental.filtering_allele_frequency(
hl.int32(AC_hom), hl.int32(AN), 0.95
),
)
# population annotations
pre_pop_AC = hl.agg.group_by(input_mt.pop, AC)
pre_pop_AN = hl.agg.group_by(input_mt.pop, AN)
pre_pop_AF = hl.agg.group_by(input_mt.pop, AF)
pre_pop_AC_het = hl.agg.group_by(input_mt.pop, AC_het)
pre_pop_AC_hom = hl.agg.group_by(input_mt.pop, AC_hom)
pre_pop_AF_hom = hl.agg.group_by(input_mt.pop, AF_hom)
pre_pop_AF_het = hl.agg.group_by(input_mt.pop, AF_het)
pre_pop_HL_hist = hl.agg.group_by(input_mt.pop, HL_hist.bin_freq)
return hl.struct(
AC=AC,
AN=AN,
AF=AF,
AC_hom=AC_hom,
AC_het=AC_het,
hl_hist=HL_hist,
dp_hist_all=DP_hist_all,
dp_hist_alt=DP_hist_alt,
dp_mean=DP_mean,
mq_mean=MQ_mean,
tlod_mean=TLOD_mean,
AF_hom=AF_hom,
AF_het=AF_het,
max_hl=max_HL,
pre_hap_AC=pre_hap_AC,
pre_hap_AN=pre_hap_AN,
pre_hap_AF=pre_hap_AF,
pre_hap_AC_het=pre_hap_AC_het,
pre_hap_AF_het=pre_hap_AF_het,
pre_hap_AC_hom=pre_hap_AC_hom,
pre_hap_AF_hom=pre_hap_AF_hom,
pre_hap_hl_hist=pre_hap_HL_hist,
pre_hap_faf=pre_hap_FAF,
pre_hap_faf_hom=pre_hap_FAF_hom,
pre_pop_AN=pre_pop_AN,
pre_pop_AC_het=pre_pop_AC_het,
pre_pop_AF_het=pre_pop_AF_het,
pre_pop_AC_hom=pre_pop_AC_hom,
pre_pop_AF_hom=pre_pop_AF_hom,
pre_pop_hl_hist=pre_pop_HL_hist,
)
def standardize_haps(
input_mt: hl.MatrixTable, annotation: str, haplogroup_order: list
) -> list:
"""
STABLE
Convert the dictionary of haplogroup annotations into an array of values in a predefined haplogroup order.
:param input_mt: MatrixTable
:param annotation: Annotation to convert and sort
:param haplogroup_order: Order in which to sort the haplogroups
:return: Sorted list of haplogroup annotations (the values of the dictionary)
"""
# Converts haplogroup dictionary to sorted array
value = [input_mt[annotation][x] for x in haplogroup_order]
return value
def standardize_pops(
input_mt: hl.MatrixTable, annotation: str, population_order: list
) -> list:
"""
STABLE
Convert the dictionary of population annotations into an array of values in a predefined population order.
:param input_mt: MatrixTable
:param annotation: Annotation to convert and sort
:param population_order: Order in which to sort the populations
:return: Sorted list of population annotations (the values of the dictionary)
"""
# Converts haplogroup dictionary to sorted array
value = [input_mt[annotation][x] for x in population_order]
return value
def add_quality_histograms(input_mt: hl.MatrixTable) -> hl.MatrixTable:
"""
STABLE
Add histogram annotations for quality metrics to the MatrixTable.
:param input_mt: MatrixTable
:return: MatrixTable annotated with quality metric histograms
"""
# Generate histogram for site quality metrics across all variants
# TODO: decide on bin edges
dp_hist_all_variants = input_mt.aggregate_rows(
hl.agg.hist(input_mt.dp_mean, 0, 4000, 40)
)
input_mt = input_mt.annotate_globals(
dp_hist_all_variants_bin_freq=dp_hist_all_variants.bin_freq,
dp_hist_all_variants_n_larger=dp_hist_all_variants.n_larger,
dp_hist_all_variants_bin_edges=dp_hist_all_variants.bin_edges,
)
mq_hist_all_variants = input_mt.aggregate_rows(
hl.agg.hist(input_mt.mq_mean, 0, 80, 40)
) # is 80 the actual max value here?
input_mt = input_mt.annotate_globals(
mq_hist_all_variants_bin_freq=mq_hist_all_variants.bin_freq,
mq_hist_all_variants_n_larger=mq_hist_all_variants.n_larger,
mq_hist_all_variants_bin_edges=mq_hist_all_variants.bin_edges,
)
tlod_hist_all_variants = input_mt.aggregate_rows(
hl.agg.hist(input_mt.tlod_mean, 0, 40000, 40)
)
input_mt = input_mt.annotate_globals(
tlod_hist_all_variants_bin_freq=tlod_hist_all_variants.bin_freq,
tlod_hist_all_variants_n_larger=tlod_hist_all_variants.n_larger,
tlod_hist_all_variants_bin_edges=tlod_hist_all_variants.bin_edges,
)
# Generate histogram for overall age distribution
age_hist_all_samples = input_mt.aggregate_cols(
hl.agg.hist(input_mt.age, 30, 80, 10)
)
input_mt = input_mt.annotate_globals(
age_hist_all_samples_bin_freq=age_hist_all_samples.bin_freq,
age_hist_all_samples_n_larger=age_hist_all_samples.n_larger,
age_hist_all_samples_n_smaller=age_hist_all_samples.n_smaller,
age_hist_all_samples_bin_edges=age_hist_all_samples.bin_edges,
)
# Add age histograms per variant type (heteroplasmic or homoplasmic)
age_data = age_hists_expr(True, input_mt.GT, input_mt.age)
input_mt = input_mt.annotate_rows(
age_hist_hom=age_data.age_hist_hom, age_hist_het=age_data.age_hist_het
)
return input_mt
def add_annotations_by_hap_and_pop(input_mt: hl.MatrixTable, temp_dir) -> hl.MatrixTable:
"""
Add variant annotations (such as AC, AN, AF, heteroplasmy histogram, and filtering allele frequency) split by haplogroup and population.
:param input_mt: MatrixTable
:return: MatrixTable with variant annotations
"""
# Order the haplogroup-specific annotations
list_hap_order = list(set(input_mt.hap.collect()))
input_mt = input_mt.annotate_globals(hap_order=sorted(list_hap_order))
# Sanity check for haplogroups (make sure that they at least start with a letter)
for i in list_hap_order:
if not re.match("^[A-Z]", i):
sys.exit(f"Invalid haplogroup {i}, does not start with a letter")
pre_hap_annotation_labels_1 = [
"pre_hap_AC",
"pre_hap_AN",
"pre_hap_AF",
"pre_hap_AC_het",
"pre_hap_AC_hom",
]
for_annot = {re.sub("pre_", "", i): standardize_haps(input_mt, i, sorted(list_hap_order)) for i in pre_hap_annotation_labels_1}
input_mt = input_mt.annotate_rows(**for_annot)
input_mt = input_mt.checkpoint(f"{temp_dir}/temp3.mt", overwrite=True)
pre_hap_annotation_labels_2 = [
"pre_hap_AF_hom",
"pre_hap_AF_het",
"pre_hap_hl_hist",
"pre_hap_faf",
"pre_hap_faf_hom",
]
for_annot = {re.sub("pre_", "", i): standardize_haps(input_mt, i, sorted(list_hap_order)) for i in pre_hap_annotation_labels_2}
input_mt = input_mt.annotate_rows(**for_annot)
input_mt = input_mt.checkpoint(f"{temp_dir}/temp4.mt", overwrite=True)
# Get a list of indexes where AC of the haplogroup is greater than 0, then get the list of haplogroups with that index
input_mt = input_mt.annotate_rows(
alt_haps=hl.enumerate(input_mt.hap_AC)
.filter(lambda x: x[1] > 0)
.map(lambda x: input_mt.hap_order[x[0]])
)
# Count number of haplogroups containing an alt allele
input_mt = input_mt.annotate_rows(n_alt_haps=hl.len(input_mt.alt_haps))
# Calculate hapmax
input_mt = input_mt.annotate_rows(
hapmax_AF_hom=input_mt.hap_order[(hl.argmax(input_mt.hap_AF_hom, unique=True))],
hapmax_AF_het=input_mt.hap_order[(hl.argmax(input_mt.hap_AF_het, unique=True))],
)
# Calculate faf hapmax
input_mt = input_mt.annotate_rows(
faf_hapmax=hl.max(input_mt.hap_faf), faf_hapmax_hom=hl.max(input_mt.hap_faf_hom)
)
# Add populatation annotations
final_pops = set(input_mt.pop.collect())
# Order according to POPS
#final_pops = [x for x in POPS if x in found_pops]
#if len(found_pops - set(POPS)) > 0:
# sys.exit("Invalid population found")
input_mt = input_mt.annotate_globals(pop_order=final_pops)
pre_pop_annotation_labels = [
"pre_pop_AN",
"pre_pop_AC_het",
"pre_pop_AC_hom",
"pre_pop_AF_hom",
"pre_pop_AF_het",
"pre_pop_hl_hist",
]
for i in pre_pop_annotation_labels:
# Remove "pre" prefix for final annotations
final_annotation = re.sub("pre_", "", i)
input_mt = input_mt.annotate_rows(
**{final_annotation: standardize_pops(input_mt, i, final_pops)}
)
# Drop intermediate annotations
annotations_to_drop = [
"pre_hap_AC",
"pre_hap_AN",
"pre_hap_AF",
"pre_hap_AC_het",
"pre_hap_AC_hom",
"pre_hap_AF_hom",
"pre_hap_AF_het",
"pre_hap_hl_hist",
"pre_hap_faf",
"pre_hap_faf_hom",
"AC_mid_het",
"AF_mid_het",
"pre_pop_AN",
"pre_pop_AC_het",
"pre_pop_AC_hom",
"pre_pop_AF_hom",
"pre_pop_AF_het",
"pre_pop_hl_hist",
]
input_mt = input_mt.drop(*annotations_to_drop)
# Last-minute drops (ever add back in?)
input_mt = input_mt.drop(
"AC",
"AF",
"hap_AC",
"hap_AF",
"hap_faf",
"faf_hapmax",
"alt_haps",
"n_alt_haps",
)
input_mt = input_mt.annotate_rows(filters=input_mt.filters.difference({"PASS"}))
return input_mt
def apply_common_low_het_flag(input_mt: hl.MatrixTable) -> hl.MatrixTable:
"""
Apply the common_low_heteroplasmy flag to the MatrixTable.
The common_low_heteroplasmy flag marks variants where the overall frequency is > 0.001 for samples with a heteroplasmy level > 0 and < 0.50 and either "low_allele_frac" or "PASS" for the genotype filter
NOTE: The "low_allele_frac" is applied by Mutect2 to variants with a heteroplasmy level below the supplied vaf_filter_threshold
:param input_mt: MatrixTable
:return: MatrixTable with the common_low_heteroplasmy flag added
"""
input_mt = format_filters(input_mt)
input_mt = input_mt.annotate_rows(
AC_mid_het=hl.agg.count_where(
(input_mt.HL < 0.50)
& (input_mt.HL > 0.0)
& ((input_mt.FT == {"PASS"}) | (input_mt.FT == {"low_allele_frac"}))
)
)
input_mt = input_mt.annotate_rows(
AF_mid_het=input_mt.AC_mid_het
/ hl.agg.count_where(
hl.is_defined(input_mt.HL)
& ((input_mt.FT == {"PASS"}) | (input_mt.FT == {"low_allele_frac"}))
)
)
input_mt = input_mt.annotate_rows(
common_low_heteroplasmy=input_mt.AF_mid_het > 0.001
)
return format_filters(input_mt)
def remove_low_allele_frac_genotypes(
input_mt: hl.MatrixTable, vaf_filter_threshold: float = 0.01
) -> hl.MatrixTable:
"""
STABLE
Remove low_allele_frac genotypes and sets the call to homoplasmic reference.
NOTE: vaf_filter_threshold should match what was supplied to the vaf_filter_threshold when running Mutect2, variants below this value will be set to homoplasmic reference after calculating the common_low_heteroplasmy filter, Mutect2 will have flagged these variants as "low_allele_frac"