-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathGCTA.py
More file actions
2009 lines (1668 loc) · 80.9 KB
/
GCTA.py
File metadata and controls
2009 lines (1668 loc) · 80.9 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
# coding: utf-8
# # GCTA
#
# In this notebook, we will use GCTA to calculate the Polygenic Risk Score (PRS).
#
# **Note:** GCTA needs to be installed or placed in the same directory as this notebook.
#
# 1. It can be downloaded from this link: [GCTA](https://yanglab.westlake.edu.cn/software/gcta/#Download).
# 1. We recommend using Linux. In cases where Windows is required due to package installation issues on Linux, we provide the following guidance:
#
# 1. For Windows, use `gcta`.
# 2. For Linux, use `./gcta`.
# ## GCTA Hyperparameters
#
# ### Hyperparameters for GCTA performed using PLINK
#
# #### Pruning Parameters
#
# Informs Plink that we wish to perform pruning with a window size of 200 variants, sliding across the genome with a step size of 50 variants at a time, and filter out any SNPs with LD \( r^2 \) higher than 0.25.
#
#
# ```python
# 1. p_window_size = [200]
# 2. p_slide_size = [50]
# 3. p_LD_threshold = [0.25]
# ```
#
# #### Clumping Parameters
#
# The P-value threshold for an SNP to be included. 1 means to include all SNPs for clumping. SNPs having \( r^2 \) higher than 0.1 with the index SNPs will be removed. SNPs within 200k of the index SNP are considered for clumping.
#
# ```python
# 1. clump_p1 = [1]
# 2. clump_r2 = [0.1]
# 3. clump_kb = [200]
# ```
# #### PCA
# Pca also affects the results evident from the initial analysis; however, including more PCA overfits the model.
#
# ### Hyperparameters for GCTA
#
# These parameters can be passed to GCTA. GCTA provides two parameters when calculating the PRS as specified in [this link](https://yanglab.westlake.edu.cn/software/gcta/#SBLUP).
#
# 1. `--cojo-wind`
# 2. `--cojo-sblup`
#
# `--cojo-wind` is the same as clumping kb as specified in the documentation [link](https://yanglab.westlake.edu.cn/software/gcta/#SBLUP). We will use the same values for this parameter as `clump_kb`.
#
# `--cojo-sblup` is the input parameter `lambda = m * (1 / h2SNP - 1)` where m is the total number of SNPs used in this analysis (i.e. the number of SNPs in common between the summary data and the reference set), and h2SNP is the proportion of variance in the phenotype explained by all SNPs. h2SNP can be estimated from GCTA-GREML if individual-level data are available or from LD score regression analysis of the summary data.
#
#
# #### Calculate h2 Heritability
#
# There are multiple ways to calculate heritability, and we considered two methods required for lambda = m * (1 / h2SNP - 1).
#
# ##### Using LDpred-2
#
# To calculate h2 using LDpred-2, we followed the [LDpred-2 tutorial](https://choishingwan.github.io/PRS-Tutorial/ldpred/).
# The code for this part is in R, as LDpred-2 is in R.
#
# 1. Using SNPs from the HapMap as preferred by the authors. The name in the code is `LDpred-2_hapmap`.
# 2. Using all the SNPs. The name in the code is `LDpred-2_full`.
#
# This approach is computationally expensive, as the correlation between all the SNPs in a specific chromosome is being calculated.
#
# ##### Using GCTA
#
# To calculate h2 using GCTA, we followed the [GCTA tutorial](https://yanglab.westlake.edu.cn/software/gcta/#Tutorial).
#
# 1. Using only genotype data and phenotype. The name in the code is `GCTA_genotype`.
#
# 1. `gcta --bfile FILE --make-grm --out FILE`
# 2. `gcta --grm FILE --pheno FILE.PHENP --reml --out FILE`
#
#
# 2. Using genotype data, covariates, and phenotype. The name in the code is `GCTA_genotype_covariate`.
#
# 1. `gcta --bfile FILE --make-grm --out FILE`
# 2. `gcta --grm FILE --pheno FILE.PHENP --qcovar FILE.cov --reml --out FILE`
#
#
# 3. Using genotype data, covariates, PCA, and phenotype. The name in the code is `GCTA_genotype_covariate_pca`.
#
# 1. `gcta --bfile FILE --make-grm --out FILE`
# 2. `gcta --grm FILE --pheno FILE.PHENP --reml --qcovar FILE.cov_pca --out FILE`
#
# OR
#
# 2. `gcta --grm FILE --pheno FILE.PHENP --reml-no-constrain --qcovar FILE.cov_pca --out FILE`
#
# **Handling REML Non-convergence:**
#
# In some cases, the REML calculation may not converge ([source](https://gcta.freeforums.net/thread/366/error-log-likelihood-converged)). To address this, the `--reml-no-constrain` flag can be used. However, it's important to note that in such cases, the heritability value might exceed 1, often attributed to sample relatedness ([source](https://www.researchgate.net/post/What_does_it_mean_when_heritability_is_larger_than_1#:~:text=1)%20Heritability%20can%20be%20greater,can%20also%20cause%20this%20result.)).
#
# An alternative approach involves using a flag like `--grm-cutoff 0.025`, similar to Plink's `--rel-cutoff 0.125`. This allows for the exclusion of specific samples, facilitating the recalculation of heritability.
#
# **To handle this issue, we used a simple approach in which we considered the `--reml` flag and calculated the heritability. If the heritability calculation doesn't converge, we used the `--grm-cutoff 0.01` flag and calculated the heritability again. The calculated heritability was then used to estimate the `lambda` for SBLUP.**
#
#
#
#
# ```bash
# gcta --grm FILE --pheno FILE.PHENP --reml --grm-cutoff 0.025 --qcovar FILE.cov_pca --out FILE
# ```
#
#
#
# Heritability calculated using GCTA and using genotype data, covariates, PCA, and phenotype, and LDpred-2 method using all the methods were almost the same.
#
#
#
# All GCTA functions generate the following file:
#
# Summary result of REML analysis:
#
# | Source | Variance | SE |
# |--------|----------|---------|
# | V(G) | 0.869695 | 0.790524|
# | V(e) | 0.000001 | 0.787625|
# | Vp | 0.869696 | 0.063776|
# | V(G)/Vp| 0.999999 | 0.905632|
#
# h2 = V(G)/Vp
#
# **Some code segments should be used when calculating the PRS, and some steps can be executed separately.**
#
# **When calculating h2 from any of the methods, the number of SNPs included in the analysis varies, and only the most suitable SNPs are being considered for the analysis. Kindly see the output screen for the changes in the number of SNPs or the SNPs being removed.**
#
#
#
#
# #### Using LDpred-2 to Calculate h2
#
# When calculating correlation for h2 calculation using LDpred-2, the following arguments should be passed, which are the same as the clumping parameters. These arguments should be passed to the R file when calculating h2.
#
# 1. `size = clump_kb = [200]`
# For one SNP, window size around this SNP to compute correlations. Default is 500. If not providing infos.pos (NULL, the default), this is a window in the number of SNPs, otherwise, it is a window in kb (genetic distance).
#
# 2. `alpha = clump_p1 = [1]`
# Type-I error for testing correlations. Default is 1 (no threshold is applied).
#
# 3. `thr_r2 = clump_r2 = [0.1]`
# Threshold to apply on squared correlations. Default is 0.
#
# The above information is taken from:
#
# ```R
# library(bigsnpr)
# options(bigstatsr.check.parallel.blas = FALSE)
# options(default.nproc.blas = NULL)
# library(data.table)
# library(magrittr)
# help(snp_cor)
# ```
# ```R
# The following code shows the process to calcuate the h2 using LDpred-2.
#
# Actual code in `GCTA_R_1.R`
#
# ##### Arguments
# 1. Argument one is the directory. Example: `SampleData1`
# 2. Argument two is the file name. Example: `SampleData1\\Fold_0`
# 3. Argument three is the output file name. Example: `train_data`
# 4. Argument four is the specific function to be called. Example: `train_data.QC.clumped.pruned`
#
# 5. Argument five is LDpred-2 option. Example: `LDpred-2_full` or `LDpred-2_hapmap`
# 6. Argument six is the size parameter. Example: `200`
# 7. Argument seven is the alpha parameter. Example: `1`
# 8. Argument eight is the thr_r2 parameter. Example: `0.1`
# 9. Argument nine is the number of PCA. Example: `6`
#
# ###### Sample values
# 1. "SampleData1"
# 2. "SampleData1\\Fold_0"
# 3. "train_data"
# 4. "train_data.QC.clumped.pruned"
# 5. "2"
# 6. "200"
# 7. "1"
# 8. "0.1"
# 9. "6"
#
# ```
#
#
# ##### `LDpred-2_hapmap`
#
# ```R
# # Load libraries.
# library(bigsnpr)
# options(bigstatsr.check.parallel.blas = FALSE)
# options(default.nproc.blas = NULL)
# library(data.table)
# library(magrittr)
# # Load phenotype file.
# result <-paste(".",args[2],paste(args[3],toString(".PHENO"), sep = ""),sep="//")
# phenotype <- fread(result)
# # Load covariate file.
# result <-paste(".",args[2],paste(args[3],toString(".cov"), sep = ""),sep="//")
# covariate <- fread(result)
# # Load PCA.
# result <-paste(".",args[2],paste(args[3],toString(".eigenvec"), sep = ""),sep="//")
# pcs <- fread(result)
# # Rename columns
# colnames(pcs) <- c("FID","IID", paste0("PC",1:as.numeric(args[9])))
# # Merge phenotype, covariate and PCA.
# pheno <- merge(phenotype, covariate) %>%
# merge(., pcs)
# # Download hapmap information from LDpred-2
# info <- readRDS(runonce::download_file(
# "https://ndownloader.figshare.com/files/25503788",
# fname = "map_hm3_ldpred2.rds"))
# # Read in the summary statistic file
# result <-paste(".",args[1],paste(args[1],toString(".txt"), sep = ""),sep="//")
#
# sumstats <- bigreadr::fread2(result)
# # LDpred 2 require the header to follow the exact naming
# names(sumstats) <-
# c("chr",
# "pos",
# "rsid",
# "a1",
# "a0",
# "n_eff",
# "beta_se",
# "p",
# "OR",
# "INFO",
# "MAF")
# # Transform the OR into log(OR)
# sumstats$beta <- log(sumstats$OR)
# # Filter out hapmap SNPs
# # Restrict analysis to SNPs common in Hapmap SNPs and summmary file SNPs.
# sumstats <- sumstats[sumstats$rsid%in% info$rsid,]
#
# # Get maximum amount of cores
# NCORES <- nb_cores()
# # Open a temporary file
#
# if (dir.exists("tmp-data")) {
# # Delete the directory and its contents
# system(paste("rm -r", shQuote("tmp-data")))
# print(paste("Directory", "tmp-data", "deleted."))
# }
# tmp <- tempfile(tmpdir = "tmp-data")
# on.exit(file.remove(paste0(tmp, ".sbk")), add = TRUE)
# # Initialize variables for storing the LD score and LD matrix
# corr <- NULL
# ld <- NULL
# # We want to know the ordering of samples in the bed file
# fam.order <- NULL
# # Preprocess the bed file (only need to do once for each data set)
# result <-paste(".",args[2],paste(args[4],toString(".rds"), sep = ""),sep="//")
# if (file.exists(result)) {
# file.remove(result)
# print(paste("File", result, "deleted."))
# }
# result <-paste(".",args[2],paste(args[4],toString(".bk"), sep = ""),sep="//")
# if (file.exists(result)) {
# file.remove(result)
# print(paste("File", result, "deleted."))
# }
#
#
# result <-paste(".",args[2],paste(args[4],toString(".bed"), sep = ""),sep="//")
#
# snp_readBed(result)
# # Now attach the genotype object
# result <-paste(".",args[2],paste(args[4],toString(".rds"), sep = ""),sep="//")
#
# obj.bigSNP <- snp_attach(result)
#
# # Extract the SNP information from the genotype
# map <- obj.bigSNP$map[-3]
#
# names(map) <- c("chr", "rsid", "pos", "a1", "a0")
#
# # perform SNP matching
# info_snp <- snp_match(sumstats, map)
# help(snp_match)
# info_snp
# # Assign the genotype to a variable for easier downstream analysis
# genotype <- obj.bigSNP$genotypes
# # Rename the data structures
# CHR <- map$chr
# POS <- map$pos
# # get the CM information from 1000 Genome
# # will download the 1000G file to the current directory (".")
# #help(snp_asGeneticPos)
# POS2 <- snp_asGeneticPos(CHR, POS, dir = ".")
#
#
# for (chr in 1:22) {
# # Extract SNPs that are included in the chromosome
#
# ind.chr <- which(info_snp$chr == chr)
# print(length(ind.chr))
# ind.chr2 <- info_snp$`_NUM_ID_`[ind.chr]
# ind.chr2
# print(length(ind.chr2))
#
# # Calculate the LD
# help(snp_cor)
# corr0 <- snp_cor(
# genotype,
# ind.col = ind.chr2,
# ncores = NCORES,
# infos.pos = POS2[ind.chr2],
# #size = 200,
# #thr_r2=0.1,
# #alpha = 1
#
# size = as.numeric(args[6]),
# alpha = as.numeric(args[7]),
#
# thr_r2=as.numeric(args[8]),
# )
# if (chr == 1) {
# ld <- Matrix::colSums(corr0^2)
# help(as_SFBM)
# corr <- as_SFBM(corr0, tmp)
# } else {
# ld <- c(ld, Matrix::colSums(corr0^2))
# corr$add_columns(corr0, nrow(corr))
# }
# }
#
#
# # We assume the fam order is the same across different chromosomes
# fam.order <- as.data.table(obj.bigSNP$fam)
# # Rename fam order
# setnames(fam.order,
# c("family.ID", "sample.ID"),
# c("FID", "IID"))
#
# df_beta <- info_snp[,c("beta", "beta_se", "n_eff", "_NUM_ID_")]
#
# length(df_beta$beta)
# length(ld)
# help(snp_ldsc)
# ldsc <- snp_ldsc(ld,
# length(ld),
# chi2 = (df_beta$beta / df_beta$beta_se)^2,
# sample_size = df_beta$n_eff,
# blocks = NULL)
# h2_est <- ldsc[["h2"]]
# h2_est
#
# if (file.exists("ldpred_h2_hapmap.txt")) {
# file.remove("ldpred_h2_hapmap.txt")
# print(paste("File", result, "deleted."))
# }
# write.table(h2_est, file = "ldpred_h2_hapmap.txt", col.names = FALSE)
#
# if (file.exists("ldpred_h2_variants.txt")) {
# file.remove("ldpred_h2_variants.txt")
# print(paste("File", result, "deleted."))
# }
# write.table(length(ld), file = "ldpred_h2_variants.txt", col.names = FALSE)
# ```
#
#
#
#
# #### `LDpred-2_full`
#
#
# ```R
# library(bigsnpr)
# options(bigstatsr.check.parallel.blas = FALSE)
# options(default.nproc.blas = NULL)
# library(data.table)
# library(magrittr)
# result <-paste(".",args[2],paste(args[3],toString(".PHENO"), sep = ""),sep="//")
# phenotype <- fread(result)
# result <-paste(".",args[2],paste(args[3],toString(".cov"), sep = ""),sep="//")
# covariate <- fread(result)
# result <-paste(".",args[2],paste(args[3],toString(".eigenvec"), sep = ""),sep="//")
# pcs <- fread(result)
# # rename columns
# colnames(pcs) <- c("FID","IID", paste0("PC",1:as.numeric(args[9])))
# # generate required table
# pheno <- merge(phenotype, covariate) %>%
# merge(., pcs)
# info <- readRDS(runonce::download_file(
# "https://ndownloader.figshare.com/files/25503788",
# fname = "map_hm3_ldpred2.rds"))
# # Read in the summary statistic file
# result <-paste(".",args[1],paste(args[1],toString(".txt"), sep = ""),sep="//")
#
# sumstats <- bigreadr::fread2(result)
# # LDpred 2 require the header to follow the exact naming
# names(sumstats) <-
# c("chr",
# "pos",
# "rsid",
# "a1",
# "a0",
# "n_eff",
# "beta_se",
# "p",
# "OR",
# "INFO",
# "MAF")
# # Transform the OR into log(OR)
# sumstats$beta <- log(sumstats$OR)
# # Filter out hapmap SNPs
# # Turn off this line to ensure that all the SNPs from the sumstats are included.
# # Restrict analysis to SNPs common in Hapmap SNPs and summmary file SNPs
# #sumstats <- sumstats[sumstats$rsid%in% info$rsid,]
#
# # Get maximum amount of cores
# NCORES <- nb_cores()
# # Open a temporary file
#
# if (dir.exists("tmp-data")) {
# # Delete the directory and its contents
#
# system(paste("rm -r", shQuote("tmp-data")))
# print(paste("Directory", "tmp-data", "deleted."))
# }
# tmp <- tempfile(tmpdir = "tmp-data")
# on.exit(file.remove(paste0(tmp, ".sbk")), add = TRUE)
# # Initialize variables for storing the LD score and LD matrix
# corr <- NULL
# ld <- NULL
# # We want to know the ordering of samples in the bed file
# fam.order <- NULL
# # preprocess the bed file (only need to do once for each data set)
# result <-paste(".",args[2],paste(args[4],toString(".rds"), sep = ""),sep="//")
# if (file.exists(result)) {
# file.remove(result)
# print(paste("File", result, "deleted."))
# }
# result <-paste(".",args[2],paste(args[4],toString(".bk"), sep = ""),sep="//")
# if (file.exists(result)) {
# file.remove(result)
# print(paste("File", result, "deleted."))
# }
#
#
# result <-paste(".",args[2],paste(args[4],toString(".bed"), sep = ""),sep="//")
#
# snp_readBed(result)
# # now attach the genotype object
# result <-paste(".",args[2],paste(args[4],toString(".rds"), sep = ""),sep="//")
#
# obj.bigSNP <- snp_attach(result)
#
# # extract the SNP information from the genotype
# map <- obj.bigSNP$map[-3]
#
# names(map) <- c("chr", "rsid", "pos", "a1", "a0")
#
# # perform SNP matching
# info_snp <- snp_match(sumstats, map)
# help(snp_match)
# info_snp
# # Assign the genotype to a variable for easier downstream analysis
# genotype <- obj.bigSNP$genotypes
# # Rename the data structures
# CHR <- map$chr
# POS <- map$pos
# # get the CM information from 1000 Genome
# # will download the 1000G file to the current directory (".")
# #help(snp_asGeneticPos)
# POS2 <- snp_asGeneticPos(CHR, POS, dir = ".")
#
#
# for (chr in 1:22) {
# # Extract SNPs that are included in the chromosome
#
# ind.chr <- which(info_snp$chr == chr)
# print(length(ind.chr))
# ind.chr2 <- info_snp$`_NUM_ID_`[ind.chr]
#
# print(length(ind.chr2))
#
# # Calculate the LD
# help(snp_cor)
# corr0 <- snp_cor(
# genotype,
# ind.col = ind.chr,
# ncores = NCORES,
# infos.pos = POS2[ind.chr2],
# #size = 200,
# #thr_r2=0.1,
# #alpha = 1
#
# size = as.numeric(args[6]),
# alpha = as.numeric(args[7]),
# thr_r2=as.numeric(args[8]),
# )
# if (chr == 1) {
# ld <- Matrix::colSums(corr0^2)
# help(as_SFBM)
# corr <- as_SFBM(corr0, tmp)
# } else {
# ld <- c(ld, Matrix::colSums(corr0^2))
# corr$add_columns(corr0, nrow(corr))
# }
# }
#
#
# # We assume the fam order is the same across different chromosomes
# fam.order <- as.data.table(obj.bigSNP$fam)
# # Rename fam order
# setnames(fam.order,
# c("family.ID", "sample.ID"),
# c("FID", "IID"))
#
# df_beta <- info_snp[,c("beta", "beta_se", "n_eff", "_NUM_ID_")]
#
# length(df_beta$beta)
# length(ld)
# help(snp_ldsc)
# ldsc <- snp_ldsc(ld,
# length(ld),
# chi2 = (df_beta$beta / df_beta$beta_se)^2,
# sample_size = df_beta$n_eff,
# blocks = NULL)
# h2_est <- ldsc[["h2"]]
#
#
# if (file.exists("ldpred_h2_full.txt")) {
# file.remove("ldpred_h2_full.txt")
# print(paste("File", result, "deleted."))
# }
#
# write.table(h2_est, file = "ldpred_h2_full.txt", col.names = FALSE)
# ```
#
#
# ### GWAS File Processing for GCTA
#
# GCTA requires GWAS file in a specific format as specified in this document https://yanglab.westlake.edu.cn/software/gcta/#COJO. The GWAS we have contains all the required columns for processing.
#
#
#
# In[1]:
import os
import pandas as pd
import numpy as np
import sys
import os
import pandas as pd
import numpy as np
def check_phenotype_is_binary_or_continous(filedirec):
# Read the processed quality controlled file for a phenotype
df = pd.read_csv(filedirec+os.sep+filedirec+'_QC.fam',sep="\s+",header=None)
column_values = df[5].unique()
if len(set(column_values)) == 2:
return "Binary"
else:
return "Continous"
filedirec = sys.argv[1]
#filedirec = "SampleData1"
#filedirec = "asthma_19"
#filedirec = "migraine_0"
# Read the GWAS file.
GWAS = filedirec + os.sep + filedirec+".gz"
df = pd.read_csv(GWAS,compression= "gzip",sep="\s+")
if check_phenotype_is_binary_or_continous(filedirec)=="Binary":
if "BETA" in df.columns.to_list():
# For Binary Phenotypes.
df["OR"] = np.exp(df["BETA"])
df = df[['CHR', 'BP', 'SNP', 'A1', 'A2', 'N', 'SE', 'P', 'OR', 'INFO', 'MAF']]
else:
# For Binary Phenotype.
df = df[['CHR', 'BP', 'SNP', 'A1', 'A2', 'N', 'SE', 'P', 'OR', 'INFO', 'MAF']]
# Transform the GWAS as required by GCTA.
df_transformed = pd.DataFrame({
'SNP': df['SNP'],
'A1': df['A1'],
'A2': df['A2'],
'freq': df['MAF'],
'b': df['OR'],
'se': df['SE'],
'p': df['P'],
'N': df['N']
})
elif check_phenotype_is_binary_or_continous(filedirec)=="Continous":
if "BETA" in df.columns.to_list():
# For Continous Phenotype.
df = df[['CHR', 'BP', 'SNP', 'A1', 'A2', 'N', 'SE', 'P', 'BETA', 'INFO', 'MAF']]
else:
df["BETA"] = np.log(df["OR"])
df = df[['CHR', 'BP', 'SNP', 'A1', 'A2', 'N', 'SE', 'P', 'BETA', 'INFO', 'MAF']]
df_transformed = pd.DataFrame({
'SNP': df['SNP'],
'A1': df['A1'],
'A2': df['A2'],
'freq': df['MAF'],
'b': df['BETA'],
'se': df['SE'],
'p': df['P'],
'N': df['N']
})
# Save this file as it is being required by GCTA.
output_file = filedirec + os.sep +filedirec+"_GCTA.txt"
df_transformed.to_csv(output_file,sep="\t",index=False)
print(df_transformed.head().to_markdown())
print("Length of DataFrame!",len(df_transformed))
# Save this file as it is being required for LDpred-2 for heritability calculation to calculate the heritability required by GCTA.
# Save this file that contains just betas even for binary phenotypes.
if "BETA" in df.columns.to_list():
# For Continous Phenotype.
df = df[['CHR', 'BP', 'SNP', 'A1', 'A2', 'N', 'SE', 'P', 'BETA', 'INFO', 'MAF']]
else:
df["BETA"] = np.log(df["OR"])
df = df[['CHR', 'BP', 'SNP', 'A1', 'A2', 'N', 'SE', 'P', 'BETA', 'INFO', 'MAF']]
df.to_csv(filedirec + os.sep +filedirec+".txt",sep="\t",index=False)
print(df.head().to_markdown())
print("Length of DataFrame!",len(df))
# ### Define Hyperparameters
#
# Define hyperparameters to be optimized and set initial values.
#
# ### Extract Valid SNPs from Clumped File
#
# For Windows, download `gwak`, and for Linux, the `awk` command is sufficient. For Windows, `GWAK` is required. You can download it from [here](https://sourceforge.net/projects/gnuwin32/). Get it and place it in the same directory.
#
#
# ### Execution Path
#
# At this stage, we have the genotype training data `newtrainfilename = "train_data.QC"` and genotype test data `newtestfilename = "test_data.QC"`.
#
# We modified the following variables:
#
# 1. `filedirec = "SampleData1"` or `filedirec = sys.argv[1]`
# 2. `foldnumber = "0"` or `foldnumber = sys.argv[2]` for HPC.
#
# Only these two variables can be modified to execute the code for specific data and specific folds. Though the code can be executed separately for each fold on HPC and separately for each dataset, it is recommended to execute it for multiple diseases and one fold at a time.
# Here’s the corrected text in Markdown format:
#
#
# ### P-values
#
# PRS calculation relies on P-values. SNPs with low P-values, indicating a high degree of association with a specific trait, are considered for calculation.
#
# You can modify the code below to consider a specific set of P-values and save the file in the same format.
#
# We considered the following parameters:
#
# - **Minimum P-value**: `1e-10`
# - **Maximum P-value**: `1.0`
# - **Minimum exponent**: `10` (Minimum P-value in exponent)
# - **Number of intervals**: `100` (Number of intervals to be considered)
#
# The code generates an array of logarithmically spaced P-values:
#
# ```python
# import numpy as np
# import os
#
# minimumpvalue = 10 # Minimum exponent for P-values
# numberofintervals = 100 # Number of intervals to be considered
#
# allpvalues = np.logspace(-minimumpvalue, 0, numberofintervals, endpoint=True) # Generating an array of logarithmically spaced P-values
#
# print("Minimum P-value:", allpvalues[0])
# print("Maximum P-value:", allpvalues[-1])
#
# count = 1
# with open(os.path.join(folddirec, 'range_list'), 'w') as file:
# for value in allpvalues:
# file.write(f'pv_{value} 0 {value}\n') # Writing range information to the 'range_list' file
# count += 1
#
# pvaluefile = os.path.join(folddirec, 'range_list')
# ```
#
# In this code:
# - `minimumpvalue` defines the minimum exponent for P-values.
# - `numberofintervals` specifies how many intervals to consider.
# - `allpvalues` generates an array of P-values spaced logarithmically.
# - The script writes these P-values to a file named `range_list` in the specified directory.
#
# In[2]:
from operator import index
import pandas as pd
import numpy as np
import os
import subprocess
import sys
import pandas as pd
import statsmodels.api as sm
import pandas as pd
from sklearn.metrics import roc_auc_score, confusion_matrix
from statsmodels.stats.contingency_tables import mcnemar
def create_directory(directory):
"""Function to create a directory if it doesn't exist."""
if not os.path.exists(directory): # Checking if the directory doesn't exist
os.makedirs(directory) # Creating the directory if it doesn't exist
return directory # Returning the created or existing directory
foldnumber = sys.argv[2]
#foldnumber = "0" # Setting 'foldnumber' to "0"
folddirec = filedirec + os.sep + "Fold_" + foldnumber # Creating a directory path for the specific fold
trainfilename = "train_data" # Setting the name of the training data file
newtrainfilename = "train_data.QC" # Setting the name of the new training data file
testfilename = "test_data" # Setting the name of the test data file
newtestfilename = "test_data.QC" # Setting the name of the new test data file
# Number of PCA to be included as a covariate.
numberofpca = ["6"] # Setting the number of PCA components to be included
# Clumping parameters.
clump_p1 = [1] # List containing clump parameter 'p1'
clump_r2 = [0.1] # List containing clump parameter 'r2'
clump_kb = [200] # List containing clump parameter 'kb'
# Pruning parameters.
p_window_size = [200] # List containing pruning parameter 'window_size'
p_slide_size = [50] # List containing pruning parameter 'slide_size'
p_LD_threshold = [0.25] # List containing pruning parameter 'LD_threshold'
# Kindly note that the number of p-values to be considered varies, and the actual p-value depends on the dataset as well.
# We will specify the range list here.
minimumpvalue = 10 # Minimum p-value in exponent
numberofintervals = 20 # Number of intervals to be considered
allpvalues = np.logspace(-minimumpvalue, 0, numberofintervals, endpoint=True) # Generating an array of logarithmically spaced p-values
count = 1
with open(folddirec + os.sep + 'range_list', 'w') as file:
for value in allpvalues:
file.write(f'pv_{value} 0 {value}\n') # Writing range information to the 'range_list' file
count = count + 1
print("Minimum P-value",allpvalues[0])
print("Maximum P-value",allpvalues[-1])
pvaluefile = folddirec + os.sep + 'range_list'
# Initializing an empty DataFrame with specified column names
prs_result = pd.DataFrame(columns=["clump_p1", "clump_r2", "clump_kb", "p_window_size", "p_slide_size", "p_LD_threshold",
"pvalue", "model","numberofpca","tempalpha","l1weight","h2","lambda","numberofvariants","Train_pure_prs", "Train_null_model", "Train_best_model",
"Test_pure_prs", "Test_null_model", "Test_best_model"])
# ### Define Helper Functions
#
# 1. **Perform Clumping and Pruning**
# 2. **Calculate PCA Using Plink**
# 3. **Fit Binary Phenotype and Save Results**
# 4. **Fit Continuous Phenotype and Save Results**
#
# In[6]:
import os
import subprocess
import pandas as pd
import statsmodels.api as sm
from sklearn.metrics import explained_variance_score
def perform_clumping_and_pruning_on_individual_data(traindirec, newtrainfilename,numberofpca, p1_val, p2_val, p3_val, c1_val, c2_val, c3_val,Name,pvaluefile):
command = [
"./plink",
"--bfile", traindirec+os.sep+newtrainfilename,
"--indep-pairwise", p1_val, p2_val, p3_val,
"--out", traindirec+os.sep+trainfilename
]
subprocess.run(command)
# First perform pruning and then clumping and the pruning.
command = [
"./plink",
"--bfile", traindirec+os.sep+newtrainfilename,
"--clump-p1", c1_val,
"--extract", traindirec+os.sep+trainfilename+".prune.in",
"--clump-r2", c2_val,
"--clump-kb", c3_val,
"--clump", filedirec+os.sep+filedirec+".txt",
"--clump-snp-field", "SNP",
"--clump-field", "P",
"--out", traindirec+os.sep+trainfilename
]
subprocess.run(command)
# Extract the valid SNPs from th clumped file.
# For windows download gwak for linux awk commmand is sufficient.
### For windows require GWAK.
### https://sourceforge.net/projects/gnuwin32/
##3 Get it and place it in the same direc.
#os.system("gawk "+"\""+"NR!=1{print $3}"+"\" "+ traindirec+os.sep+trainfilename+".clumped > "+traindirec+os.sep+trainfilename+".valid.snp")
#print("gawk "+"\""+"NR!=1{print $3}"+"\" "+ traindirec+os.sep+trainfilename+".clumped > "+traindirec+os.sep+trainfilename+".valid.snp")
#Linux:
command = f"awk 'NR!=1{{print $3}}' {traindirec}{os.sep}{trainfilename}.clumped > {traindirec}{os.sep}{trainfilename}.valid.snp"
os.system(command)
#print("awk "+"\""+"NR!=1{print $3}"+"\" "+ traindirec+os.sep+trainfilename+".clumped > "+traindirec+os.sep+trainfilename+".valid.snp")
command = [
"./plink",
"--make-bed",
"--bfile", traindirec+os.sep+newtrainfilename,
"--indep-pairwise", p1_val, p2_val, p3_val,
"--extract", traindirec+os.sep+trainfilename+".valid.snp",
"--out", traindirec+os.sep+newtrainfilename+".clumped.pruned"
]
subprocess.run(command)
command = [
"./plink",
"--make-bed",
"--bfile", traindirec+os.sep+testfilename,
"--indep-pairwise", p1_val, p2_val, p3_val,
"--extract", traindirec+os.sep+trainfilename+".valid.snp",
"--out", traindirec+os.sep+testfilename+".clumped.pruned"
]
subprocess.run(command)
def calculate_pca_for_traindata_testdata_for_clumped_pruned_snps(traindirec, newtrainfilename,p):
# Calculate the PRS for the test data using the same set of SNPs and also calculate the PCA.
# Also extract the PCA at this point.
# PCA are calculated afer clumping and pruining.
command = [
"./plink",
"--bfile", folddirec+os.sep+testfilename+".clumped.pruned",
# Select the final variants after clumping and pruning.
"--extract", traindirec+os.sep+trainfilename+".valid.snp",
"--pca", p,
"--out", folddirec+os.sep+testfilename
]
subprocess.run(command)
command = [
"./plink",
"--bfile", traindirec+os.sep+newtrainfilename+".clumped.pruned",
# Select the final variants after clumping and pruning.
"--extract", traindirec+os.sep+trainfilename+".valid.snp",
"--pca", p,
"--out", traindirec+os.sep+trainfilename
]
subprocess.run(command)
# This function fit the binary model on the PRS.
def fit_binary_phenotype_on_PRS(traindirec, newtrainfilename,h2model,p, p1_val, p2_val, p3_val, c1_val, c2_val, c3_val,Name,pvaluefile, tempdata,_lambda1):
threshold_values = allpvalues
# Merge the covariates, pca and phenotypes.
tempphenotype_train = pd.read_table(traindirec+os.sep+newtrainfilename+".clumped.pruned"+".fam", sep="\s+",header=None)
phenotype_train = pd.DataFrame()
phenotype_train["Phenotype"] = tempphenotype_train[5].values
pcs_train = pd.read_table(traindirec+os.sep+trainfilename+".eigenvec", sep="\s+",header=None, names=["FID", "IID"] + [f"PC{str(i)}" for i in range(1, int(p)+1)])
covariate_train = pd.read_table(traindirec+os.sep+trainfilename+".cov",sep="\s+")
covariate_train.fillna(0, inplace=True)
covariate_train = covariate_train[covariate_train["FID"].isin(pcs_train["FID"].values) & covariate_train["IID"].isin(pcs_train["IID"].values)]
covariate_train['FID'] = covariate_train['FID'].astype(str)
pcs_train['FID'] = pcs_train['FID'].astype(str)
covariate_train['IID'] = covariate_train['IID'].astype(str)
pcs_train['IID'] = pcs_train['IID'].astype(str)
covandpcs_train = pd.merge(covariate_train, pcs_train, on=["FID","IID"])
covandpcs_train.fillna(0, inplace=True)
## Scale the covariates!
from sklearn.preprocessing import MinMaxScaler
from sklearn.metrics import explained_variance_score
scaler = MinMaxScaler()
normalized_values_train = scaler.fit_transform(covandpcs_train.iloc[:, 2:])
#covandpcs_train.iloc[:, 2:] = normalized_values_test
tempphenotype_test = pd.read_table(traindirec+os.sep+testfilename+".clumped.pruned"+".fam", sep="\s+",header=None)
phenotype_test= pd.DataFrame()
phenotype_test["Phenotype"] = tempphenotype_test[5].values
pcs_test = pd.read_table(traindirec+os.sep+testfilename+".eigenvec", sep="\s+",header=None, names=["FID", "IID"] + [f"PC{str(i)}" for i in range(1, int(p)+1)])
covariate_test = pd.read_table(traindirec+os.sep+testfilename+".cov",sep="\s+")
covariate_test.fillna(0, inplace=True)
covariate_test = covariate_test[covariate_test["FID"].isin(pcs_test["FID"].values) & covariate_test["IID"].isin(pcs_test["IID"].values)]
covariate_test['FID'] = covariate_test['FID'].astype(str)
pcs_test['FID'] = pcs_test['FID'].astype(str)
covariate_test['IID'] = covariate_test['IID'].astype(str)
pcs_test['IID'] = pcs_test['IID'].astype(str)
covandpcs_test = pd.merge(covariate_test, pcs_test, on=["FID","IID"])
covandpcs_test.fillna(0, inplace=True)
normalized_values_test = scaler.transform(covandpcs_test.iloc[:, 2:])
#covandpcs_test.iloc[:, 2:] = normalized_values_test
tempalphas = [0.1,0.2,0.3,0.4,0.5,0.6,0.7,0.8,0.9]
l1weights = [0.1,0.2,0.3,0.4,0.5,0.6,0.7,0.8,0.9]
tempalphas = [0.1]
l1weights = [0.1]
phenotype_train["Phenotype"] = phenotype_train["Phenotype"].replace({1: 0, 2: 1})
phenotype_test["Phenotype"] = phenotype_test["Phenotype"].replace({1: 0, 2: 1})
for tempalpha in tempalphas:
for l1weight in l1weights:
try:
null_model = sm.Logit(phenotype_train["Phenotype"], sm.add_constant(covandpcs_train.iloc[:, 2:])).fit_regularized(alpha=tempalpha, L1_wt=l1weight)
#null_model = sm.Logit(phenotype_train["Phenotype"], sm.add_constant(covandpcs_train.iloc[:, 2:])).fit()
except:
print("XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX")
continue
train_null_predicted = null_model.predict(sm.add_constant(covandpcs_train.iloc[:, 2:]))
from sklearn.metrics import roc_auc_score, confusion_matrix
from sklearn.metrics import r2_score
test_null_predicted = null_model.predict(sm.add_constant(covandpcs_test.iloc[:, 2:]))
global prs_result
for i in threshold_values:
try:
prs_train = pd.read_table(traindirec+os.sep+Name+os.sep+"train_data.pv_"+f"{i}.profile", sep="\s+", usecols=["FID", "IID", "SCORE"])
except:
continue
prs_train['FID'] = prs_train['FID'].astype(str)
prs_train['IID'] = prs_train['IID'].astype(str)
try:
prs_test = pd.read_table(traindirec+os.sep+Name+os.sep+"test_data.pv_"+f"{i}.profile", sep="\s+", usecols=["FID", "IID", "SCORE"])
except:
continue
prs_test['FID'] = prs_test['FID'].astype(str)
prs_test['IID'] = prs_test['IID'].astype(str)
pheno_prs_train = pd.merge(covandpcs_train, prs_train, on=["FID", "IID"])
pheno_prs_test = pd.merge(covandpcs_test, prs_test, on=["FID", "IID"])
try:
model = sm.Logit(phenotype_train["Phenotype"], sm.add_constant(pheno_prs_train.iloc[:, 2:])).fit_regularized(alpha=tempalpha, L1_wt=l1weight)
#model = sm.Logit(phenotype_train["Phenotype"], sm.add_constant(pheno_prs_train.iloc[:, 2:])).fit()
except:
continue