-
Notifications
You must be signed in to change notification settings - Fork 32
Expand file tree
/
Copy pathsparse_mt.py
More file actions
1489 lines (1300 loc) · 60.4 KB
/
sparse_mt.py
File metadata and controls
1489 lines (1300 loc) · 60.4 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
# noqa: D100
import logging
from typing import Callable, Dict, List, Optional, Set, Tuple, Union
import hail as hl
from gnomad.sample_qc.sex import adjusted_sex_ploidy_expr
from gnomad.utils.annotations import (
agg_by_strata,
annotate_adj,
fs_from_sb,
generate_freq_group_membership_array,
get_adj_expr,
get_lowqual_expr,
pab_max_expr,
sor_from_sb,
)
from gnomad.utils.intervals import interval_length, union_intervals
from gnomad.utils.reference_genome import get_reference_genome
logging.basicConfig(
format="%(asctime)s (%(name)s %(lineno)s): %(message)s",
datefmt="%m/%d/%Y %I:%M:%S %p",
)
logger = logging.getLogger(__name__)
logger.setLevel(logging.INFO)
INFO_AGG_FIELDS = {
"sum_agg_fields": ["QUALapprox"],
"int32_sum_agg_fields": ["VarDP"],
"median_agg_fields": ["ReadPosRankSum", "MQRankSum"],
"array_sum_agg_fields": ["SB", "RAW_MQandDP"],
}
AS_INFO_AGG_FIELDS = {
"sum_agg_fields": ["AS_QUALapprox", "AS_RAW_MQ"],
"int32_sum_agg_fields": ["AS_VarDP"],
"median_agg_fields": ["AS_RAW_ReadPosRankSum", "AS_RAW_MQRankSum"],
"array_sum_agg_fields": ["AS_SB_TABLE"],
}
def compute_last_ref_block_end(mt: hl.MatrixTable) -> hl.Table:
"""
Compute the genomic position of the most upstream reference block overlapping each row on a sparse MT.
Note that since reference blocks do not extend beyond contig boundaries, only the position is kept.
This function returns a Table with that annotation. (`last_END_position`).
:param mt: Input MatrixTable
:return: Output Table with `last_END_position` annotation
"""
mt = mt.select_entries("END")
# Localize entries, so that they can be viewed as an array and scanned
# over using hl.scan.array_agg
ht = mt._localize_entries("__entries", "__cols")
# Compute the position by using hl.scan._prev_nonnull.
# This was inspired by hl.experimental.densify
# _prev_non_null is an aggregator that keeps the previous record in memory
# and updates it with the given value at the row if it's not null (missing)
# The following code computes the following annotation for each row:
# 1. Keep a scan of the entries using _prev_nonnull, keeping the start (ht.locus) and end (entry.END) of each ref block (1.1)
# 2. For the current row locus, record the start of the block that starts the furthest away,
# that is the minimum position in the current scan for any block that
# overlaps the current locus (2.1)
ht = ht.select(
last_END_position=hl.or_else(
hl.min( # 2. For the current row locus, record the start of the block that starts the furthest away
hl.scan.array_agg(
lambda entry: hl.scan._prev_nonnull( # 1. Keep a scan of the entries using _prev_nonnull
hl.or_missing(
hl.is_defined(
entry.END
), # Update the scan whenever a new ref block is encountered
hl.tuple(
[ # 1.1 keep the start (ht.locus) and end (entry.END) of each ref block
ht.locus,
entry.END,
]
),
)
),
ht.__entries,
).map(
lambda x: hl.or_missing( # 2.1 get the start position of blocks that overlap the current locus
(x[1] >= ht.locus.position) & (x[0].contig == ht.locus.contig),
x[0].position,
)
)
),
ht.locus.position,
)
)
return ht.select_globals().key_by("locus")
def densify_sites(
mt: hl.MatrixTable,
sites_ht: hl.Table,
last_END_positions_ht: hl.Table,
semi_join_rows: bool = True,
) -> hl.MatrixTable:
"""
Create a dense version of the input sparse MT at the sites in `sites_ht` reading the minimal amount of data required.
Note that only rows that appear both in `mt` and `sites_ht` are returned.
:param mt: Input sparse MT
:param sites_ht: Desired sites to densify
:param last_END_positions_ht: Table storing positions of the furthest ref block (END tag)
:param semi_join_rows: Whether to filter the MT rows based on semi-join (default, better if sites_ht is large) or based on filter_intervals (better if sites_ht only contains a few sites)
:return: Dense MT filtered to the sites in `sites_ht`
"""
logger.info("Computing intervals to densify from sites Table.")
sites_ht = sites_ht.key_by("locus")
sites_ht = sites_ht.annotate(
interval=hl.locus_interval(
sites_ht.locus.contig,
last_END_positions_ht[sites_ht.key].last_END_position,
end=sites_ht.locus.position,
includes_end=True,
reference_genome=sites_ht.locus.dtype.reference_genome,
)
)
sites_ht = sites_ht.filter(hl.is_defined(sites_ht.interval))
if semi_join_rows:
mt = mt.filter_rows(hl.is_defined(sites_ht.key_by("interval")[mt.locus]))
else:
logger.info("Collecting intervals to densify.")
intervals = sites_ht.interval.collect()
print(
"Found {0} intervals, totalling {1} bp in the dense Matrix.".format(
len(intervals),
sum(
[
interval_length(interval)
for interval in union_intervals(intervals)
]
),
)
)
mt = hl.filter_intervals(mt, intervals)
mt = hl.experimental.densify(mt)
return mt.filter_rows(hl.is_defined(sites_ht[mt.locus]))
def _get_info_agg_expr(
mt: hl.MatrixTable,
sum_agg_fields: Union[
List[str], Dict[str, hl.expr.NumericExpression]
] = INFO_AGG_FIELDS["sum_agg_fields"],
int32_sum_agg_fields: Union[
List[str], Dict[str, hl.expr.NumericExpression]
] = INFO_AGG_FIELDS["int32_sum_agg_fields"],
median_agg_fields: Union[
List[str], Dict[str, hl.expr.NumericExpression]
] = INFO_AGG_FIELDS["median_agg_fields"],
array_sum_agg_fields: Union[
List[str], Dict[str, hl.expr.ArrayNumericExpression]
] = INFO_AGG_FIELDS["array_sum_agg_fields"],
prefix: str = "",
treat_fields_as_allele_specific: bool = False,
retain_cdfs: bool = False,
cdf_k: int = 200,
) -> Dict[str, hl.expr.Aggregation]:
"""
Create Aggregators for both site or AS info expression aggregations.
.. note::
- If `SB` is specified in array_sum_agg_fields, it will be aggregated as
`AS_SB_TABLE`, according to GATK standard nomenclature.
- If `RAW_MQandDP` is specified in array_sum_agg_fields, it will be used for
the `MQ` calculation and then dropped according to GATK recommendation.
- If `RAW_MQ` and `MQ_DP` are given, they will be used for the `MQ` calculation
and then dropped according to GATK recommendation.
- If the fields to be aggregated (`sum_agg_fields`, `int32_sum_agg_fields`,
`median_agg_fields`) are passed as list of str, then they should correspond
to entry fields in `mt` or in mt.gvcf_info`.
- Priority is given to entry fields in `mt` over those in `mt.gvcf_info` in
case of a name clash.
:param mt: Input MT
:param sum_agg_fields: Fields to aggregate using sum.
:param int32_sum_agg_fields: Fields to aggregate using sum using int32.
:param median_agg_fields: Fields to aggregate using (approximate) median.
:param array_sum_agg_fields: Fields to aggregate using element-wise summing over an
array.
:param prefix: Optional prefix for the fields. Used for adding 'AS_' in the AS case.
:param treat_fields_as_allele_specific: Treat info fields as allele-specific.
Defaults to False.
:param retain_cdfs: If True, retains the cumulative distribution functions (CDFs)
as an annotation for `median_agg_fields`. Keeping the CDFs is useful for
annotations that require calculating the median across combined datasets at a
later stage. Default is False.
:param cdf_k: Parameter controlling the accuracy vs. memory usage tradeoff when
retaining CDFs. A higher value of `cdf_k` results in a more accurate CDF
approximation but increases memory usage and computation time. Default is 200.
:return: Dictionary of expression names and their corresponding aggregation
Expression.
"""
def _agg_list_to_dict(
mt: hl.MatrixTable, fields: List[str]
) -> Dict[str, hl.expr.NumericExpression]:
out_fields = {}
if "gvcf_info" in mt.entry:
out_fields = {f: mt.gvcf_info[f] for f in fields if f in mt.gvcf_info}
out_fields.update({f: mt[f] for f in fields if f in mt.entry})
# Check that all fields were found.
missing_fields = [f for f in fields if f not in out_fields]
if missing_fields:
raise ValueError(
"Could not find the following field(s)in the MT entry schema (or nested"
" under mt.gvcf_info: {}".format(",".join(missing_fields))
)
if treat_fields_as_allele_specific:
# TODO: Change to use hl.vds.local_to_global when fill_value can accept
# missing (error in v0.2.119).
out_fields = {
f: hl.bind(
lambda x: hl.if_else(f == "AS_SB_TABLE", x, x[1:]),
hl.range(hl.len(mt.alleles)).map(
lambda i: hl.or_missing(
mt.LA.contains(i), out_fields[f][mt.LA.index(i)]
)
),
)
for f in fields
}
return out_fields
# Map str to expressions where needed.
if isinstance(sum_agg_fields, list):
sum_agg_fields = _agg_list_to_dict(mt, sum_agg_fields)
if isinstance(int32_sum_agg_fields, list):
int32_sum_agg_fields = _agg_list_to_dict(mt, int32_sum_agg_fields)
if isinstance(median_agg_fields, list):
median_agg_fields = _agg_list_to_dict(mt, median_agg_fields)
if isinstance(array_sum_agg_fields, list):
array_sum_agg_fields = _agg_list_to_dict(mt, array_sum_agg_fields)
aggs = [
(median_agg_fields, lambda x: hl.agg.approx_quantiles(x, 0.5)),
(sum_agg_fields, hl.agg.sum),
(int32_sum_agg_fields, lambda x: hl.int32(hl.agg.sum(x))),
(array_sum_agg_fields, hl.agg.array_sum),
]
if retain_cdfs:
# Note: hl.agg.approx_cdf is a non-deterministic method and cannot be seeded.
# Results may vary with each rerun.
cdf_median_agg_fields = {}
# Store values for each median agg fields in a new dictionary with "_cdf"
# appended to the annotation name.
for k, v in median_agg_fields.items():
cdf_median_agg_fields[f"{k}_cdf"] = v
# Append the cdf annotations to the aggs list. Set '_raw' to True to return
# a representation of the internal state of the CDF, which allows for mergining
# with other CDFs downstream.
aggs.append(
(cdf_median_agg_fields, lambda x: hl.agg.approx_cdf(x, k=cdf_k, _raw=True))
)
# Create aggregators.
agg_expr = {}
for agg_fields, agg_func in aggs:
for k, expr in agg_fields.items():
if treat_fields_as_allele_specific:
# If annotation is of the form 'AS_RAW_*_RankSum' it has a histogram
# representation where keys give the per-variant rank sum value to one
# decimal place followed by a comma and the corresponding count for
# that value, so we want to sum the rank sum value (first element).
# Rename annotation in the form 'AS_RAW_*_RankSum' to 'AS_*_RankSum'.
if k.startswith("AS_RAW_") and (
k.endswith("RankSum") or k.endswith("RankSum_cdf")
):
agg_expr[f"{prefix}{k.replace('_RAW', '')}"] = hl.agg.array_agg(
lambda x: agg_func(hl.or_missing(hl.is_defined(x), x[0])), expr
)
else:
agg_expr[f"{prefix}{k}"] = hl.agg.array_agg(
lambda x: agg_func(x), expr
)
else:
agg_expr[f"{prefix}{k}"] = agg_func(expr)
if treat_fields_as_allele_specific:
prefix = "AS_"
# Handle annotations combinations and casting for specific annotations
# If RAW_MQandDP is in agg_expr or if both MQ_DP and RAW_MQ are, compute MQ instead
mq_tuple = None
if f"{prefix}RAW_MQandDP" in agg_expr:
logger.info(
"Computing %sMQ as sqrt(%sRAW_MQandDP[0]/%sRAW_MQandDP[1]). "
"Note that %sMQ will be set to 0 if %sRAW_MQandDP[1] == 0.",
*[prefix] * 5,
)
mq_tuple = agg_expr.pop(f"{prefix}RAW_MQandDP")
elif "AS_RAW_MQ" in agg_expr and treat_fields_as_allele_specific:
logger.info(
"Computing AS_MQ as sqrt(AS_RAW_MQ[i]/AD[i+1]). "
"Note that AS_MQ will be set to 0 if AS_RAW_MQ == 0."
)
ad_expr = hl.vds.local_to_global(
mt.LAD, mt.LA, hl.len(mt.alleles), fill_value=0, number="R"
)
mq_tuple = hl.zip(agg_expr.pop("AS_RAW_MQ"), hl.agg.array_sum(ad_expr[1:]))
elif f"{prefix}RAW_MQ" in agg_expr and f"{prefix}MQ_DP" in agg_expr:
logger.info(
"Computing %sMQ as sqrt(%sRAW_MQ/%sMQ_DP). "
"Note that MQ will be set to 0 if %sRAW_MQ == 0.",
*[prefix] * 4,
)
mq_tuple = (agg_expr.pop(f"{prefix}RAW_MQ"), agg_expr.pop(f"{prefix}MQ_DP"))
if mq_tuple is not None:
if treat_fields_as_allele_specific:
agg_expr[f"{prefix}MQ"] = mq_tuple.map(
lambda x: hl.if_else(x[1] > 0, hl.sqrt(x[0] / x[1]), 0)
)
else:
agg_expr[f"{prefix}MQ"] = hl.if_else(
mq_tuple[1] > 0, hl.sqrt(mq_tuple[0] / mq_tuple[1]), 0
)
# If both VarDP and QUALapprox are present, also compute QD.
if f"{prefix}VarDP" in agg_expr and f"{prefix}QUALapprox" in agg_expr:
logger.info(
"Computing %sQD as %sQUALapprox/%sVarDP. "
"Note that %sQD will be set to 0 if %sVarDP == 0.",
*[prefix] * 5,
)
var_dp = agg_expr[f"{prefix}VarDP"]
qual_approx = agg_expr[f"{prefix}QUALapprox"]
if treat_fields_as_allele_specific:
agg_expr[f"{prefix}QD"] = hl.map(
lambda x: hl.if_else(x[1] > 0, x[0] / x[1], 0),
hl.zip(qual_approx, var_dp),
)
else:
agg_expr[f"{prefix}QD"] = hl.if_else(var_dp > 0, qual_approx / var_dp, 0)
# SB needs to be cast to int32 for FS down the line.
if f"{prefix}SB" in agg_expr:
agg_expr[f"{prefix}SB"] = agg_expr[f"{prefix}SB"].map(lambda x: hl.int32(x))
# SB needs to be cast to int32 for FS down the line.
if "AS_SB_TABLE" in agg_expr:
agg_expr["AS_SB_TABLE"] = agg_expr["AS_SB_TABLE"].map(
lambda x: x.map(lambda y: hl.int32(y))
)
return agg_expr
def get_as_info_expr(
mt: hl.MatrixTable,
sum_agg_fields: Union[
List[str], Dict[str, hl.expr.NumericExpression]
] = INFO_AGG_FIELDS["sum_agg_fields"],
int32_sum_agg_fields: Union[
List[str], Dict[str, hl.expr.NumericExpression]
] = INFO_AGG_FIELDS["int32_sum_agg_fields"],
median_agg_fields: Union[
List[str], Dict[str, hl.expr.NumericExpression]
] = INFO_AGG_FIELDS["median_agg_fields"],
array_sum_agg_fields: Union[
List[str], Dict[str, hl.expr.ArrayNumericExpression]
] = INFO_AGG_FIELDS["array_sum_agg_fields"],
alt_alleles_range_array_field: str = "alt_alleles_range_array",
treat_fields_as_allele_specific: bool = False,
retain_cdfs: bool = False,
cdf_k: int = 200,
) -> hl.expr.StructExpression:
"""
Return an allele-specific annotation Struct containing typical VCF INFO fields from GVCF INFO fields stored in the MT entries.
.. note::
- If `SB` is specified in array_sum_agg_fields, it will be aggregated as
`AS_SB_TABLE`, according to GATK standard nomenclature.
- If `RAW_MQandDP` is specified in array_sum_agg_fields, it will be used for
the `MQ` calculation and then dropped according to GATK recommendation.
- If `RAW_MQ` and `MQ_DP` are given, they will be used for the `MQ` calculation
and then dropped according to GATK recommendation.
- If the fields to be aggregate (`sum_agg_fields`, `int32_sum_agg_fields`,
`median_agg_fields`) are passed as list of str, then they should correspond
to entry fields in `mt` or in `mt.gvcf_info`.
- Priority is given to entry fields in `mt` over those in `mt.gvcf_info` in
case of a name clash.
- If `treat_fields_as_allele_specific` is False, it's expected that there is a
single value for each entry field to be aggregated. Then when performing the
aggregation per global alternate allele, that value is included in the
aggregation if the global allele is present in the entry's list of local
alleles. If `treat_fields_as_allele_specific` is True, it's expected that
each entry field to be aggregated has one value per local allele, and each
of those is mapped to a global allele for aggregation.
:param mt: Input Matrix Table
:param sum_agg_fields: Fields to aggregate using sum.
:param int32_sum_agg_fields: Fields to aggregate using sum using int32.
:param median_agg_fields: Fields to aggregate using (approximate) median.
:param array_sum_agg_fields: Fields to aggregate using array sum.
:param alt_alleles_range_array_field: Annotation containing an array of the range
of alternate alleles e.g., `hl.range(1, hl.len(mt.alleles))`
:param treat_fields_as_allele_specific: Treat info fields as allele-specific.
Defaults to False.
:param retain_cdfs: If True, retains the cumulative distribution functions (CDFs)
as an annotation for `median_agg_fields`. Keeping the CDFs is useful for
annotations that require calculating the median across combined datasets at a
later stage. Default is False.
:param cdf_k: Parameter controlling the accuracy vs. memory usage tradeoff when
retaining CDFs. A higher value of `cdf_k` results in a more accurate CDF
approximation but increases memory usage and computation time. Default is 200.
:return: Expression containing the AS info fields
"""
if "DP" in list(sum_agg_fields) + list(int32_sum_agg_fields):
logger.warning(
"`DP` was included in allele-specific aggregation, however `DP` is"
" typically not aggregated by allele; `VarDP` is.Note that the resulting"
" `AS_DP` field will NOT include reference genotypes."
)
agg_expr = _get_info_agg_expr(
mt=mt,
sum_agg_fields=sum_agg_fields,
int32_sum_agg_fields=int32_sum_agg_fields,
median_agg_fields=median_agg_fields,
array_sum_agg_fields=array_sum_agg_fields,
prefix="" if treat_fields_as_allele_specific else "AS_",
treat_fields_as_allele_specific=treat_fields_as_allele_specific,
retain_cdfs=retain_cdfs,
cdf_k=cdf_k,
)
if alt_alleles_range_array_field not in mt.row or mt[
alt_alleles_range_array_field
].dtype != hl.dtype("array<int32>"):
msg = (
f"'get_as_info_expr' expected a row field '{alt_alleles_range_array_field}'"
" of type array<int32>"
)
logger.error(msg)
raise ValueError(msg)
if not treat_fields_as_allele_specific:
# Modify aggregations to aggregate per allele
agg_expr = {
f: hl.agg.array_agg(
lambda ai: hl.agg.filter(mt.LA.contains(ai), expr),
mt[alt_alleles_range_array_field],
)
for f, expr in agg_expr.items()
}
# Run aggregations
info = hl.struct(**agg_expr)
# Add FS and SOR if SB is present.
if "AS_SB_TABLE" in info or "AS_SB" in info:
drop = []
# Rename AS_SB to AS_SB_TABLE if present and add SB Ax2 aggregation logic.
if "AS_SB" in agg_expr:
if "AS_SB_TABLE" in agg_expr:
logger.warning(
"Both `AS_SB` and `AS_SB_TABLE` were specified for aggregation."
" `AS_SB` will be used for aggregation."
)
as_sb_table = hl.array(
[
info.AS_SB.filter(lambda x: hl.is_defined(x)).fold(
lambda i, j: i[:2] + j[:2], [0, 0]
) # ref
]
).extend(
info.AS_SB.map(lambda x: x[2:]) # each alt
)
drop = ["AS_SB"]
else:
as_sb_table = info.AS_SB_TABLE
info = info.annotate(
AS_SB_TABLE=as_sb_table,
AS_FS=hl.range(1, hl.len(mt.alleles)).map(
lambda i: fs_from_sb(as_sb_table[0].extend(as_sb_table[i]))
),
AS_SOR=hl.range(1, hl.len(mt.alleles)).map(
lambda i: sor_from_sb(as_sb_table[0].extend(as_sb_table[i]))
),
).drop(*drop)
return info
def get_site_info_expr(
mt: hl.MatrixTable,
sum_agg_fields: Union[
List[str], Dict[str, hl.expr.NumericExpression]
] = INFO_AGG_FIELDS["sum_agg_fields"],
int32_sum_agg_fields: Union[
List[str], Dict[str, hl.expr.NumericExpression]
] = INFO_AGG_FIELDS["int32_sum_agg_fields"],
median_agg_fields: Union[
List[str], Dict[str, hl.expr.NumericExpression]
] = INFO_AGG_FIELDS["median_agg_fields"],
array_sum_agg_fields: Union[
List[str], Dict[str, hl.expr.ArrayNumericExpression]
] = INFO_AGG_FIELDS["array_sum_agg_fields"],
retain_cdfs: bool = False,
cdf_k: int = 200,
) -> hl.expr.StructExpression:
"""
Create a site-level annotation Struct aggregating typical VCF INFO fields from GVCF INFO fields stored in the MT entries.
.. note::
- If `RAW_MQandDP` is specified in array_sum_agg_fields, it will be used for
the `MQ` calculation and then dropped according to GATK recommendation.
- If `RAW_MQ` and `MQ_DP` are given, they will be used for the `MQ` calculation
and then dropped according to GATK recommendation.
- If the fields to be aggregate (`sum_agg_fields`, `int32_sum_agg_fields`,
`median_agg_fields`) are passed as list of str, then they should correspond
to entry fields in `mt` or in `mt.gvcf_info`.
- Priority is given to entry fields in `mt` over those in `mt.gvcf_info` in
case of a name clash.
:param mt: Input Matrix Table
:param sum_agg_fields: Fields to aggregate using sum.
:param int32_sum_agg_fields: Fields to aggregate using sum using int32.
:param median_agg_fields: Fields to aggregate using (approximate) median.
:param retain_cdfs: If True, retains the cumulative distribution functions (CDFs)
as an annotation for `median_agg_fields`. Keeping the CDFs is useful for
annotations that require calculating the median across combined datasets at a
later stage. Default is False.
:param cdf_k: Parameter controlling the accuracy vs. memory usage tradeoff when
retaining CDFs. A higher value of `cdf_k` results in a more accurate CDF
approximation but increases memory usage and computation time. Default is 200.
:return: Expression containing the site-level info fields
"""
if "DP" in list(sum_agg_fields) + list(int32_sum_agg_fields):
logger.warning(
"`DP` was included in site-level aggregation. This requires a densifying"
" prior to running get_site_info_expr"
)
agg_expr = _get_info_agg_expr(
mt=mt,
sum_agg_fields=sum_agg_fields,
int32_sum_agg_fields=int32_sum_agg_fields,
median_agg_fields=median_agg_fields,
array_sum_agg_fields=array_sum_agg_fields,
retain_cdfs=retain_cdfs,
cdf_k=cdf_k,
)
# Add FS and SOR if SB is present
# This is done outside _get_info_agg_expr as the behavior is different
# in site vs allele-specific versions
if "SB" in agg_expr:
agg_expr["FS"] = fs_from_sb(agg_expr["SB"])
agg_expr["SOR"] = sor_from_sb(agg_expr["SB"])
# Run aggregator on non-ref genotypes
info = hl.agg.filter(
mt.LGT.is_non_ref(),
hl.struct(**{k: v for k, v in agg_expr.items() if k != "DP"}),
)
# Add DP, computed over both ref and non-ref genotypes, if present
if "DP" in agg_expr:
info = info.annotate(DP=agg_expr["DP"])
return info
def default_compute_info(
mt: hl.MatrixTable,
site_annotations: bool = False,
as_annotations: bool = False,
# Set to True by default to prevent a breaking change.
quasi_as_annotations: bool = True,
n_partitions: Optional[int] = 5000,
lowqual_indel_phred_het_prior: int = 40,
ac_filter_groups: Optional[Dict[str, hl.Expression]] = None,
retain_cdfs: bool = False,
cdf_k: int = 200,
) -> hl.Table:
"""
Compute a HT with the typical GATK allele-specific (AS) info fields as well as ACs and lowqual fields.
.. note::
- This table doesn't split multi-allelic sites.
- At least one of `site_annotations`, `as_annotations` or `quasi_as_annotations`
must be True.
:param mt: Input MatrixTable. Note that this table should be filtered to nonref sites.
:param site_annotations: Whether to generate site level info fields. Default is False.
:param as_annotations: Whether to generate allele-specific info fields using
allele-specific annotations in gvcf_info. Default is False.
:param quasi_as_annotations: Whether to generate allele-specific info fields using
non-allele-specific annotations in gvcf_info, but performing per allele
aggregations. This method can be used in cases where genotype data doesn't
contain allele-specific annotations to approximate allele-specific annotations.
Default is True.
:param n_partitions: Optional number of desired partitions for output Table. If
specified, naive_coalesce is performed. Default is 5000.
:param lowqual_indel_phred_het_prior: Phred-scaled prior for a het genotype at a
site with a low quality indel. Default is 40. We use 1/10k bases (phred=40) to
be more consistent with the filtering used by Broad's Data Sciences Platform
for VQSR.
:param ac_filter_groups: Optional dictionary of sample filter expressions to compute
additional groupings of ACs. Default is None.
:param retain_cdfs: If True, retains the cumulative distribution functions (CDFs)
as an annotation for `median_agg_fields`. Keeping the CDFs is useful for
annotations that require calculating the median across combined datasets at a
later stage. Default is False.
:param cdf_k: Parameter controlling the accuracy vs. memory usage tradeoff when
retaining CDFs. A higher value of `cdf_k` results in a more accurate CDF
approximation but increases memory usage and computation time. Default is 200.
:return: Table with info fields
:rtype: Table
"""
if not site_annotations and not as_annotations and not quasi_as_annotations:
raise ValueError(
"At least one of `site_annotations`, `as_annotations`, or "
"`quasi_as_annotations` must be True!"
)
# Add a temporary annotation for allele count groupings.
ac_filter_groups = {"": True, **(ac_filter_groups or {})}
mt = mt.annotate_cols(_ac_filter_groups=ac_filter_groups)
# Move gvcf info entries out from nested struct.
mt = mt.transmute_entries(**mt.gvcf_info)
# Adding alt_alleles_range_array as a required annotation for
# get_as_info_expr to reduce memory usage.
mt = mt.annotate_rows(alt_alleles_range_array=hl.range(1, hl.len(mt.alleles)))
info_expr = None
quasi_info_expr = None
# Compute quasi-AS info expr.
if quasi_as_annotations:
info_expr = get_as_info_expr(mt, retain_cdfs=retain_cdfs, cdf_k=cdf_k)
# Compute AS info expr using gvcf_info allele specific annotations.
if as_annotations:
if info_expr is not None:
quasi_info_expr = info_expr
info_expr = get_as_info_expr(
mt,
**AS_INFO_AGG_FIELDS,
treat_fields_as_allele_specific=True,
retain_cdfs=retain_cdfs,
cdf_k=cdf_k,
)
if info_expr is not None:
# Add allele specific pab_max
info_expr = info_expr.annotate(
AS_pab_max=pab_max_expr(mt.LGT, mt.LAD, mt.LA, hl.len(mt.alleles))
)
if site_annotations:
site_expr = get_site_info_expr(mt, retain_cdfs=retain_cdfs, cdf_k=cdf_k)
if info_expr is None:
info_expr = site_expr
else:
info_expr = info_expr.annotate(**site_expr)
# Add 'AC' and 'AC_raw' for each allele count filter group requested.
# First compute ACs for each non-ref allele, grouped by adj.
grp_ac_expr = {
f: hl.agg.array_agg(
lambda ai: hl.agg.filter(
mt.LA.contains(ai) & mt._ac_filter_groups[f],
hl.agg.group_by(
get_adj_expr(mt.LGT, mt.GQ, mt.DP, mt.LAD),
hl.agg.sum(
mt.LGT.one_hot_alleles(mt.LA.map(lambda x: hl.str(x)))[
mt.LA.index(ai)
]
),
),
),
mt.alt_alleles_range_array,
)
for f in ac_filter_groups
}
# Then, for each non-ref allele, compute
# 'AC' as the adj group
# 'AC_raw' as the sum of adj and non-adj groups
info_expr = info_expr.annotate(
**{
f"AC{'_' + f if f else f}_raw": grp.map(
lambda i: hl.int32(i.get(True, 0) + i.get(False, 0))
)
for f, grp in grp_ac_expr.items()
},
**{
f"AC{'_' + f if f else f}": grp.map(lambda i: hl.int32(i.get(True, 0)))
for f, grp in grp_ac_expr.items()
},
)
ann_expr = {"info": info_expr}
if quasi_info_expr is not None:
ann_expr["quasi_info"] = quasi_info_expr
info_ht = mt.select_rows(**ann_expr).rows()
# Add AS lowqual flag
info_ht = info_ht.annotate(
AS_lowqual=get_lowqual_expr(
info_ht.alleles,
info_ht.info.AS_QUALapprox,
indel_phred_het_prior=lowqual_indel_phred_het_prior,
)
)
if site_annotations:
# Add lowqual flag
info_ht = info_ht.annotate(
lowqual=get_lowqual_expr(
info_ht.alleles,
info_ht.info.QUALapprox,
indel_phred_het_prior=lowqual_indel_phred_het_prior,
)
)
if n_partitions is not None:
info_ht = info_ht.naive_coalesce(n_partitions)
return info_ht
def split_info_annotation(
info_expr: hl.expr.StructExpression, a_index: hl.expr.Int32Expression
) -> hl.expr.StructExpression:
"""
Split multi-allelic allele-specific info fields.
:param info_expr: Field containing info struct.
:param a_index: Allele index. Output by hl.split_multi or hl.split_multi_hts.
:return: Info struct with split annotations.
"""
# Index AS annotations
info_expr = info_expr.annotate(
**{
f: info_expr[f][a_index - 1]
for f in info_expr
if f.startswith("AC") or (f.startswith("AS_") and not f == "AS_SB_TABLE")
}
)
if "AS_SB_TABLE" in info_expr:
info_expr = info_expr.annotate(
AS_SB_TABLE=info_expr.AS_SB_TABLE[0].extend(info_expr.AS_SB_TABLE[a_index])
)
return info_expr
def split_lowqual_annotation(
lowqual_expr: hl.expr.ArrayExpression, a_index: hl.expr.Int32Expression
) -> hl.expr.BooleanExpression:
"""
Split multi-allelic low QUAL annotation.
:param lowqual_expr: Field containing low QUAL annotation.
:param a_index: Allele index. Output by hl.split_multi or hl.split_multi_hts.
:return: Low QUAL expression for particular allele.
"""
return lowqual_expr[a_index - 1]
def impute_sex_ploidy(
mt: hl.MatrixTable,
excluded_calling_intervals: Optional[hl.Table] = None,
included_calling_intervals: Optional[hl.Table] = None,
normalization_contig: str = "chr20",
chr_x: Optional[str] = None,
chr_y: Optional[str] = None,
use_only_variants: bool = False,
) -> hl.Table:
"""
Impute sex ploidy from a sparse MatrixTable.
Sex ploidy is imputed by normalizing the coverage of chromosomes X and Y using the coverage of an autosomal
chromosome (by default chr20).
Coverage is computed using the median block coverage (summed over the block size) and the non-ref coverage at
non-ref genotypes unless the `use_only_variants` argument is set to True and then it will use the mean coverage
defined by only the variants.
:param mt: Input sparse Matrix Table
:param excluded_calling_intervals: Optional table of intervals to exclude from the computation. Used only when
determining contig size (not used when computing chromosome depth) when `use_only_variants` is False.
:param included_calling_intervals: Optional table of intervals to use in the computation. Used only when
determining contig size (not used when computing chromosome depth) when `use_only_variants` is False.
:param normalization_contig: Which chromosome to normalize by
:param chr_x: Optional X Chromosome contig name (by default uses the X contig in the reference)
:param chr_y: Optional Y Chromosome contig name (by default uses the Y contig in the reference)
:param use_only_variants: Whether to use depth of variant data within calling intervals instead of reference data.
Default will only use reference data.
:return: Table with mean coverage over chromosomes 20, X and Y and sex chromosomes ploidy based on normalized coverage.
"""
ref = get_reference_genome(mt.locus, add_sequence=True)
if chr_x is None:
if len(ref.x_contigs) != 1:
raise NotImplementedError(
"Found {0} X chromosome contigs ({1}) in Genome reference."
" sparse_impute_sex_ploidy currently only supports a single X"
" chromosome contig. Please use the `chr_x` argument to specify which"
" X chromosome contig to use ".format(
len(ref.x_contigs), ",".join(ref.x_contigs)
)
)
chr_x = ref.x_contigs[0]
if chr_y is None:
if len(ref.y_contigs) != 1:
raise NotImplementedError(
"Found {0} Y chromosome contigs ({1}) in Genome reference."
" sparse_impute_sex_ploidy currently only supports a single Y"
" chromosome contig. Please use the `chr_y` argument to specify which"
" Y chromosome contig to use ".format(
len(ref.y_contigs), ",".join(ref.y_contigs)
)
)
chr_y = ref.y_contigs[0]
def get_contig_size(contig: str) -> int:
"""
Compute the size of the specified `contig` using the median block coverage (summed over the block size).
The size of the contig will be determined using only non par regions if the contig is an X or Y reference contig
and using the intervals specified by `included_calling_intervals` and excluding intervals specified by
`excluded_calling_intervals` if either is defined in the outer function.
:param contig: Contig to compute the size of
:return: Integer of the contig size
"""
logger.info("Working on %s", contig)
contig_ht = hl.utils.range_table(
ref.contig_length(contig),
n_partitions=int(ref.contig_length(contig) / 500_000),
)
contig_ht = contig_ht.annotate(
locus=hl.locus(contig=contig, pos=contig_ht.idx + 1, reference_genome=ref)
)
contig_ht = contig_ht.filter(contig_ht.locus.sequence_context().lower() != "n")
if contig in ref.x_contigs:
contig_ht = contig_ht.filter(contig_ht.locus.in_x_nonpar())
if contig in ref.y_contigs:
contig_ht = contig_ht.filter(contig_ht.locus.in_y_nonpar())
contig_ht = contig_ht.key_by("locus")
if included_calling_intervals is not None:
contig_ht = contig_ht.filter(
hl.is_defined(included_calling_intervals[contig_ht.key])
)
if excluded_calling_intervals is not None:
contig_ht = contig_ht.filter(
hl.is_missing(excluded_calling_intervals[contig_ht.key])
)
contig_size = contig_ht.count()
logger.info("Contig %s has %d bases for coverage.", contig, contig_size)
return contig_size
def get_chr_dp_ann(chrom: str) -> hl.Table:
"""
Compute the mean depth of the specified chromosome.
The total depth will be determined using the sum DP of either reference and variant data or only variant data
depending on the value of `use_only_variants` in the outer function.
If `use_only_variants` is set to False then this value is computed using the median block coverage (summed over
the block size). If `use_only_variants` is set to True, this value is computed using the sum of DP for all
variants divided by the total number of variants.
The depth calculations will be determined using only non par regions if the contig is an X or Y reference contig
and using the intervals specified by `included_calling_intervals` and excluding intervals specified by
`excluded_calling_intervals` if either is defined in the outer function (when `use_only_variants` is not
set this only applies to the contig size estimate and is not used when computing chromosome depth).
:param chrom: Chromosome to compute the mean depth of
:return: Table of a per sample mean depth of `chrom`
"""
contig_size = get_contig_size(chrom)
chr_mt = hl.filter_intervals(mt, [hl.parse_locus_interval(chrom)])
if chrom in ref.x_contigs:
chr_mt = chr_mt.filter_rows(chr_mt.locus.in_x_nonpar())
if chrom in ref.y_contigs:
chr_mt = chr_mt.filter_rows(chr_mt.locus.in_y_nonpar())
if use_only_variants:
if included_calling_intervals is not None:
chr_mt = chr_mt.filter_rows(
hl.is_defined(included_calling_intervals[chr_mt.locus])
)
if excluded_calling_intervals is not None:
chr_mt = chr_mt.filter_rows(
hl.is_missing(excluded_calling_intervals[chr_mt.locus])
)
return chr_mt.select_cols(
**{
f"{chrom}_mean_dp": hl.agg.filter(
chr_mt.LGT.is_non_ref(),
hl.agg.sum(chr_mt.DP),
)
/ hl.agg.filter(chr_mt.LGT.is_non_ref(), hl.agg.count())
}
).cols()
else:
return chr_mt.select_cols(
**{
f"{chrom}_mean_dp": (
hl.agg.sum(
hl.if_else(
chr_mt.LGT.is_hom_ref(),
chr_mt.DP * (1 + chr_mt.END - chr_mt.locus.position),
chr_mt.DP,
)
)
/ contig_size
)
}
).cols()
normalization_chrom_dp = get_chr_dp_ann(normalization_contig)
chrX_dp = get_chr_dp_ann(chr_x)
chrY_dp = get_chr_dp_ann(chr_y)
ht = normalization_chrom_dp.annotate(
**chrX_dp[normalization_chrom_dp.key],
**chrY_dp[normalization_chrom_dp.key],
)
return ht.annotate(
**{
f"{chr_x}_ploidy": ht[f"{chr_x}_mean_dp"]
/ (ht[f"{normalization_contig}_mean_dp"] / 2),
f"{chr_y}_ploidy": ht[f"{chr_y}_mean_dp"]
/ (ht[f"{normalization_contig}_mean_dp"] / 2),
}
)
def densify_all_reference_sites(
mtds: Union[hl.MatrixTable, hl.vds.VariantDataset],
reference_ht: hl.Table,
interval_ht: Optional[hl.Table] = None,
row_key_fields: Union[Tuple[str], List[str], Set[str]] = ("locus",),
entry_keep_fields: Union[Tuple[str], List[str], Set[str]] = ("GT",),
) -> hl.MatrixTable:
"""
Densify a VariantDataset or Sparse MatrixTable at all sites in a reference Table.
:param mtds: Input sparse MatrixTable or VariantDataset.
:param reference_ht: Table of reference sites.
:param interval_ht: Optional Table of intervals to filter to.
:param row_key_fields: Fields to use as row key. Defaults to locus.
:param entry_keep_fields: Fields to keep in entries before performing the
densification. Defaults to GT.
:return: Densified MatrixTable.
"""
is_vds = isinstance(mtds, hl.vds.VariantDataset)
if interval_ht is not None and not is_vds:
raise NotImplementedError(
"Filtering to an interval list for a sparse Matrix Table is currently"
" not supported."
)
# Filter datasets to interval list.
if interval_ht is not None:
reference_ht = reference_ht.filter(
hl.is_defined(interval_ht[reference_ht.locus])