-
Notifications
You must be signed in to change notification settings - Fork 1
/
mrp.py
2146 lines (1837 loc) · 70.2 KB
/
mrp.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#!/usr/bin/env python3
from __future__ import division
import argparse, os, itertools, collections, gc, time
from functools import partial, reduce
import pandas as pd
import numpy as np
import numpy.matlib
import scipy.stats
from colorama import Fore, Back, Style
pd.options.mode.chained_assignment = None
def is_pos_def_and_full_rank(X, tol=0.99):
"""
Ensures a matrix is positive definite and full rank.
Keep diagonals and multiples every other cell by .99.
Parameters:
X: Matrix to verify.
tol: A tolerance factor for continual multiplication until the matrix is
singular (Default: 0.99).
Returns:
X: Verified (and, if applicable, adjusted) matrix.
converged: bool for whether or not the matrix is singular.
"""
X = np.matrix(X)
if np.all(np.linalg.eigvals(X) > 0):
return X, True
else:
i = 0
while not np.all(np.linalg.eigvals(X) > 0):
X = np.diag(np.diag(X)) + tol * X - tol * np.diag(np.diag(X))
i += 1
if i > 4:
return X, False
return X, True
def safe_inv(X, matrix_name, block, agg_type):
"""
Safely inverts a matrix, or returns NaN.
Parameters:
X: Matrix to invert.
matrix_name: One of "U"/"v_beta" - used to print messages when inversion fails.
block: Name of the aggregation block (gene/variant).
Used to print messages when inversion fails.
agg_type: One of "gene"/"variant". Dictates block of aggregation.
Used to print messages when inversion fails.
Returns:
X_inv: Inverse of X.
"""
try:
X_inv = np.linalg.inv(X)
except np.linalg.LinAlgError:
X = is_pos_def_and_full_rank(X)
try:
X_inv = np.linalg.inv(X)
except np.linalg.LinAlgError:
print("Could not invert " + matrix_name + " for " + agg_type + " " + block+ ".")
return np.nan
return X_inv
def farebrother(quad_T, d, fb):
"""
Farebrother method from CompQuadForm.
Parameters:
quad_T: Value point at which distribution function is to be evaluated.
d: Distinct non-zero characteristic root(s) of A*Sigma.
fb: Farebrother R method (rpy2 object).
Returns:
p_value: Farebrother p-value.
"""
res = fb(quad_T, d)
return np.asarray(res)[0]
def davies(quad_T, d, dm):
"""
Davies method from CompQuadForm.
Parameters:
quad_T: Value point at which distribution function is to be evaluated.
d: Distinct non-zero characteristic root(s) of A*Sigma.
dm: Davies R method (rpy2 object).
Returns:
p_value: Davies p-value.
"""
res = dm(quad_T, d)
return np.asarray(res)[0]
def imhof(quad_T, d, im):
"""
Imhof method from CompQuadForm.
Parameters:
quad_T: Value point at which distribution function is to be evaluated.
d: Distinct non-zero characteristic root(s) of A*Sigma.
im: Imhof R method (rpy2 object).
Returns:
p_value: Imhof p-value.
"""
res = im(quad_T, d)
return np.asarray(res)[0]
def initialize_r_objects():
"""
Initializes Farebrother, Davies, and Imhof R methods as rpy2 objects.
Returns:
fb: Farebrother R method (rpy2 object).
dm: Davies R method (rpy2 object).
im: Imhof R method (rpy2 object).
"""
robjects.r(
"""
require(MASS)
require(CompQuadForm)
farebrother.method <- function(quadT, d, h = rep(1, length(d)), delta = rep(0, length(d)), maxiter = 100000, epsilon = 10^-16, type = 1) {
return(farebrother(quadT, d, h, delta, maxit = as.numeric(maxiter), eps = as.numeric(epsilon), mode = as.numeric(type))$Qq)
}
""")
robjects.r(
"""
require(MASS)
require(CompQuadForm)
imhof.method <- function(quadT, d, h = rep(1, length(d)), delta = rep(0, length(d)), epsilon = 10^-16, lim = 10000) {
return(imhof(quadT, d, h, delta, epsabs = as.numeric(epsilon), epsrel = as.numeric(epsilon), limit=as.numeric(lim))$Qq)
}
""")
robjects.r(
"""
require(MASS)
require(CompQuadForm)
davies.method <- function(quadT, d, h = rep(1, length(d)), delta = rep(0, length(d)), sig = 0, limit = 10000, accuracy = 0.0001) {
return(davies(quadT, d, h, delta, sigma=as.numeric(sig), lim = as.numeric(limit), acc = as.numeric(accuracy))$Qq)
}
""")
fb = robjects.globalenv["farebrother.method"]
fb = robjects.r["farebrother.method"]
im = robjects.globalenv["imhof.method"]
im = robjects.r["imhof.method"]
dm = robjects.globalenv["davies.method"]
dm = robjects.r["davies.method"]
return fb, dm, im
def return_BF_pvals(beta, U, v_beta, v_beta_inv, fb, dm, im, methods):
"""
Computes a p-value from the quadratic form that is subsumed by the Bayes Factor.
Parameters:
beta: Effect size vector without missing data.
U: Kronecker product of the three matrices (S*M*K x S*M*K)
dictating correlation structures; no missing data.
v_beta: Diagonal matrix of variances of effect sizes without missing data.
v_beta_inv: Inverse of v_beta.
fb: Farebrother R method (rpy2 object).
dm: Davies R method (rpy2 object).
im: Imhof R method (rpy2 object).
methods: List of p-value generating method(s) to apply to our data.
Returns:
p_values: List of p-values corresponding to each method specified as input.
"""
n = beta.shape[0]
A = v_beta + U
A, _ = is_pos_def_and_full_rank(A)
if np.any(np.isnan(A)):
return [np.nan] * len(methods)
A_inv = np.linalg.inv(A)
quad_T = np.asmatrix(beta.T) * np.asmatrix((v_beta_inv - A_inv)) * np.asmatrix(beta)
B, _ = is_pos_def_and_full_rank(
np.matlib.eye(n) - np.asmatrix(A_inv) * np.asmatrix(v_beta)
)
if np.any(np.isnan(B)):
return [np.nan] * len(methods)
d = np.linalg.eig(B)[0]
d = [i for i in d if i > 0.01]
p_values = collections.deque([])
for method in methods:
if method == "farebrother":
p_value = farebrother(quad_T, d, fb)
elif method == "davies":
p_value = davies(quad_T, d, dm)
elif method == "imhof":
p_value = imhof(quad_T, d, im)
p_value = max(0, min(1, p_value))
p_values.append(p_value)
return p_values
def compute_posterior_probs(log10BF, prior_odds_list):
"""
Computes posterior probability given prior odds and a log10 Bayes Factor.
Parameters:
log10BF: log10 Bayes Factor of given association.
prior_odds_list: List of assumed prior odds.
Returns:
posterior_probs: List of posterior probabilities of the event
given the list of prior odds and the Bayes Factor.
"""
BF = 10 ** (log10BF)
posterior_odds_list = [prior_odds * BF for prior_odds in prior_odds_list]
posterior_probs = [
(posterior_odds / (1 + posterior_odds))
for posterior_odds in posterior_odds_list
]
return posterior_probs
def return_BF(
U, beta, v_beta, mu, block, agg_type, prior_odds_list, p_value_methods, fb, dm, im
):
"""
Given quantities calculated previously and the inputs, returns the associated
Bayes Factor.
Parameters:
U: Kronecker product of the three matrices (S*M*K x S*M*K)
dictating correlation structures; no missing data.
beta: Effect size vector without missing data.
v_beta: Diagonal matrix of variances of effect sizes without missing data.
mu: A mean of genetic effects, size of beta
(NOTE: default is 0, can change in the code below).
block: Name of the aggregation block (gene/variant).
agg_type: One of "gene"/"variant". Dictates block of aggregation.
prior_odds_list: List of prior odds used as assumptions to calculate
posterior probabilities of Bayes Factors.
p_value_methods: List of p-value methods used to calculate p-values from
Bayes Factors.
fb, dm, im: initialized R functions for Farebrother, Davies, and Imhof methods.
NoneType if p_value_methods is [].
Returns:, []
log10BF: log_10 Bayes Factor (ratio of marginal likelihoods of alternative model,
which accounts for priors, and null).
posterior_probs: List of posterior probabilities corresponding to each prior odds
in prior_odds_list.
p_values: List of p-values corresponding to each method in p_value_methods.
converged: whether or not v_beta_inv and U_inv are defined.
"""
v_beta_inv = safe_inv(v_beta, "v_beta", block, agg_type)
U_inv = safe_inv(U, "U", block, agg_type)
if v_beta_inv is not np.nan and U_inv is not np.nan:
sum_inv = safe_inv(U_inv + v_beta_inv, "U_inv + v_beta_inv", block, agg_type)
if sum_inv is np.nan:
np.nan, [], [], False
fat_middle = v_beta_inv - (v_beta_inv.dot(sum_inv)).dot(v_beta_inv)
logBF = (
-0.5 * np.linalg.slogdet(np.matlib.eye(beta.shape[0]) + v_beta_inv * U)[1]
+ 0.5 * beta.T.dot(v_beta_inv.dot(beta))
- 0.5 * (((beta - mu).T).dot(fat_middle)).dot(beta - mu)
)
logBF = float(np.array(logBF))
log10BF = logBF / np.log(10)
posterior_probs = (
compute_posterior_probs(log10BF, prior_odds_list) if prior_odds_list else []
)
p_values = (
return_BF_pvals(beta, U, v_beta, v_beta_inv, fb, dm, im, p_value_methods)
if p_value_methods
else []
)
return log10BF, posterior_probs, p_values, True
else:
return np.nan, [], [], False
def delete_rows_and_columns(X, indices_to_remove):
"""
Helper function to delete rows and columns from a matrix.
Parameters:
X: Matrix that needs adjustment.
indices_to_remove: Rows and columns to be deleted.
Returns:
X: Smaller matrix that has no missing data.
"""
X = np.delete(X, indices_to_remove, axis=0)
X = np.delete(X, indices_to_remove, axis=1)
return X
def adjust_for_missingness(U, omega, beta, se, beta_list):
"""
Deletes rows and columns where we do not have effect sizes/standard errors.
Calls method delete_rows_and_columns, a helper function that calls the numpy
command.
Parameters:
U: Kronecker product of the three matrices (S*M*K x S*M*K)
dictating correlation structures; may relate to missing data.
omega: (S*M*K x S*M*K) matrix that contains correlation of errors
across variants, studies, and phenotypes.
beta: Vector of effect sizes within the unit of aggregation;
may contain missing data.
se: Vector of standard errors within the unit of aggregation;
may contain missing data.
beta_list: List of effect sizes within the unit of aggregation;
may contain missing data.
Returns:
U: Potentially smaller U matrix not associated with missing data.
omega: Potentially smaller omega matrix not associated with missing data.
beta: Potentially smaller beta vector without missing data.
se: Potentially smaller SE vector without missing data.
"""
indices_to_remove = np.argwhere(np.isnan(beta_list))
U = delete_rows_and_columns(U, indices_to_remove)
omega = delete_rows_and_columns(omega, indices_to_remove)
beta = beta[~np.isnan(beta)].reshape(-1, 1)
se = se[~np.isnan(se)]
return U, omega, beta, se
def generate_beta_se(subset_df, pops, phenos):
"""
Gathers effect sizes and standard errors from a unit of aggregation (gene/variant).
Parameters:
subset_df: Slice of the original dataframe that encompasses the current unit of
aggregation (gene/variant).
pops: Unique set of populations (studies) to use for analysis.
phenos: Unique set of phenotypes to use for analysis.
Returns:
beta_list: A list of effect sizes (some may be missing) from the subset.
se_list: A list of standard errors (some may be missing) from the subset.
"""
beta_list = collections.deque([])
se_list = collections.deque([])
for pop in pops:
for pheno in phenos:
if ("BETA_" + pop + "_" + pheno) in subset_df.columns:
beta_list.extend(list(subset_df["BETA_" + pop + "_" + pheno]))
se_list.extend(list(subset_df["SE_" + pop + "_" + pheno]))
else:
beta_list.extend([np.nan] * len(subset_df))
se_list.extend([np.nan] * len(subset_df))
return beta_list, se_list
def calculate_all_params(
df,
pops,
phenos,
key,
sigma_m_type,
R_study,
R_phen,
R_var_model,
agg_type,
M,
err_corr,
mean,
):
"""
Calculates quantities needed for MRP (U, beta, v_beta, mu).
Parameters:
df: Merged, filtered, and annotated dataframe containing summary statistics.
pops: Unique set of populations (studies) to use for analysis.
phenos: Unique set of phenotypes to use for analysis.
key: Variant/gene name.
sigma_m_type: One of "sigma_m_mpc_pli"/"sigma_m_var"/"sigma_m_1"/"sigma_m_005".
Dictates variant scaling factor by functional annotation.
R_study: R_study matrix to use for analysis (independent/similar).
R_phen: R_phen matrix to use for analysis (empirically calculated).
R_var_model: String ("independent"/"similar") corresponding to R_var matrices to
use for analysis.
agg_type: One of "gene"/"variant". Dictates block of aggregation.
M: Number of variants within the gene block if agg_type is "gene"; if "variant", 1.
err_corr: A (S*K x S*K) matrix of correlation of errors across studies
and phenotypes. Used to calculate v_beta.
mean: Prior mean of genetic effects to use (from command line).
Returns:
U: Kronecker product of the three matrices (S*M*K x S*M*K)
dictating correlation structures, adjusted for missingness.
beta: A S*M*K x 1 vector of effect sizes.
v_beta: A (S*M*K x S*M*K) matrix of variances of effect sizes.
mu: A mean of genetic effects, size of beta
(NOTE: default is 0, can change in the code below).
converged: whether or not U is pos-def/full-rank.
num_variants_mpc: the nummber of MPC-augmented variants in the gene.
num_variants_pli: the number of pLI-augmented variants in the gene.
"""
subset_filter_col = "gene_symbol" if agg_type == "gene" else "V"
subset_df = df.loc[np.in1d(df[subset_filter_col], [key]), ]
if sigma_m_type == "sigma_m_mpc_pli":
num_variants_pli = np.sum(np.logical_and(
np.in1d(subset_df['category'], ['ptv']),
np.in1d(subset_df['pLI'], ['True'])
))
num_variants_mpc = np.sum(np.logical_and(
np.in1d(subset_df['category'], ['pav']),
(subset_df['MPC'] >= 1)
))
else:
num_variants_mpc, num_variants_pli = None, None
sigma_m = np.array(subset_df[sigma_m_type])
diag_sigma_m = np.diag(np.atleast_1d(sigma_m))
R_var = np.diag(np.ones(M)) if R_var_model == "independent" else np.ones((M, M))
R_var, _ = is_pos_def_and_full_rank(R_var)
R_study, _ = is_pos_def_and_full_rank(R_study)
R_phen, _ = is_pos_def_and_full_rank(R_phen)
S_var = np.dot(np.dot(diag_sigma_m, R_var), diag_sigma_m)
beta_list, se_list = generate_beta_se(subset_df, pops, phenos)
beta = np.array(beta_list).reshape(-1, 1)
se = np.array(se_list)
omega = np.kron(err_corr, np.diag(np.ones(M)))
U = np.kron(np.kron(R_study, R_phen), S_var)
U, omega, beta, se = adjust_for_missingness(U, omega, beta, se, beta_list)
U, converged = is_pos_def_and_full_rank(U, 0.8)
diag_se = np.diag(se)
v_beta = np.dot(np.dot(diag_se, omega), diag_se)
v_beta, _ = is_pos_def_and_full_rank(v_beta)
mu = np.ones(beta.shape) * mean
return U, beta, v_beta, mu, converged, num_variants_mpc, num_variants_pli
def output_file(
bf_dfs, agg_type, pops, phenos, maf_thresh, se_thresh, out_folder, out_filename, chrom
):
"""
Outputs a file containing aggregation unit and Bayes Factors.
Parameters:
bf_dfs: List of dataframes containing Bayes Factors from each analysis.
agg_type: One of "gene"/"variant". Dictates block of aggregation.
pops: Unique set of populations (studies) to use for analysis.
phenos: Unique set of phenotypes to use for analysis.
maf_thresh: Maximum MAF of variants in this run.
se_thresh: Upper threshold for SE for this run.
out_folder: Output folder in which results are stored.
out_filename: Optional prefix for file output.
chrom: List of chromosomes (optional) from command line.
"""
outer_merge = partial(pd.merge, on=[agg_type], how="outer")
out_df = reduce(outer_merge, bf_dfs)
if not os.path.exists(out_folder):
os.makedirs(out_folder)
print("")
print(Fore.RED + "Folder " + out_folder + " created." + Style.RESET_ALL)
print("")
if not out_filename:
out_file = os.path.join(out_folder, "_".join(pops) + "_" + "_".join(phenos) + "_" + agg_type + "_maf_" + str(maf_thresh) + "_se_" + str(se_thresh) + "_chrs_" + "_".join(chrom) + ".tsv.gz")
else:
out_file = os.path.join(out_folder, "_".join(pops) + "_" + out_filename + "_" + agg_type + "_maf_" + str(maf_thresh) + "_se_" + str(se_thresh) + ".tsv.gz")
sort_col = [col for col in out_df.columns if "log_10_BF" in col][0]
out_df = out_df.sort_values(by=sort_col, ascending=False)
out_df.to_csv(out_file, sep="\t", index=False, compression="gzip")
print("")
print(Fore.RED + "Results written to " + out_file + "." + Style.RESET_ALL)
print("")
def get_output_file_columns(
agg_type,
R_study_model,
R_var_model,
sigma_m_type,
analysis,
prior_odds_list,
p_value_methods,
):
"""
Sets up the columns that must be enumerated in the output dataframe from MRP.
Parameters:
agg_type: One of "gene"/"variant". Dictates block of aggregation.
R_study_model: String ("independent"/"similar") corresponding to R_study.
R_var_model: String ("independent"/"similar") corresponding to R_var matrices to
use for analysis.
sigma_m_type: One of "sigma_m_mpc_pli"/"sigma_m_var"/"sigma_m_1"/"sigma_m_005".
scaling factor by functional annotation.
analysis: One of "ptv"/"pav"/"pcv". Dictates which variants are included.
prior_odds_list: List of prior odds used as assumptions to calculate posterior
probabilities of Bayes Factors.
p_value_methods: List of p-value methods used to calculate p-values from Bayes
Factors.
Returns:
bf_df_columns: Columns needed for the output file.
fb: Farebrother R method (rpy2 object), or None if --p_value is not invoked.
dm: Davies R method (rpy2 object), or None if --p_value is not invoked.
im: Imhof R method (rpy2 object), or None if --p_value is not invoked.
"""
bf_df_columns = collections.deque([agg_type])
if agg_type == "gene":
bf_df_columns.extend(["num_variants_" + analysis])
if sigma_m_type == "sigma_m_mpc_pli":
bf_df_columns.extend(
["num_variants_mpc_" + analysis, "num_variants_pli_" + analysis]
)
bf_df_columns.extend(
[
"log_10_BF"
+ "_study_"
+ R_study_model
+ "_var_"
+ R_var_model
+ "_"
+ sigma_m_type
+ "_"
+ analysis
]
)
if prior_odds_list:
bf_df_columns.extend(
[
"posterior_prob_w_prior_odds_"
+ str(prior_odds)
+ "_study_"
+ R_study_model
+ "_var_"
+ R_var_model
+ "_"
+ sigma_m_type
+ "_"
+ analysis
for prior_odds in prior_odds_list
]
)
if p_value_methods:
fb, dm, im = initialize_r_objects()
bf_df_columns.extend(
[
"p_value_"
+ p_value_method
+ "_study_"
+ R_study_model
+ "_var_"
+ R_var_model
+ "_"
+ sigma_m_type
+ "_"
+ analysis
for p_value_method in p_value_methods
]
)
else:
fb = dm = im = None
return bf_df_columns, fb, dm, im
def run_mrp(
df,
S,
K,
pops,
phenos,
R_study,
R_study_model,
R_phen,
err_corr,
R_var_model,
analysis,
sigma_m_type,
agg_type,
prior_odds_list,
p_value_methods,
mean,
):
"""
Runs MRP with the given parameters.
Parameters:
df: Merged dataframe containing all relevant summary statistics.
S: Number of populations/studies.
K: Number of phenotypes.
pops: Unique set of populations (studies) to use for analysis.
phenos: Unique set of phenotypes to use for analysis.
R_study: R_study matrix to use for analysis (independent/similar).
R_study_model: String ("independent"/"similar") corresponding to R_study.
R_phen: R_phen matrix to use for analysis (empirically calculated).
err_corr: A (S*K x S*K) matrix of correlation of errors across studies and
phenotypes. Used to calculate v_beta.
R_var_model: String ("independent"/"similar") corresponding to R_var matrices to
use for analysis.
analysis: One of "ptv"/"pav"/"pcv". Dictates which variants are included.
sigma_m_type: One of "sigma_m_mpc_pli"/"sigma_m_var"/"sigma_m_1"/"sigma_m_005".
scaling factor by functional annotation.
agg_type: One of "gene"/"variant". Dictates block of aggregation.
prior_odds_list: List of prior odds used as assumptions to calculate posterior
probabilities of Bayes Factors.
p_value_methods: List of p-value methods used to calculate p-values from Bayes
Factors.
mean: Prior mean of genetic effects to use (from command line).
Returns:
bf_df: Dataframe with log_10 Bayes Factor, posterior odds, and p-value (if applicable).
"""
m_dict = (
df.groupby("gene_symbol").size()
if agg_type == "gene"
else df.groupby("V").size()
)
bf_df_columns, fb, dm, im = get_output_file_columns(
agg_type,
R_study_model,
R_var_model,
sigma_m_type,
analysis,
prior_odds_list,
p_value_methods,
)
data = collections.deque([])
num_converged = 0
for i, (key, value) in enumerate(m_dict.items()):
if i % 1000 == 0:
print("Done " + str(i) + " " + agg_type + "s out of " + str(len(m_dict)))
gc.collect()
M = value
U, beta, v_beta, mu, converged, num_variants_mpc, num_variants_pli = calculate_all_params(
df,
pops,
phenos,
key,
sigma_m_type,
R_study,
R_phen,
R_var_model,
agg_type,
M,
err_corr,
mean,
)
bf, posterior_probs, p_values, converged = return_BF(
U,
beta,
v_beta,
mu,
key,
agg_type,
prior_odds_list,
p_value_methods,
fb,
dm,
im,
)
if converged:
num_converged += 1
if agg_type == "gene" and sigma_m_type != "sigma_m_mpc_pli":
data.append([key, beta.shape[0], bf] + posterior_probs + p_values)
elif agg_type == "gene" and sigma_m_type == "sigma_m_mpc_pli":
data.append(
[key, beta.shape[0], num_variants_mpc, num_variants_pli, bf]
+ posterior_probs
+ p_values
)
else:
data.append([key, bf] + posterior_probs + p_values)
print("")
print(
str(num_converged)
+ "/"
+ str(len(m_dict))
+ " genes' matrices had well-behaved eigenvalues."
)
bf_df = pd.DataFrame(data, columns=bf_df_columns)
return bf_df
def print_params(
analysis,
R_study_model,
R_var_model,
agg_type,
sigma_m_type,
maf_thresh,
se_thresh,
prior_odds_list,
p_value_methods,
mean,
):
"""
Provides a text overview of each analysis in the terminal.
Parameters:
analysis: One of "ptv"/"pav"/"pcv". Dictates which variants are included.
R_study_model: One of "independent"/"similar". Dictates correlation structure
across studies.
R_var_model: One of "independent"/"similar". Dictates correlation structure
across variants.
agg_type: One of "gene"/"variant". Dictates block of aggregation.
sigma_m_type: One of "sigma_m_mpc_pli"/"sigma_m_var"/"sigma_m_1"/"sigma_m_005".
scaling factor by functional annotation.
maf_thresh: Maximum MAF of variants in this run.
prior_odds_list: List of prior odds used as assumptions to calculate posterior
probabilities of Bayes Factors.
p_value_methods: List of p-value methods used to calculate p-values from Bayes
Factors.
"""
print("")
print(Fore.YELLOW + "Analysis: " + Style.RESET_ALL + analysis)
print(Fore.YELLOW + "R_study model: " + Style.RESET_ALL + R_study_model)
print(Fore.YELLOW + "R_var model: " + Style.RESET_ALL + R_var_model)
print(Fore.YELLOW + "Aggregation by: " + Style.RESET_ALL + agg_type)
print(Fore.YELLOW + "Variant weighting factor: " + Style.RESET_ALL + sigma_m_type)
print(Fore.YELLOW + "MAF threshold: " + Style.RESET_ALL + str(maf_thresh))
print(Fore.YELLOW + "SE threshold: " + Style.RESET_ALL + str(se_thresh))
print(Fore.YELLOW + "Prior mean: " + Style.RESET_ALL + str(mean))
if prior_odds_list:
print(Fore.YELLOW + "Prior odds: " + Style.RESET_ALL + ", ".join([str(prior_odd) for prior_odd in prior_odds_list]))
if p_value_methods:
print(Fore.YELLOW + "Methods for p-value generation: " + Style.RESET_ALL + ", ".join(p_value_methods))
print("")
def filter_category(df, variant_filter):
"""
Filters a set of dataframes that have been read in based on functional consequence.
Dependent on the variant filter that is dictated by the analysis.
Parameters:
df: Merged dataframe containing all summary statistics.
variant_filter: The variant filter dictated by the analysis ("ptv"/"pav"/"pcv").
Returns:
df: Merged dataframe containing all relevant summary statistics;
filters out variants excluded from analysis.
"""
if variant_filter == "ptv":
df = df[df.category == "ptv"]
elif variant_filter == "pav":
df = df[(df.category == "ptv") | (df.category == "pav")]
elif variant_filter == "pcv":
df = df[(df.category == "ptv") | (df.category == "pav") | (df.category == "pcv")]
return df
def loop_through_parameters(
df,
se_thresh,
maf_threshes,
agg,
variant_filters,
S,
R_study_list,
R_study_models,
pops,
K,
R_phen,
phenos,
R_var_models,
sigma_m_types,
err_corr,
prior_odds_list,
p_value_methods,
out_folder,
out_filename,
mean,
chrom,
):
"""
Loops through parameters specified through command line (or defaults).
Parameters:
df: Merged dataframe containing all summary statistics.
se_thresh: Upper threshold for SE for this run.
maf_threshes: List of maximum MAFs of variants in your runs.
agg: Unique list of aggregation units ("gene"/"variant") to use for analysis.
variant_filters: Unique list of variant filters ("ptv"/"pav"/"pcv","all") to use
for analysis.
S: Number of populations/studies.
R_study_list: Unique list of R_study matrices to use for analysis.
R_study_models: Unique strings ("independent"/"similar") corresponding to each
matrix in R_study_list.
pops: Unique set of populations (studies) to use for analysis.
K: Number of phenotypes.
R_phen: R_phen matrix to use for analysis (empirically calculated).
phenos: Unique set of phenotypes to use for analysis.
R_var_models: Unique strings ("independent"/"similar") corresponding to R_var
matrices to use for analysis.
sigma_m_types: Unique list of sigma_m types ("sigma_m_mpc_pli"/"sigma_m_var"/"sigma_m_1"/"sigma_m_005")
to use for analysis.
err_corr: Matrix of correlation of errors across studies and phenotypes.
prior_odds_list: List of prior odds used as assumptions to calculate posterior
probabilities of Bayes Factors.
p_value_methods: List of p-value methods used to calculate p-values from Bayes
Factors.
out_folder: Folder where output will be placed.
out_filename: Optional prefix for file output.
chrom: List of chromosomes (optional) from command line.
"""
if (S == 1) and (len(R_study_models) > 1):
print(Fore.YELLOW + "Since we are not meta-analyzing, R_study is just [1]." + Style.RESET_ALL)
print("")
R_study_models = ["similar"]
R_study_list = [R_study_list[0]]
for maf_thresh in maf_threshes:
print(Fore.YELLOW + "Running MRP across parameters for MAF threshold " + str(maf_thresh) + " and SE threshold " + str(se_thresh) + "..." + Style.RESET_ALL)
maf_df = df[(df.maf <= maf_thresh) & (df.maf >= 0)]
for agg_type in agg:
bf_dfs = collections.deque([])
# If not aggregating, then R_var choice does not affect BF
if (agg_type == "variant") and (len(R_var_models) > 1):
print(Fore.YELLOW + "Since we are not aggregating, R_var is just [1]." + Style.RESET_ALL)
R_var_models = ["independent"]
for analysis in variant_filters:
analysis_df = filter_category(maf_df, analysis)
analysis_bf_dfs = collections.deque([])
for sigma_m_type in sigma_m_types:
sigma_m_type_bf_dfs = collections.deque([])
for R_study, R_study_model in zip(R_study_list, R_study_models):
for R_var_model in R_var_models:
print_params(
analysis,
R_study_model,
R_var_model,
agg_type,
sigma_m_type,
maf_thresh,
se_thresh,
prior_odds_list,
p_value_methods,
mean,
)
bf_df = run_mrp(
analysis_df,
S,
K,
pops,
phenos,
R_study,
R_study_model,
R_phen,
err_corr,
R_var_model,
analysis,
sigma_m_type,
agg_type,
prior_odds_list,
p_value_methods,
mean,
)
sigma_m_type_bf_dfs.append(bf_df)
if sigma_m_type == "sigma_m_mpc_pli":
outer_merge = partial(
pd.merge,
on=[
agg_type,
"num_variants_" + analysis,
"num_variants_mpc_" + analysis,
"num_variants_pli_" + analysis,
],
how="outer",
)
else:
outer_merge = partial(
pd.merge,
on=[agg_type, "num_variants_" + analysis],
how="outer",
)
sigma_m_type_bf_df = reduce(outer_merge, sigma_m_type_bf_dfs)
analysis_bf_dfs.append(sigma_m_type_bf_df)
if agg_type == "gene":
outer_merge = partial(
pd.merge, on=[agg_type, "num_variants_" + analysis], how="outer"
)
else:
outer_merge = partial(pd.merge, on=[agg_type], how="outer")
analysis_bf_df = reduce(outer_merge, analysis_bf_dfs)
bf_dfs.append(analysis_bf_df)
output_file(
bf_dfs,
agg_type,
pops,
phenos,
maf_thresh,
se_thresh,
out_folder,
out_filename,
chrom,
)
def get_sigma_and_consequence_categories():
"""
Here we define two constants: consequence category and sigma_m value for each consequence category
"""
sigma_m = {
'ptv': 0.2,
'pav': 0.05,
'pcv': 0.03,
'intron': 0.03,
'utr': 0.03,
'others': 0.02,
}
consequence_categories = {
'ptv': [
"splice_acceptor_variant",
"splice_donor_variant",
"stop_lost",
"stop_gained",
"frameshift_variant",
"transcript_ablation",
"start_lost",
"pLoF",
],
'pav': [
"missense_variant",
"splice_region_variant",
"protein_altering_variant",
"inframe_insertion",
"inframe_deletion",
"missense",
"LC",
],
'pcv': [
"stop_retained_variant",
"coding_sequence_variant",
"incomplete_terminal_codon_variant",
"synonymous_variant",
"start_retained_variant",
],
'intron': [
"intron_variant",
],
'utr': [
"5_prime_UTR_variant",
"3_prime_UTR_variant",