-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathHAIL.py
More file actions
1564 lines (1211 loc) · 67.8 KB
/
HAIL.py
File metadata and controls
1564 lines (1211 loc) · 67.8 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
#
# # HAIL
#
# In this notebook, we used [Hail](https://github.com/hail-is/hail) to calculate Polygenic Risk Scores (PRS). Hail does not calculate new betas but instead uses the existing weights from the GWAS and applies a custom formula for the calculation.
#
# We followed this tutorial to calculate the PRS:
# [https://nbviewer.org/github/ddbj/imputation-server-wf/blob/main/Notebooks/hail-prs-tutorial.ipynb](https://nbviewer.org/github/ddbj/imputation-server-wf/blob/main/Notebooks/hail-prs-tutorial.ipynb)
#
# ## Basic Process
#
# 1. Read the genotype data.
# 2. Convert it to VCF.
# 3. Use Beagle to convert the data to Beagle format.
# 4. Convert the Beagle format to Hail format.
# 5. Pass the data to Hail, GWAS, and genotype.
# 6. Calculate PRS using Hail.
#
# ### Genotype Data Processing
#
# 1. **Convert genotype data to VCF format.**
# Hail requires data in `beagle.vcf.gz` format. The first step is to convert the `bed`, `bim`, and `fam` files to VCF format. A simple approach is to extract genotype data for each chromosome and then convert the data to VCF.
#
# ```bash
# plink --bfile traindirec/newtrainfilename.clumped.pruned --chr 22 --make-bed --out traindirec/newtrainfilename.clumped.pruned.22
# plink --bfile traindirec/newtrainfilename.clumped.pruned.22 --chr 22 --recode vcf --out traindirec/hail.train.22
# ```
#
# 2. **Download the phased reference panel.**
# To run the following commands, download the phased reference panel from 1000 Genomes and place it in the current working directory:
# [1000 Genomes Reference Panel](https://ftp.1000genomes.ebi.ac.uk/vol1/ftp/release/20130502/)
#
# ```bash
# wget https://ftp.1000genomes.ebi.ac.uk/vol1/ftp/release/20130502/ALL.chr1.phase3_shapeit2_mvncall_integrated_v5b.20130502.genotypes.vcf.gz
# wget https://ftp.1000genomes.ebi.ac.uk/vol1/ftp/release/20130502/ALL.chr2.phase3_shapeit2_mvncall_integrated_v5b.20130502.genotypes.vcf.gz
# wget https://ftp.1000genomes.ebi.ac.uk/vol1/ftp/release/20130502/ALL.chr3.phase3_shapeit2_mvncall_integrated_v5b.20130502.genotypes.vcf.gz
# wget https://ftp.1000genomes.ebi.ac.uk/vol1/ftp/release/20130502/ALL.chr4.phase3_shapeit2_mvncall_integrated_v5b.20130502.genotypes.vcf.gz
# wget https://ftp.1000genomes.ebi.ac.uk/vol1/ftp/release/20130502/ALL.chr5.phase3_shapeit2_mvncall_integrated_v5b.20130502.genotypes.vcf.gz
# wget https://ftp.1000genomes.ebi.ac.uk/vol1/ftp/release/20130502/ALL.chr6.phase3_shapeit2_mvncall_integrated_v5b.20130502.genotypes.vcf.gz
# wget https://ftp.1000genomes.ebi.ac.uk/vol1/ftp/release/20130502/ALL.chr7.phase3_shapeit2_mvncall_integrated_v5b.20130502.genotypes.vcf.gz
# wget https://ftp.1000genomes.ebi.ac.uk/vol1/ftp/release/20130502/ALL.chr8.phase3_shapeit2_mvncall_integrated_v5b.20130502.genotypes.vcf.gz
# wget https://ftp.1000genomes.ebi.ac.uk/vol1/ftp/release/20130502/ALL.chr9.phase3_shapeit2_mvncall_integrated_v5b.20130502.genotypes.vcf.gz
# wget https://ftp.1000genomes.ebi.ac.uk/vol1/ftp/release/20130502/ALL.chr10.phase3_shapeit2_mvncall_integrated_v5b.20130502.genotypes.vcf.gz
# wget https://ftp.1000genomes.ebi.ac.uk/vol1/ftp/release/20130502/ALL.chr11.phase3_shapeit2_mvncall_integrated_v5b.20130502.genotypes.vcf.gz
# wget https://ftp.1000genomes.ebi.ac.uk/vol1/ftp/release/20130502/ALL.chr12.phase3_shapeit2_mvncall_integrated_v5b.20130502.genotypes.vcf.gz
# wget https://ftp.1000genomes.ebi.ac.uk/vol1/ftp/release/20130502/ALL.chr13.phase3_shapeit2_mvncall_integrated_v5b.20130502.genotypes.vcf.gz
# wget https://ftp.1000genomes.ebi.ac.uk/vol1/ftp/release/20130502/ALL.chr14.phase3_shapeit2_mvncall_integrated_v5b.20130502.genotypes.vcf.gz
# wget https://ftp.1000genomes.ebi.ac.uk/vol1/ftp/release/20130502/ALL.chr15.phase3_shapeit2_mvncall_integrated_v5b.20130502.genotypes.vcf.gz
# wget https://ftp.1000genomes.ebi.ac.uk/vol1/ftp/release/20130502/ALL.chr16.phase3_shapeit2_mvncall_integrated_v5b.20130502.genotypes.vcf.gz
# wget https://ftp.1000genomes.ebi.ac.uk/vol1/ftp/release/20130502/ALL.chr17.phase3_shapeit2_mvncall_integrated_v5b.20130502.genotypes.vcf.gz
# wget https://ftp.1000genomes.ebi.ac.uk/vol1/ftp/release/20130502/ALL.chr18.phase3_shapeit2_mvncall_integrated_v5b.20130502.genotypes.vcf.gz
# wget https://ftp.1000genomes.ebi.ac.uk/vol1/ftp/release/20130502/ALL.chr19.phase3_shapeit2_mvncall_integrated_v5b.20130502.genotypes.vcf.gz
# wget https://ftp.1000genomes.ebi.ac.uk/vol1/ftp/release/20130502/ALL.chr20.phase3_shapeit2_mvncall_integrated_v5b.20130502.genotypes.vcf.gz
# wget https://ftp.1000genomes.ebi.ac.uk/vol1/ftp/release/20130502/ALL.chr21.phase3_shapeit2_mvncall_integrated_v5b.20130502.genotypes.vcf.gz
# wget https://ftp.1000genomes.ebi.ac.uk/vol1/ftp/release/20130502/ALL.chr22.phase3_shapeit2_mvncall_integrated_v5b.20130502.genotypes.vcf.gz
# ```
#
# 3. **Alternatively, download the reference panel from Hail.**
# - Reference panels:
# [Hail Reference Panel](https://sc.ddbj.nig.ac.jp/en/advanced_guides/imputation_server_tutorial)
#
# - Files (2.6 GB):
# - [test-data.GRCh37.vcf.gz](https://zenodo.org/records/6650681/files/test-data.GRCh37.vcf.gz?download=1) (1.3 GB, `md5:aff8bca4689cc70f6dbc1c3296590458`)
# - [test-data.GRCh38.vcf.gz](https://zenodo.org/records/6650681/files/test-data.GRCh38.vcf.gz?download=1) (1.3 GB, `md5:d28a741e820444ca926f7b0d5ac2e196`)
#
# 4. **Download genetic distances from the Beagle website.**
# [Beagle Genetic Maps](https://bochet.gcc.biostat.washington.edu/beagle/genetic_maps/)
#
# 5. **Download Beagle.**
# - Beagle documentation:
# [Beagle Documentation](https://faculty.washington.edu/browning/beagle/beagle_5.4_18Mar22.pdf)
# - Beagle download page:
# [Download Beagle](https://faculty.washington.edu/browning/beagle/beagle.html)
#
# 6. **Run the Beagle command.**
# Run the following command to perform phasing and imputation:
#
# ```bash
# java -Xmx50g -jar beagle gt=traindirec/hail.train.22.vcf ref=ALL.chr22.phase3_shapeit2_mvncall_integrated_v5b.20130502.genotypes.vcf.gz map=plink.chr22.GRCh37.map out=traindirec/beagle.hail.train.22
# ```
#
# 7. **Follow the remaining process.**
# The rest of the process is straightforward and can be followed from this GitHub repository:
# [PRS on Hail GitHub Repository](https://github.com/hacchy1983/prs-on-hail-public)
#
#
# ## GWAS file processing for HAIL for Binary Phenotypes.
# When the effect size relates to disease risk and is thus given as an odds ratio (OR) rather than BETA (for continuous traits), the PRS is computed as a product of ORs. To simplify this calculation, take the natural logarithm of the OR so that the PRS can be computed using summation instead.
# In[24]:
import os
import pandas as pd
import numpy as np
import sys
filedirec = sys.argv[1]
#filedirec = "SampleData1"
#filedirec = "asthma_19"
#filedirec = "migraine_0"
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"
# Read the GWAS file.
GWAS = filedirec + os.sep + filedirec+".gz"
df = pd.read_csv(GWAS,compression= "gzip",sep="\s+")
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 = df.rename(columns={
'CHR': 'chr_name',
'BP': 'chr_position',
'A1': 'effect_allele',
'A2': 'other_allele',
'BETA': 'effect_weight'
})
# Selecting the relevant columns
df = df[['chr_name', 'chr_position', 'effect_allele', 'other_allele', 'effect_weight']]
# Remove duplicates based on 'chr_name' and 'chr_position'
print("Length of DataFrame!",len(df))
df = df.drop_duplicates(subset=['chr_name', 'chr_position', 'effect_allele', 'other_allele'])
print("Length of DataFrame!",len(df))
df.to_csv(filedirec + os.sep +"Hail.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[10]:
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
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", "numberofpca","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[20]:
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,
"--maf",str(0.2),
"--geno",str(0.001),
"--hwe",str(0.00001),
"--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)
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,p, p1_val, p2_val, p3_val, c1_val, c2_val, c3_val,Name,pvaluefile):
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
prs_train = pd.read_table(traindirec+os.sep+Name+os.sep+"train_hail_prs.csv",sep=",",index_col=0)
print(prs_train)
prs_train[['FID', 'IID']] = prs_train['subjectID'].str.split('_', expand=True)
# Drop the original 'Combined' column if it's no longer needed
prs_train = prs_train.drop(columns=['subjectID'])
prs_train.rename(columns={'PGS002724': 'SCORE'}, inplace=True)
prs_train['FID'] = prs_train['FID'].astype(str)
prs_train['IID'] = prs_train['IID'].astype(str)
prs_test = pd.read_table(traindirec+os.sep+Name+os.sep+"test_hail_prs.csv",sep=",",index_col=0)
print(prs_test)
prs_test[['FID', 'IID']] = prs_test['subjectID'].str.split('_', expand=True)
# Drop the original 'Combined' column if it's no longer needed
prs_test = prs_test.drop(columns=['subjectID'])
prs_test.rename(columns={'PGS002724': 'SCORE'}, inplace=True)
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
train_best_predicted = model.predict(sm.add_constant(pheno_prs_train.iloc[:, 2:]))
test_best_predicted = model.predict(sm.add_constant(pheno_prs_test.iloc[:, 2:]))
from sklearn.metrics import roc_auc_score, confusion_matrix
prs_result = prs_result._append({
"clump_p1": c1_val,
"clump_r2": c2_val,
"clump_kb": c3_val,
"p_window_size": p1_val,
"p_slide_size": p2_val,
"p_LD_threshold": p3_val,
#"pvalue": i,
"numberofpca":p,
"tempalpha":str(tempalpha),
"l1weight":str(l1weight),
"Train_pure_prs":roc_auc_score(phenotype_train["Phenotype"].values,prs_train['SCORE'].values),
"Train_null_model":roc_auc_score(phenotype_train["Phenotype"].values,train_null_predicted.values),
"Train_best_model":roc_auc_score(phenotype_train["Phenotype"].values,train_best_predicted.values),
"Test_pure_prs":roc_auc_score(phenotype_test["Phenotype"].values,prs_test['SCORE'].values),
"Test_null_model":roc_auc_score(phenotype_test["Phenotype"].values,test_null_predicted.values),
"Test_best_model":roc_auc_score(phenotype_test["Phenotype"].values,test_best_predicted.values),
}, ignore_index=True)
prs_result.to_csv(traindirec+os.sep+Name+os.sep+"Results.csv",index=False)
# This function fit the binary model on the PRS.
def fit_continous_phenotype_on_PRS(traindirec, newtrainfilename,p, p1_val, p2_val, p3_val, c1_val, c2_val, c3_val,Name,pvaluefile):
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.OLS(phenotype_train["Phenotype"], sm.add_constant(covandpcs_train.iloc[:, 2:])).fit_regularized(alpha=tempalpha, L1_wt=l1weight)
null_model = sm.OLS(phenotype_train["Phenotype"], sm.add_constant(covandpcs_train.iloc[:, 2:])).fit()
#null_model = sm.OLS(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
prs_train = pd.read_table(traindirec+os.sep+Name+os.sep+"train_hail_prs.csv",sep=",",index_col=0)
print(prs_train)
prs_train[['FID', 'IID']] = prs_train['subjectID'].str.split('_', expand=True)
# Drop the original 'Combined' column if it's no longer needed
prs_train = prs_train.drop(columns=['subjectID'])
prs_train.rename(columns={'PGS002724': 'SCORE'}, inplace=True)
prs_train['FID'] = prs_train['FID'].astype(str)
prs_train['IID'] = prs_train['IID'].astype(str)
prs_test = pd.read_table(traindirec+os.sep+Name+os.sep+"test_hail_prs.csv",sep=",",index_col=0)
prs_test[['FID', 'IID']] = prs_test['subjectID'].str.split('_', expand=True)
# Drop the original 'Combined' column if it's no longer needed
prs_test = prs_test.drop(columns=['subjectID'])
prs_test.rename(columns={'PGS002724': 'SCORE'}, inplace=True)
print(prs_test)
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"])
print(pheno_prs_train)
try:
#model = sm.OLS(phenotype_train["Phenotype"], sm.add_constant(pheno_prs_train.iloc[:, 2:])).fit_regularized(alpha=tempalpha, L1_wt=l1weight)
model = sm.OLS(phenotype_train["Phenotype"], sm.add_constant(pheno_prs_train.iloc[:, 2:])).fit()
except:
print("Model did not fit")
continue
train_best_predicted = model.predict(sm.add_constant(pheno_prs_train.iloc[:, 2:]))
test_best_predicted = model.predict(sm.add_constant(pheno_prs_test.iloc[:, 2:]))
from sklearn.metrics import roc_auc_score, confusion_matrix
prs_result = prs_result._append({
"clump_p1": c1_val,
"clump_r2": c2_val,
"clump_kb": c3_val,
"p_window_size": p1_val,
"p_slide_size": p2_val,
"p_LD_threshold": p3_val,
"numberofpca":p,
"tempalpha":str(tempalpha),
"l1weight":str(l1weight),
"Train_pure_prs":explained_variance_score(phenotype_train["Phenotype"],prs_train['SCORE'].values),
"Train_null_model":explained_variance_score(phenotype_train["Phenotype"],train_null_predicted),
"Train_best_model":explained_variance_score(phenotype_train["Phenotype"],train_best_predicted),
"Test_pure_prs":explained_variance_score(phenotype_test["Phenotype"],prs_test['SCORE'].values),
"Test_null_model":explained_variance_score(phenotype_test["Phenotype"],test_null_predicted),
"Test_best_model":explained_variance_score(phenotype_test["Phenotype"],test_best_predicted),
}, ignore_index=True)
print(prs_result)
prs_result.to_csv(traindirec+os.sep+Name+os.sep+"Results.csv",index=False)
return
# ## Execute HAIL
# In[23]:
import hail as hl
import shutil
import os
# Define a global variable to store results
prs_result = pd.DataFrame()
def transform_hail_data(traindirec, newtrainfilename,p, p1_val, p2_val, p3_val, c1_val, c2_val, c3_val,Name,pvaluefile):
### First perform clumping on the file and save the clumpled file.
perform_clumping_and_pruning_on_individual_data(traindirec, newtrainfilename,p, p1_val, p2_val, p3_val, c1_val, c2_val, c3_val,Name,pvaluefile)
#newtrainfilename = newtrainfilename+".clumped.pruned"
#testfilename = testfilename+".clumped.pruned"
#clupmedfile = traindirec+os.sep+newtrainfilename+".clump"
#prunedfile = traindirec+os.sep+newtrainfilename+".clumped.pruned"
# Also extract the PCA at this point for both test and training data.
calculate_pca_for_traindata_testdata_for_clumped_pruned_snps(traindirec, newtrainfilename,p)
# Delete the files generated in the previous iteration
# Loop through each chromosome and delete the corresponding files
import time
def remove_path(path):
try:
if os.path.isdir(path):
shutil.rmtree(path) # Remove directory
print(f'Deleted directory: {path}')
else:
os.remove(path) # Remove file
print(f'Deleted file: {path}')
except OSError as e:
print(f'Error deleting {path}: {e}')
print('Retrying...')
# Loop through each chromosome and delete the corresponding files and directories
for chromosome in range(1, 23):
train_path = os.path.join(traindirec, f'hail.train.{chromosome}.mt')
test_path = os.path.join(traindirec, f'hail.test.{chromosome}.mt')
# Delete train path if it exists
if os.path.exists(train_path):
remove_path(train_path)
pass
# Delete test path if it exists
if os.path.exists(test_path):
remove_path(test_path)
pass
#"""
# Here we will perform processing on the genotype data and convert it to specific format
# as required by HAIL.
# Read the genotype data
# Convert it to VCF
# Use beagle to convert the data to beagle format
# Convert the beagle format to Hail format.
for chromosome in range(1, 23):
# Plink command to split by chromosome
plink_command = [
"./plink",
"--bfile", traindirec+os.sep+newtrainfilename+".clumped.pruned",
"--chr", str(chromosome),
"--make-bed",
"--out", traindirec+os.sep+newtrainfilename+".clumped.pruned."+str(chromosome),
]
try:
subprocess.run(plink_command, check=True)
except:
pass
# Convert chromosomes to VCF format.
plink_command = [
"./plink",
"--bfile", traindirec+os.sep+newtrainfilename+".clumped.pruned."+str(chromosome),
"--chr", str(chromosome),
"--recode","vcf",
"--out", traindirec+os.sep+"hail.train."+str(chromosome),
]
try:
subprocess.run(plink_command)
except:
pass
# Run beagle and convert the data to beagle format.
#A “DR2” subfield with the estimated squared correlation between the estimated allele
#dose and the true allele dose
#• An “AF” subfield with the estimated alternate allele frequencies in the target samples
#• The “IMP” flag if the marker is imputed
beagle_command = [
"java",
"-Xmx50g",
"-jar", "beagle",
#"gp=true",
#"impute=false",
#"burnin=1",
#"window=100",
"gt="+traindirec+os.sep+"hail.train."+str(chromosome)+".vcf",
"ref="+"ALL.chr"+str(chromosome)+".phase3_shapeit2_mvncall_integrated_v5b.20130502.genotypes.vcf.gz",
"map="+"plink.chr"+str(chromosome)+".GRCh37.map",
"out="+traindirec+os.sep+"beagle.hail.train."+str(chromosome)
]
# Execute the command
try:
subprocess.run(beagle_command)
print(" ".join(beagle_command))
except:
pass
# Convert beagle format to HAIL format.
try:
hl.import_vcf(traindirec+os.sep+"beagle.hail.train."+str(chromosome)+".vcf.gz", force_bgz=True).write(traindirec+os.sep+"hail.train."+str(chromosome)+".mt", overwrite=True)
except:
pass
# Read the genotype data
mt = ""
filecount = 0
for chromosome in range(1, 23):
file = os.path.join(traindirec, f"hail.train.{chromosome}.mt")
if os.path.exists(file): # Check if the file exists
if filecount == 0:
mt = hl.read_matrix_table(file)
print(mt.rows().show(5))
print(chromosome, file, mt.count(), mt.count())
filecount += 1 # Increment filecount after the first file is processed
else:
tmpmt = hl.read_matrix_table(file)
mt = mt.union_rows(tmpmt)
print(chromosome, file, tmpmt.count(), mt.count())
else:
print("File does not exist:", file)
print(mt.count())
mt.write(traindirec+os.sep+'HAILTRAIN.mt', overwrite=True)
mt = hl.read_matrix_table(traindirec+os.sep+'HAILTRAIN.mt')
print(mt.rows().show(5))
mt = mt.annotate_rows(variantID = (hl.str(mt.locus.contig) + ":" + hl.str(mt.locus.position)) )
# We skipped the cleaning process as the data is already clean.
#print(mt.rows().show(5))
#mt1 = mt.filter_rows(hl.len(mt.info.DR2) == 1)
#mtnot1 = mt.filter_rows(hl.len(mt.info.DR2) > 1)
#mt1_filt = mt1.filter_rows(mt1.info.DR2.first()>=0.3)
#print(mt1_filt.rows().show(5))
model_PGS002724 = hl.import_table(filedirec+os.sep+"Hail.txt", impute=True, force=True, comment='#')
model_PGS002724 = model_PGS002724.annotate(
variantID = hl.str(model_PGS002724.chr_name) + ":" + hl.str(model_PGS002724.chr_position)
)
model_PGS002724 = model_PGS002724.key_by('variantID')
mt_match_PGS002724 = mt.annotate_rows(**model_PGS002724[mt.variantID])
mt_match_PGS002724 = mt_match_PGS002724.filter_rows(hl.is_defined(mt_match_PGS002724.effect_weight))
flip_PGS002724 = hl.case().when(
(mt_match_PGS002724.effect_allele == mt_match_PGS002724.alleles[0])
& (mt_match_PGS002724.other_allele == mt_match_PGS002724.alleles[1]), True ).when(
(mt_match_PGS002724.effect_allele == mt_match_PGS002724.alleles[1])
& (mt_match_PGS002724.other_allele == mt_match_PGS002724.alleles[0]), False ).or_missing()
mt_match_PGS002724 = mt_match_PGS002724.annotate_rows(flip=flip_PGS002724)
prs_PGS002724 = hl.agg.sum(hl.float64(mt_match_PGS002724.effect_weight) *
hl.if_else( mt_match_PGS002724.flip,
2 - mt_match_PGS002724.DS.first(),
mt_match_PGS002724.DS.first()))
mt_match_PGS002724 = mt_match_PGS002724.annotate_cols(prs=prs_PGS002724)
mt_match_PGS002724.cols().export(traindirec+os.sep+Name+os.sep+'train_PRS.txt')
prs_PGS002724 = hl.import_table(traindirec+os.sep+Name+os.sep+'train_PRS.txt', impute=True, force=True)
prs_PGS002724 = prs_PGS002724.key_by('s')
prs_merge = prs_PGS002724.rename({'s':'subjectID', 'prs':'PGS002724'})
prs_merge_pandas = prs_merge.to_pandas()
print(prs_merge_pandas.head())
prs_merge_pandas.to_csv(traindirec+os.sep+Name+os.sep+"train_hail_prs.csv")
# Save the data.
prs_merge_pandas = pd.read_csv(traindirec+os.sep+Name+os.sep+"train_hail_prs.csv",index_col=0)
print(prs_merge_pandas.head())
#"""
#"""
# Repeat the process for test dataset.
# testfilename
for chromosome in range(1, 23):
# Plink command to split by chromosome
plink_command = [
"./plink",
"--bfile", traindirec+os.sep+testfilename+".clumped.pruned",
"--chr", str(chromosome),
"--make-bed",
"--out", traindirec+os.sep+testfilename+".clumped.pruned."+str(chromosome),
]
try:
subprocess.run(plink_command)
except:
pass
plink_command = [
"./plink",
"--bfile",traindirec+os.sep+testfilename+".clumped.pruned."+str(chromosome),
"--chr", str(chromosome),
"--recode","vcf",
"--out", traindirec+os.sep+"hail.test."+str(chromosome),
]
try:
subprocess.run(plink_command, check=True)
except:
pass
beagle_command = [
"java",
"-Xmx50g",
"-jar", "beagle",
#"gp=true",
#"burnin=1",
#"window=100",
"gt="+traindirec+os.sep+"hail.test."+str(chromosome)+".vcf",
"ref="+"ALL.chr"+str(chromosome)+".phase3_shapeit2_mvncall_integrated_v5b.20130502.genotypes.vcf.gz",
"map="+"plink.chr"+str(chromosome)+".GRCh37.map",
"out="+traindirec+os.sep+"beagle.hail.test."+str(chromosome)
]
# Execute the command
try:
subprocess.run(beagle_command)
print(" ".join(beagle_command))
except:
pass
#raise
try:
hl.import_vcf(traindirec+os.sep+"beagle.hail.test."+str(chromosome)+".vcf.gz", force_bgz=True).write(traindirec+os.sep+"hail.test."+str(chromosome)+".mt", overwrite=True)
#raise
except:
pass
mt = ""
filecount = 0
for chromosome in range(1, 23):
file = os.path.join(traindirec, f"hail.test.{chromosome}.mt")
if os.path.exists(file): # Check if the file exists
if filecount == 0:
mt = hl.read_matrix_table(file)
print(mt.rows().show(5))
print(chromosome, file, mt.count(), mt.count())
filecount += 1 # Increment filecount after the first file is processed
else:
tmpmt = hl.read_matrix_table(file)
mt = mt.union_rows(tmpmt)
print(chromosome, file, tmpmt.count(), mt.count())
else:
print("File does not exist:", file)
print(mt.count())
mt.write(traindirec+os.sep+'HAILTEST.mt', overwrite=True)
#"""
#convert_data_in_hail_format()
#"""