forked from choishingwan/PRSice
-
Notifications
You must be signed in to change notification settings - Fork 0
/
PRSice.R
executable file
·2629 lines (2478 loc) · 97.7 KB
/
PRSice.R
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 Rscript
#
# Environment stuff: This will allow us to locate the cpp file correctly
#
# For window users, the reason why PRSice doesn't work with window is due to
# area flagged with WINDOW PEOPLE. If you can go around that, then you can
# make PRSice work (though I have not debug PRSice executable in window)
# Remove annoying messages ------------------------------------------------
#options(error = quote({dump.frames(to.file=TRUE); q()}))
In_Regression <-
DEC <-
Coef <-
CI.L <-
CI.U <-
Group <-
Threshold <-
R2 <-
print.p <-
R <-
P <-
value <-
Phenotype <- Set <- PRS.R2 <- LCI <- UCI <- quant.ref <- NULL
r.version <- "2.3.3"
# Help Messages --------------------------------------
help_message <-
"usage: Rscript PRSice.R [options] <-b base_file> <-t target_file> <--prsice prsice_location>\n
\nRequired:\n
--prsice Location of the PRSice binary\n
--dir Location to install ggplot. Only require if ggplot\n
is not installed\n
\nBase File:\n
--base-info Base INFO score filtering. Format should be\n
<Column name>:<Threshold>. SNPs with info \n
score less than <Threshold> will be ignored\n
Column name default: INFO\n
Threshold default: 0.9\n
--base-maf Base MAF filtering. Format should be\n
<Column name>:<Threshold>. SNPs with maf\n
less than <Threshold> will be ignored. An\n
additional column can also be added (e.g.\n
also filter MAF for cases), using the\n
following format:\n
<Column name>:<Threshold>,<Column name>:<Threshold>\n
--beta Whether the test statistic is in the form of \n
BETA or OR. If set, test statistic is assume\n
to be in the form of BETA. Mutually exclusive\n
from --or \n
--bp Column header containing the SNP coordinate\n
Default: BP\n
--chr Column header containing the chromosome\n
Default: CHR\n
--index If set, assume the INDEX instead of NAME for\n
the corresponding columns are provided. Index\n
should be 0-based (start counting from 0)\n
--no-default Remove all default options. If set, PRSice\n
will not set any default column name and you\n
must manually provide all required columns\n
(--snp, --stat, --A1, --pvalue)\n
--or Whether the test statistic is in the form of \n
BETA or OR. If set, test statistic is assume\n
to be in the form of OR. Mutually exclusive \n
from --beta \n
--pvalue | -p Column header containing the p-value\n
Default: P\n
--snp Column header containing the SNP ID\n
Default: SNP\n
--stat Column header containing the summary statistic\n
If --beta is set, default as BETA. Otherwise,\n
will search for OR or BETA from the header\n
of the base file\n
\nTarget File:\n
--binary-target Indicate whether the target phenotype\n
is binary or not. Either T or F should be\n
provided where T represent a binary phenotype.\n
For multiple phenotypes, the input should be\n
separated by comma without space. \n
Default: T if --beta and F if --beta is not\n
--info Filter SNPs based on info score. Only used\n
for imputed target\n
--keep File containing the sample(s) to be extracted from\n
the target file. First column should be FID and\n
the second column should be IID. If --ignore-fid is\n
set, first column should be IID\n
Mutually exclusive from --remove\n
--maf Filter SNPs based on minor allele frequency (MAF)\n
--nonfounders Keep the nonfounders in the analysis\n
Note: They will still be excluded from LD calculation\n
--pheno | -f Phenotype file containing the phenotype(s).\n
First column must be FID of the samples and\n
the second column must be IID of the samples.\n
When --ignore-fid is set, first column must\n
be the IID of the samples.\n
Must contain a header if --pheno-col is\n
specified\n
--pheno-col | -F Headers of phenotypes to be included from the\n
phenotype file\n
--prevalence | -k Prevalence of all binary trait. If provided\n
will adjust the ascertainment bias of the R2.\n
Note that when multiple binary trait is found,\n
prevalence information must be provided for\n
all of them\n
--remove File containing the sample(s) to be removed from\n
the target file. First column should be FID and\n
the second column should be IID. If --ignore-fid is\n
set, first column should be IID\n
Mutually exclusive from --keep\n
--target | -t Target genotype file. Currently support\n
both BGEN and binary PLINK format. For \n
multiple chromosome input, simply substitute\n
the chromosome number with #. PRSice will\n
automatically replace # with 1-22\n
For binary plink format, you can also specify\n
a seperate fam file by <prefix>,<fam file>\n
--target-list File containing prefix of target genotype\n
files. Similar to --target but allow more \n
flexibility. Do not support external fam file\n
at the moment\n
--type File type of the target file. Support bed \n
(binary plink) and bgen format. Default: bed\n
\nDosage:\n
--allow-inter Allow the generate of intermediate file. This will\n
speed up PRSice when using dosage data as clumping\n
reference and for hard coding PRS calculation\n
--dose-thres Translate any SNPs with highest genotype probability\n
less than this threshold to missing call\n
--hard-thres A hardcall is saved when the distance to the nearest\n
hardcall is less than the hardcall threshold.\n
Otherwise a missing code is saved\n
Default is: 0.1\n
--hard Use hard coding instead of dosage for PRS construction.\n
Default is to use dosage instead of hard coding\n
\nClumping:\n
--clump-kb The distance for clumping in kb\n
Default: 250kb (1mb for PRSet)\n
--clump-r2 The R2 threshold for clumping\n
Default: 0.1\n
--clump-p The p-value threshold use for clumping.\n
Default: 1\n
--ld | -L LD reference file. Use for LD calculation. If not\n
provided, will use the post-filtered target genotype\n
for LD calculation. Support multiple chromosome input\n
Please see --target for more information\n
--ld-dose-thres Translate any SNPs with highest genotype probability\n
less than this threshold to missing call\n
--ld-geno Filter SNPs based on genotype missingness\n
--ld-hard-thres A hardcall is saved when the distance to the nearest\n
hardcall is less than the hardcall threshold.\n
Otherwise a missing code is saved\n
Default is: 0.1\n
--ld-info Filter SNPs based on info score. Only used\n
for imputed LD reference\n
--ld-keep File containing the sample(s) to be extracted from\n
the LD reference file. First column should be FID and\n
the second column should be IID. If --ignore-fid is\n
set, first column should be IID\n
Mutually exclusive from --ld-remove\n
No effect if --ld was not provided\n
--ld-list File containing prefix of LD reference files.\n
Similar to --ld but allow more \n
flexibility. Do not support external fam file\n
at the moment\n
--ld-maf Filter SNPs based on minor allele frequency\n
--ld-remove File containing the sample(s) to be removed from\n
the LD reference file. First column should be FID and\n
the second column should be IID. If --ignore-fid is\n
set, first column should be IID\n
Mutually exclusive from --ld-keep\n
--ld-type File type of the LD file. Support bed (binary plink)\n
and bgen format. Default: bed\n
--no-clump Stop PRSice from performing clumping\n
--proxy Proxy threshold for index SNP to be considered\n
as part of the region represented by the clumped\n
SNP(s). e.g. --proxy 0.8 means the index SNP will\n
represent region of any clumped SNP(s) that has a\n
R2>=0.8 even if the index SNP does not physically\n
locate within the region\n
\nCovariate:\n
--cov | -C Covariate file. First column should be FID and \n
the second column should be IID. If --ignore-fid\n
is set, first column should be IID\n
--cov-col | -c Header of covariates. If not provided, will use\n
all variables in the covariate file. By adding\n
@ in front of the string, any numbers within [\n
and ] will be parsed. E.g. @PC[1-3] will be\n
read as PC1,PC2,PC3. Discontinuous input are also\n
supported: @cov[1.3-5] will be parsed as \n
cov1,cov3,cov4,cov5\n
--cov-factor Header of categorical covariate(s). Dummy variable\n
will be automatically generated. Any items in\n
--cov-factor must also be found in --cov-col\n
Also accept continuous input (start with @).\n
\nP-value Thresholding:\n
--bar-levels Level of barchart to be plotted. When --fastscore\n
is set, PRSice will only calculate the PRS for \n
threshold within the bar level. Levels should be\n
comma separated without space\n
--fastscore Only calculate threshold stated in --bar-levels\n
--no-full By default, PRSice will include the full model, \n
i.e. p-value threshold = 1. Setting this flag will\n
disable that behaviour\n
--interval | -i The step size of the threshold. Default: 0.00005\n
--lower | -l The starting p-value threshold. Default: 5e-8\n
--model Genetic model use for regression. The genetic\n
encoding is based on the base data where the\n
encoding represent number of the coding allele\n
Available models include:\n
add - Additive model, code as 0/1/2 (default)\n
dom - Dominant model, code as 0/1/1\n
rec - Recessive model, code as 0/0/1\n
het - Heterozygous only model, code as 0/1/0\n
--missing Method to handle missing genotypes. By default, \n
final scores are averages of valid per-allele \n
scores with missing genotypes contribute an amount\n
proportional to imputed allele frequency. To throw\n
out missing observations instead (decreasing the\n
denominator in the final average when this happens),\n
use the 'SET_ZERO' modifier. Alternatively,\n
you can use the 'CENTER' modifier to shift all scores\n
to mean zero. \n
--no-regress Do not perform the regression analysis and simply\n
output all PRS.\n
--score Method to calculate the polygenic score.\n
Available methods include:\n
avg - Take the average effect size (default)\n
std - Standardize the effect size \n
con-std - Standardize the effect size using mean \n
and sd derived from control samples\n
sum - Direct summation of the effect size \n
--upper | -u The final p-value threshold. Default: 0.5\n
\nPRSet:\n
--background String to indicate a background file. This string\n
should have the format of Name:Type where type can be\n
bed - 0-based range with 3 column. Chr Start End\n
range - 1-based range with 3 column. Chr Start End\n
gene - A file contain a column of gene name\n
--bed | -B Bed file containing the selected regions.\n
Name of bed file will be used as the region\n
identifier. WARNING: Bed file is 0-based\n
--feature Feature(s) to be included from the gtf file.\n
Default: exon,CDS,gene,protein_coding.\n
--full-back Use the whole genome as background for competitive\n
p-value calculation\n
--gtf | -g GTF file containing gene boundaries. Required\n
when --msigdb is used\n
--msigdb | -m MSIGDB file containing the pathway information.\n
Require the gtf file\n
--snp-set Provide a SNP set file containing the snp set(s).\n
Two different file format is allowed:\n
SNP list format - A file containing a single\n
column of SNP ID. Name of the\n
set will be the file name or\n
can be provided using \n
--snp-set File:Name\n
MSigDB format - Each row represent a single SNP \n
set with the first column \n
containing the name of the SNP\n
set.\n
--wind-3 Add N base(s) to the 3' region of each feature(s) \n
--wind-5 Add N base(s) to the 5' region of each feature(s) \n
\nPlotting:\n
--bar-col-high Colour of the most predicting threshold\n
Default: firebrick\n
--bar-col-lower Colour of the poorest predicting threshold\n
Default: dodgerblue\n
--bar-col-p Change the colour of bar to p-value threshold\n
instead of the association with phenotype\n
--bar-palatte Colour palatte to be used for bar plotting when\n
--bar_col_p is set. Default: YlOrRd\n
--device Select different plotting devices. You can choose\n
any plotting devices supported by base R.\n
Default: png\n
--multi-plot Plot the top N phenotype / gene set in a\n
summary plot\n
--plot When set, will only perform plotting.\n
--plot-set Define the gene set to be plot. Default: Base\n
--quantile | -q Number of quantiles to plot. No quantile plot\n
will be generated when this is not provided.\n
--quant-break Quantile groupings for plotting the strata plot\n
--quant-extract | -e File containing sample ID to be plot on a separated\n
quantile e.g. extra quantile containing only \n
schizophrenia samples. Must contain IID. Should\n
contain FID if --ignore-fid isn't set.\n
--quant-ref Reference quantile for quantile plot\n
--scatter-r2 y-axis of the high resolution scatter plot should be R2\n
\nMisc:\n
--all-score Output PRS for ALL threshold. WARNING: This\n
will generate a huge file\n
--chr-id Try to construct an RS ID for SNP based on its\n
chromosome, coordinate, effective allele and \n
non-effective allele.\n
e.g. c:L-aBd is translated to: \n
<chr>:<coordinate>-<effective><noneffective>d\n
This is always true for target file, whereas for\n
base file, this is only used if the RS ID \n
wasn't provided\n
--exclude File contains SNPs to be excluded from the\n
analysis\n
--extract File contains SNPs to be included in the \n
analysis\n
--id-delim This parameter causes sample IDs to be parsed as\n
<FID><delimiter><IID>; the default delimiter\n
is '_'. \n
--ignore-fid Ignore FID for all input. When this is set,\n
first column of all file will be assume to\n
be IID instead of FID\n
--keep-ambig Keep ambiguous SNPs. Only use this option\n
if you are certain that the base and target\n
has the same A1 and A2 alleles\n
--logit-perm When performing permutation, still use logistic\n
regression instead of linear regression. This\n
will substantially slow down PRSice\n
--memory Maximum memory usage allowed (in Mb). PRSice will try\n
its best to honor this setting\n
--non-cumulate Calculate non-cumulative PRS. PRS will be reset\n
to 0 for each new P-value threshold instead of\n
adding up\n
--out | -o Prefix for all file output\n
--perm Number of permutation to perform. This swill\n
generate the empirical p-value. Recommend to\n
use value larger than 10,000\n
--print-snp Print all SNPs that remains in the analysis \n
after clumping is performed. For PRSet, Y \n
indicate the SNPs falls within the gene set \n
of interest and N otherwise. If only PRSice \n
is performed, a single \"gene set\" called \n
\"Base\" will be presented with all entries\n
marked as Y\n
--seed | -s Seed used for permutation. If not provided,\n
system time will be used as seed. When same\n
seed and same input is provided, same result\n
can be generated\n
--thread | -n Number of thread use\n
--use-ref-maf When specified, missingness imputation will be\n
performed based on the reference samples\n
--ultra Ultra aggressive memory usage. When this is enabled\n
PRSice and PRSet will try to load all genotypes into\n
memory after clumping is performed. This should\n
drastically speed up PRSice and PRSet at the expense\n
of higher memory consumption.\n
Has no effect for dosage score\n
--x-range Range of SNPs to be excluded from the whole\n
analysis. It can either be a single bed file\n
or a comma seperated list of range. Range must\n
be in the format of chr:start-end or chr:coordinate\n
--help | -h Display this help message\n"
# Library handling --------------------------------------------------------
if (!exists('startsWith', mode = 'function')) {
startsWith <- function(x, prefix) {
return(substring(x, 1, nchar(prefix)) == prefix)
}
}
libraries <-
c("ggplot2",
"data.table",
"optparse",
"methods",
"tools",
"grDevices",
"RColorBrewer")
found.library.dir <- FALSE
argv <- commandArgs(trailingOnly = TRUE)
dir.arg.idx <- grep("--dir",argv)
no.install <- length(grep("--no-install", argv)) > 0
if (length(dir.arg.idx) != 0) {
dir.arg.idx <- dir.arg.idx + 1
found.library.dir <- TRUE
}
# INSTALL_PACKAGE: Functions for automatically install all required packages
InstalledPackage <- function(package) {
available <- suppressMessages(suppressWarnings(
sapply(
package,
require,
quietly = TRUE,
character.only = TRUE,
warn.conflicts = FALSE
)
))
missing <- package[!available]
if (length(missing) > 0)
return(FALSE)
return(TRUE)
}
CRANChoosen <- function()
{
return(getOption("repos")["CRAN"] != "@CRAN@")
}
UsePackage <- function(package, dir, no.install)
{
if (!InstalledPackage(package))
{
dir.create(file.path(dir, "lib"), showWarnings = FALSE)
.libPaths(c(.libPaths(), paste(dir, "/lib", sep = "")))
if (!InstalledPackage(package) & !no.install) {
if (is.na(dir)) {
writeLines("WARNING: dir not provided, cannot install the required packages")
return(FALSE)
} else{
writeLines(paste(
"Trying to install ",
package,
" in ",
dir,
"/lib",
sep = ""
))
}
suppressMessages(suppressWarnings(
install.packages(
package,
lib = paste(dir, "/lib", sep = ""),
repos = "http://cran.rstudio.com/",
quiet = T
)
))
}
if (!InstalledPackage(package))
return(FALSE)
}
return(TRUE)
}
use.data.table <- T
use.ggplot <- T
for (library in libraries)
{
package.directory <- "."
if (found.library.dir) {
package.directory <- argv[dir.arg.idx]
}
if (!UsePackage(library, package.directory, no.install))
{
if (library == "data.table") {
use.data.table <- F
writeLines("Cannot install data.table, will fall back and use read.table instead")
writeLines("Note: It will be slower when reading large files")
} else if (library == "ggplot2") {
use.ggplot <- F
writeLines("Cannot install ggplot2, will fall back and native plotting devices")
writeLines("Note: The legends will be uglier")
} else{
stop("Error: ", library, " cannot be load nor install!")
}
}
}
# Command line arguments --------------------------------------------------
# We don't type the help message here. Will just directly use the usage information from c++
# See the Help Messages section for more information
option_list <- list(
# Base file
make_option(c("--A1"), type = "character"),
make_option(c("--A2"), type = "character"),
make_option(c("--a1"), type = "character"),
make_option(c("--a2"), type = "character"),
make_option(c("-b", "--base"), type = "character"),
make_option(c("--base-info"), type = "character", dest = "base_info"),
make_option(c("--base-maf"), type = "character", dest = "base_maf"),
make_option(c("--beta"), action = "store_true"),
make_option(c("--bp"), type = "character"),
make_option(c("--chr"), type = "character"),
make_option(c("--index"), action = "store_true"),
make_option(c("--no-default"), action = "store_true", dest = "no_default"),
make_option(c("--or"), action = "store_true"),
make_option(c("-p", "--pvalue"), type = "character"),
make_option(c("--snp"), type = "character"),
make_option(c("--stat"), type = "character"),
# Target file
make_option(c("--binary-target"), type = "character", dest = "binary_target"),
make_option(c("--geno"), type = "numeric"),
make_option(c("--info"), type = "numeric"),
make_option(c("--keep"), type = "character"),
make_option(c("--maf"), type = "numeric"),
make_option(c("--nonfounders"), action = "store_true", dest = "nonfounders"),
make_option(c("--pheno-col"), type = "character", dest = "pheno_col"),
make_option(c("--pheno-file"), type = "character", dest = "pheno_file"),
make_option(c("-f", "--pheno"), type = "character", dest = "pheno_file"),
make_option(c("-k", "--prevalence"), type = "character"),
make_option(c("--remove"), type = "character"),
make_option(c("-t", "--target"), type = "character"),
make_option(c("--target-list"), type = "character", dest = "target_list"),
make_option(c("--type"), type = "character"),
# Dosage
make_option(c("--allow-inter"), action = "store_true", dest = "allow_inter"),
make_option(c("--hard-thres"), type = "numeric", dest = "hard_thres"),
make_option(c("--dose-thres"), type = "numeric", dest = "dose_thres"),
make_option(c("--hard"), action = "store_true"),
# Clumping
make_option(c("--clump-kb"), type = "character", dest = "clump_kb"),
make_option(c("--clump-r2"), type = "numeric", dest = "clump_r2"),
make_option(c("--clump-p"), type = "numeric", dest = "clump_p"),
make_option(c("-L", "--ld"), type = "character"),
make_option(c("--ld-list"), type = "character", dest = "ld_list"),
make_option(c("--ld-geno"), type = "numeric", dest = "ld_geno"),
make_option(c("--ld-info"), type = "numeric", dest = "ld_info"),
make_option(c("--ld-hard-thres"), type = "numeric", dest = "ld_hard_thres"),
make_option(c("--ld-dose-thres"), type = "numeric", dest = "ld_dose_thres"),
make_option(c("--ld-keep"), type = "character", dest = "ld_keep"),
make_option(c("--ld-maf"), type = "numeric", dest = "ld_maf"),
make_option(c("--ld-remove"), type = "character", dest = "ld_remove"),
make_option(c("--ld-type"), type = "character", dest = "ld_type"),
make_option(c("--no-clump"), action = "store_true", dest = "no_clump"),
make_option(c("--proxy"), type = "numeric"),
# Covariates
make_option(c("-c", "--cov-col"), type = "character", dest = "cov_col"),
make_option(c("--cov-file"), type = "character", dest = "cov_file"),
make_option(c("-C", "--cov"), type = "character", dest = "cov_file"),
make_option(c("--cov-factor"), type = "character", dest = "cov_factor"),
# P-thresholding
make_option(
c("--bar-levels"),
type = "character",
dest = "bar_levels"
),
make_option(c("--fastscore"), action = "store_true"),
make_option(c("--no-full"), action = "store_true"),
make_option(c("-i", "--interval"), type = "numeric"),
make_option(c("-l", "--lower"), type = "numeric"),
make_option(c("--model"), type = "character"),
make_option(c("--missing"), type = "character"),
make_option(c("--no-regress"), action = "store_true", dest = "no_regress"),
make_option(c("--score"), type = "character"),
make_option(c("-u", "--upper"), type = "numeric"),
# PRSet
make_option(c("-B", "--bed"), type = "character"),
make_option(c("--background"), type = "character"),
make_option(c("--feature"), type = "character"),
make_option(c("--full-back"), action = "store_true", dest = "full_back"),
make_option(c("-g", "--gtf"), type = "character"),
make_option(c("-m", "--msigdb"), type = "character"),
make_option(c("--set-perm"), type = "numeric", dest = "set_perm"),
make_option(c("--wind-5"), type = "character", dest = "wind_5"),
make_option(c("--wind-3"), type = "character", dest = "wind_3"),
make_option(c("--snp-set"), type = "character", dest = "snp_set"),
# Misc
make_option(c("--all-score"), action = "store_true", dest = "all_score"),
make_option(c("--ultra"), action = "store_true"),
make_option(c("--chr-id"), type = "character", dest = "chr_id"),
make_option(c("--exclude"), type = "character"),
make_option(c("--extract"), type = "character"),
make_option(c("--enable-mmap"), action = "store_true", dest = "enable_mmap"),
make_option(c("--ignore-fid"), action = "store_true", dest = "ignore_fid"),
make_option(c("--id-delim"), type = "character"),
make_option(c("--logit-perm"), action = "store_true", dest = "logit_perm"),
make_option(c("--keep-ambig"), action = "store_true", dest = "keep_ambig"),
make_option(c("--flip-ambig"), action = "store_true", dest = "flip_ambig"),
make_option(c("--memory"), type = "character", dest="memory"),
make_option(c("-o", "--out"), type = "character", default = "PRSice"),
make_option(c("--perm"), type = "numeric"),
make_option(c("-s", "--seed"), type = "numeric"),
make_option(c("--print-snp"), action = "store_true", dest = "print_snp"),
make_option(c("--non-cumulate"), action = "store_true", dest = "non_cumulate"),
make_option(c("-n", "--thread"), type = "numeric"),
make_option(c( "--num-auto"), type = "numeric"),
make_option(c("--use-ref-maf"), action = "store_true", dest = "use_ref_maf"),
make_option(c("--x-range"), type = "character", dest = "x_range"),
#R Specified options
make_option(c("--plot"), action = "store_true"),
make_option(c("--quantile", "-q"), type = "numeric"),
make_option(c("--quant-break"), type = "character", dest = "quant_break"),
make_option(c("--multi-plot"), type = "numeric", dest = "multi_plot"),
make_option(c("--plot-set"),
type = "character",
dest = "plot_set",
default = "Base"),
make_option(c("--quant-pheno"), action = "store_true", dest = "quant_pheno"),
make_option(c("--quant-extract", "-e"), type = "character", dest = "quant_extract"),
make_option("--quant-ref", type = "numeric", dest = "quant_ref"),
make_option("--scatter-r2",
action = "store_true",
default = F,
dest = "scatter_r2"),
make_option("--bar-col-p",
action = "store_true",
default = F,
dest = "bar_col_p"),
make_option("--bar-col-low",
type = "character",
default = "dodgerblue",
dest = "bar_col_low"),
make_option("--bar-col-high",
type = "character",
default = "firebrick",
dest = "bar_col_high"),
make_option("--bar-palatte",
type = "character",
default = "YlOrRd",
dest = "bar_palatte"),
make_option("--prsice", type = "character"),
make_option("--device", type = "character", default = "png"),
make_option("--dir", type = "character")
)
# We want to know if user used --help, if they do, we will print the help message ourselves
capture <- commandArgs(trailingOnly = TRUE)
help <- (sum(c("--help", "-h") %in% capture) >= 1)
has_c <- (sum(c("--prsice") %in% capture) >= 1)
if (help) {
cat(help_message)
quit()
}
# If help is not invoked, we can start processing the input
argv <- parse_args(OptionParser(option_list = option_list))
# Exclude the non-C++ parameters
not_cpp <- c(
"help",
"plot",
"quantile",
"quant-extract",
"intermediate",
"quant-ref",
"quant-pheno",
"quant-break",
"scatter-r2",
"bar-col-p",
"bar-col-low",
"bar-col-high",
"bar-palatte",
"device",
"prsice",
"multi-plot",
"plot-set",
"dir",
"no-install"
)
# For backward compatibility. We want to remove the --cov-header in the future
if (is.null(argv$cov_col) && !is.null(argv$cov_header))
{
argv$cov_col = argv$cov_header
}
# Check help messages --------------------------------------------------
get_os <- function() {
sysinf <- Sys.info()
if (!is.null(sysinf)) {
os <- sysinf['sysname']
if (os == 'Darwin')
os <- "osx"
} else {
## mystery machine
os <- .Platform$OS.type
if (grepl("^darwin", R.version$os))
os <- "osx"
if (grepl("linux-gnu", R.version$os))
os <- "linux"
}
tolower(os)
}
# CALL_PRSICE: Call the cpp PRSice if required
# To ensure the excutable is set correctly
# For window, we might not be able to start an executable by simply adding ./
# therefore Window people will need to be careful with their parameter input
# Function to check if the argument was used
provided <- function(name, argv) {
return(name %in% names(argv))
}
os <- get_os()
if (provided("prsice", argv)) {
if (!startsWith(argv$prsice, "/") &&
!startsWith(argv$prsice, ".") && os != "windows") {
argv$prsice = paste("./", argv$prsice, sep = "")
}
}
# Running PRSice ----------------------------------------------------------
# We don't bother to check if the input is correct, the parameter should be checked by the c++ program
add_command <- function(input) {
if (length(input) == 1) {
if (is.na(input)) {
return(NA)
} else{
return(input)
}
} else{
return(paste(input, collapse = ","))
}
}
command <- ""
argv_c <- argv
names(argv_c) <- gsub("_", "-", names(argv))
flags <-
c(
"all-score",
"allow-inter",
"beta",
"fastscore",
"ignore-fid",
"index",
"keep-ambig",
"flip-ambig",
"logit-perm",
"no-clump",
"no-default",
"no-full",
"no-mt",
"no-regress",
"no-x",
"no-xy",
"no-y",
"non-cumulate",
"or",
"print-snp",
"use-ref-maf",
"ultra"
)
# Skip PRSice core function if only plotting is requirec
if (!provided("plot", argv)) {
for (i in names(argv_c)) {
# only need special processing for flags and specific inputs
if (i == "id-delim") {
if (!is.na(i)) {
command = paste(command, " --", i, " \"", argv_c[[i]], "\"", sep = "")
}
} else if (i %in% flags) {
if (argv_c[[i]])
command = paste(command, " --", i, sep = "")
} else if (i %in% not_cpp) {
# ignore
} else{
temp = add_command(argv_c[[i]])
if (!is.na(temp)) {
command = paste(command, " --", i, " ", temp, sep = "")
}
}
}
if (nchar(command) == 0) {
cat(help_message)
quit()
}
if (provided("prsice", argv_c)) {
ret <- system2(argv_c$prsice, command)
if (ret != 0 || provided(help, argv)) {
stop()
}
} else{
stop("Cannot run PRSice without the PRSice binary file")
}
}
writeLines("Begin plotting");
writeLines(paste0("Current Rscript version = ",r.version))
# Helper functions --------------------------------------------------------
# allow older version of ggplot2 to work
expand_scale <- function(mult = 0, add = 0) {
stopifnot(is.numeric(mult) && is.numeric(add))
stopifnot((length(mult) %in% 1:2) && (length(add) %in% 1:2))
mult <- rep(mult, length.out = 2)
add <- rep(add, length.out = 2)
c(mult[1], add[1], mult[2], add[2])
}
max_length <- function(x) {
info <- strsplit(as.character(x), split = "\n")[[1]]
max(sapply(info, nchar))
}
str_wrap <- function(x) {
lapply(strwrap(x, width = 25, simplify = FALSE), paste, collapse = "\n")
}
shorten_label <- function(x) {
lab <-
paste(strsplit(paste(
strsplit(as.character(x), split = "\\.")[[1]], collapse = " "
), split = "_")[[1]], collapse = " ")
return(str_wrap(lab)[[1]])
}
# Quantile functions ------------------------------------------------------
get_quantile <- function(x, num.quant, quant.ref){
quant <- as.numeric(cut(x,
breaks = unique(quantile(
x, probs = seq(0, 1, 1 / num.quant)
)),
include.lowest = T))
if(is.na(quant.ref) | is.null(quant.ref)){
quant.ref <- ceiling(num.quant / 2)
}
quant <- factor(quant, levels = c(quant.ref, seq(min(quant), max(quant), 1)[-quant.ref]))
return(quant)
}
set_uneven_quant <- function(quant.cutoff, ref.cutoff, num.quant, prs, quant.index){
quant <- get_quantile(prs, num.quant, 1)
quant <- factor(quant,1:num.quant)
quant.cut <- sort(as.numeric(strsplit(quant.cutoff, split=",")[[1]]))
if((!is.null(ref.cutoff) & sum(ref.cutoff == quant.cut)==0) | num.quant < max(quant.cut)){
stop(
"Invalid quant-break. quant-break must be smaller than total number of quantiles and quant-ref must be one of the quant-break"
)
}
prev.name <- 0
ref.level <- NULL
for(i in 1:length(quant.cut)){
up.bound <- max(which(suppressWarnings(as.numeric(levels(quant))) <= quant.cut[i]))
cur.name <- levels(quant)[up.bound]
name.level <- paste0("(",prev.name, ",", cur.name, "]")
if(prev.name==0){
name.level <- paste0("[",prev.name, ",", cur.name, "]")
}
if(!is.null(ref.cutoff)) {
if (quant.cut[i] == ref.cutoff) {
ref.level <- name.level
}
}
range <- i:up.bound
levels(quant)[range] <- rep(name.level, length(range))
prev.name <- cur.name
}
if(is.null(ref.level)){
writeLines("=======================================")
writeLines("Warning: Cannot find required reference level, will use the middle level as reference")
writeLines("=======================================")
ref.level <- levels(quant)[ceiling(length(quant.cut)/2)]
}
ref.index <- which(levels(quant)==ref.level)
quant.index <- c(ref.index,c(1:length(levels(quant)))[-ref.index])
quant<- relevel(quant, ref=ref.level)
return(list(quant, quant.index))
}
# Determine Default -------------------------------------------------------
# Bar level default -------------------------------------------------------
if(!provided("bar_levels", argv)){
if(!provided("msigdb", argv) & !provided("gtf", argv) & !provided("bed", argv)) {
# Not PRSet
argv$bar_levels <- paste(0.001, 0.05, 0.1, 0.2, 0.3, 0.4, 0.5, sep=",")
if (!provided("no_full", argv)) {
argv$bar_levels <- paste(argv$bar_levels, 1, sep=",")
}
} else if (!provided("fastscore", argv) &
!provided("lower", argv) &
!provided("upper", argv) & !provided("interval", argv)) {
# This is prset, no thresholding unless user use parameters related to thresholding
argv$bar_levels <- "1"
}else{
argv$bar_levels <- paste(0.001, 0.05, 0.1, 0.2, 0.3, 0.4, 0.5, sep=",")
if (!provided("no_full", argv)) {
argv$bar_levels <- paste(argv$bar_levels, 1, sep=",")
}
}
}
# Base check --------------------------------------------------------------
# We need to check the base when both --beta, --or and --binary-target isn't provided
# as PRSice will try to determine the binary-target flag with those input
base.beta <- provided("beta", argv)
base.or <- provided("or", argv)
if(!base.beta &
!base.or &
!provided("binary_target", argv)) {
if (!provided("base", argv)) {
stop(
"Warning: Without base file, we cannot determine if the summary statistic is beta or OR, which is used to determine if the target phenotype is binary or not. Please use --binary-target to specify the correct target phenotype type."
)
}
zz <- gzfile(argv$base)
base_header <- readLines(zz, n = 1)
close(zz)
or <- length(grep("or", base_header, ignore.case = TRUE)) == 1
beta <- length(grep("beta", base_header, ignore.case = TRUE)) == 1
if (or & beta) {
stop(
"Both OR and BETA detected. Cannot determine which one should be used. Please use --beta or --binary-target"
)
}
if (beta) {
base.beta <- T
base.or <- F
} else if (or) {
base.or <- T
base.beta <- F
}
else {
stop("Do not detect either BETA or OR. Please ensure your base input is correct")
}
}
# Determine default of binary-target ----------------------------------------
get_binary_vector <- function(input){
# Assume the input is correct. If not, then user is likely using --plot
vec <- strsplit(input, split=",")[[1]]
binary.vec <- NULL
for(i in vec){
if(endsWith(toupper(i), "F") |endsWith(toupper(i), "FALSE")){
count <- as.numeric(gsub("F", "", gsub("FALSE","", i, ignore.case=T), ignore.case=T))
if(!is.na(count)){
binary.vec <- c(binary.vec, rep(F, count))
}else{
binary.vec <- c(binary.vec, F)
}
}else if(endsWith(toupper(i), "T") |endsWith(toupper(i), "TRUE")){
count <- as.numeric(gsub("T", "", gsub("TRUE","", i, ignore.case=T), ignore.case=T))
if(!is.na(count)){
binary.vec <- c(binary.vec, rep(T,count))
}else{
binary.vec <- c(binary.vec, T)
}
}
}
return(binary.vec)
}
binary.vector <- NULL
if(!provided("binary_target", argv)){
num.pheno <- 1
if(provided("pheno_col", argv)){
num.pheno <- length(strsplit(argv$pheno_col, split=",")[[1]])
}
if(base.beta){
binary.vector <- rep(F, num.pheno)
}else if(base.or){
binary.vector <- rep(T, num.pheno)
}else{
stop("Error: Fatal logic error from Sam when parsing binary target status")
}
}else{
# Try to parse binary_target into vector of TF
binary.vector <- get_binary_vector(argv$binary_target)
}
# Sanity check for binary-target
if(provided("pheno_col", argv) ){
pheno_length <- length(strsplit(argv$pheno_col, split=",")[[1]])
binary_length <- length(binary.vector)
if(pheno_length==0 & binary_length==1){
# This is ok
}else if(pheno_length!=binary_length){
stop("Error: Number of target phenotypes doesn't match information of binary target! You must indicate whether the phenotype is binary using --binary-target\n")
}
}
# Plottings ---------------------------------------------------------------
# Standard Theme for all plots
theme_sam <- NULL
if(use.ggplot){
theme_sam <- theme_classic()+theme(axis.title=element_text(face="bold", size=18),
axis.text=element_text(size=14),
legend.title=element_text(face="bold", size=18),
legend.text=element_text(size=14),
axis.text.x=element_text(angle=45, hjust=1)
)
}
# Quantile Plots----------------------------------------------------------
call_quantile <-
function(pheno.merge,
covariance,
prefix,
num_quant,
quant.index,
pheno.as.quant,
use.residual,
use.ggplot,
binary,
extract,
device,
uneven) {
if (!pheno.as.quant) {
family <- gaussian
if (binary) {
family <- binomial
}
if(!is.null(covariance)){
pheno.merge <- merge(pheno.merge, covariance)
}
independent.variables <-
c("quantile", "Pheno", colnames(covariance[, !colnames(covariance) %in% c("FID", "IID")]))
reg <-
summary(glm(Pheno ~ ., family, data = pheno.merge[, independent.variables]))
coef.quantiles <- (reg$coefficients[1:num_quant, 1])
ci <- (1.96 * reg$coefficients[1:num_quant, 2])