forked from precimed/python_convert
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathsumstats.py
2299 lines (1978 loc) · 128 KB
/
sumstats.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#!/usr/bin/env python
'''
(c) 2016-2018 Oleksandr Frei and Alexey A. Shadrin
Various utilities for GWAS summary statistics.
'''
from __future__ import print_function
import pandas as pd
import numpy as np
from scipy import stats
import scipy.io as sio
import scipy.sparse
import os
import time, sys, traceback
import argparse
import six
from sumstats_utils import *
import collections
import re
from shutil import copyfile, rmtree
import zipfile
import glob
import socket
import getpass
import subprocess
import tarfile
__version__ = '1.0.0'
MASTHEAD = "***********************************************************************\n"
MASTHEAD += "* sumstats.py: utilities for GWAS summary statistics\n"
MASTHEAD += "* Version {V}\n".format(V=__version__)
MASTHEAD += "* (C) 2016-2018 Oleksandr Frei and Alexey A. Shadrin\n"
MASTHEAD += "* Norwegian Centre for Mental Disorders Research / University of Oslo\n"
MASTHEAD += "* GNU General Public License v3\n"
MASTHEAD += "***********************************************************************\n"
def parse_args(args):
parser = argparse.ArgumentParser(description="A collection of various utilities for GWAS summary statistics.")
parent_parser = argparse.ArgumentParser(add_help=False)
parent_parser.add_argument("--log", type=str, default=None, help="filename for the log file. Default is <out>.log")
parent_parser.add_argument("--log-append", action="store_true", default=False, help="append to existing log file. Default is to erase previous log file if it exists.")
subparsers = parser.add_subparsers()
# 'csv' utility : load raw summary statistics file and convert it into a standardized format
parser_csv = subparsers.add_parser("csv", parents=[parent_parser],
help='Load raw summary statistics file and convert it into a standardized format: '
'tab-separated file with standard column names, standard chromosome labels, NA label for missing data, etc. '
'The conversion does not change the number of lines in the input files (e.g. no filtering is done on markers). '
'Unrecognized columns are removed from the summary statistics file. '
'The remaining utilities in sumstats.py work with summary statistics files in the standardized format.')
parser_csv.add_argument("--sumstats", type=str, default='-',
help="Raw input file with summary statistics. "
"Default is '-', e.i. to read from sys.stdin (input pipe).")
parser_csv.add_argument("--out", type=str, default='-',
help="File to output the result. "
"Default is '-', e.i. to write to sys.stdout (output pipe).")
parser_csv.add_argument("--force", action="store_true", default=False, help="Allow sumstats.py to overwrite output file if it exists.")
# Generate parameters from describe_cname.
# Keys in describe_cname will be used as standard columns names for the resulting csv file.
for cname in sorted(cols._asdict()):
parser_csv.add_argument("--{}".format(cname.lower()), default=None, type=str, help=describe_cname[cname])
parser_csv.add_argument("--auto", action="store_true", default=False,
help="Auto-detect column types based on a set of standard column names.")
parser_csv.add_argument("--ignore", type=str, nargs='+',
help="List of column names in the original file to ignore during auto-detection")
parser_csv.add_argument("--chunksize", default=100000, type=int,
help="Size of chunk to read the file.")
parser_csv.add_argument("--head", default=0, type=int,
help="How many header lines of the file to print out for visual inspection (0 to disable)")
parser_csv.add_argument("--preview", default=0, type=int,
help="How many chunks to output into the output (debug option to preview large files that take long time to parse)")
parser_csv.add_argument("--skip-validation", action="store_true", default=False,
help="Skip validation of the resulting csv file")
parser_csv.add_argument("--sep", default='\s+', type=str, choices=[',', ';', '\t', ' '],
help="Delimiter to use (',' ';' $' ' or $'\\t'). By default uses delim_whitespace option in pandas.read_csv.")
parser_csv.add_argument("--na-values", type=str, nargs='+',
help="Additional strings to recognize as NA/NaN.")
parser_csv.add_argument("--all-snp-info-23-and-me", default=None, type=str,
help="all_snp_info file for summary stats in 23-and-me format")
parser_csv.add_argument("--qc-23-and-me", action="store_true", default=False,
help="QC 23andMe summary stats (exclude SNPs with 'N' in 'pass' column")
parser_csv.add_argument("--n-val", default=None, type=float,
help="Sample size. If this option is not set, will try to infer the sample "
"size from the input file. If the input file contains a sample size "
"column, and this flag is set, the argument to this flag has priority.")
parser_csv.add_argument("--ncase-val", default=None, type=float,
help="Number of cases. If this option is not set, will try to infer the number "
"of cases from the input file. If the input file contains a number of cases "
"column, and this flag is set, the argument to this flag has priority.")
parser_csv.add_argument("--ncontrol-val", default=None, type=float,
help="Number of controls. If this option is not set, will try to infer the number "
"of controls from the input file. If the input file contains a number of controls "
"column, and this flag is set, the argument to this flag has priority.")
parser_csv.add_argument("--header", default=None, type=str,
help="Whitespace-delimited list of column names. "
"This could be used for input files without column names.")
parser_csv.add_argument("--keep-cols", nargs='*', default=[],
help="List of non-standard column names from --sumstats file to keep in --out file. Columns names will UPPERCASEed.")
parser_csv.add_argument("--keep-all-cols", action="store_true", default=False,
help="Keep all non-standard column names from --sumstats file to keep in --out file. Columns names will UPPERCASEed.")
parser_csv.add_argument("--output-cleansumstats-meta", action="store_true", default=False,
help="Instead of converting the file output meta-information file for https://github.com/BioPsyk/cleansumstats/")
parser_csv.set_defaults(func=make_csv)
# 'variantid' utility : load raw summary statistics file and convert it into a standardized format
parser_variantid = subparsers.add_parser("variantid", parents=[parent_parser],
help='Add VARIANT_ID column, with CHR:BP:A1:A2, where A1 and A2 codes are taking from the reference ')
parser_variantid.add_argument("--sumstats", type=str, default='-',
help="Raw input file with summary statistics. "
"Default is '-', e.i. to read from sys.stdin (input pipe).")
parser_variantid.add_argument("--out", type=str, default='-',
help="File to output the result. "
"Default is '-', e.i. to write to sys.stdout (output pipe).")
parser_variantid.add_argument("--force", action="store_true", default=False, help="Allow sumstats.py to overwrite output file if it exists.")
parser_variantid.add_argument("--ref", type=str, help="[required] Tab-separated file with list of referense SNPs.")
parser_variantid.set_defaults(func=make_variantid)
# 'qc' utility: miscellaneous quality control and filtering procedures
parser_qc = subparsers.add_parser("qc", parents=[parent_parser],
help="Miscellaneous quality control and filtering procedures")
parser_qc.add_argument("--sumstats", type=str, default='-',
help="Raw input file with summary statistics. "
"Default is '-', e.i. to read from sys.stdin (input pipe).")
parser_qc.add_argument("--out", type=str, default='-',
help="[required] File to output the result. "
"Default is '-', e.i. to write to sys.stdout (output pipe).")
parser_qc.add_argument("--force", action="store_true", default=False, help="Allow sumstats.py to overwrite output file if it exists.")
parser_qc.add_argument("--exclude-ranges", type=str, nargs='+',
help='Exclude SNPs in ranges of base pair position, for example MHC. '
'The syntax is chr:from-to, for example 6:25000000-35000000. Multiple regions can be excluded. Require CHR and BP columns in sumstats file. ')
parser_qc.add_argument("--dropna-cols", type=str, nargs='+',
help='List of column names. SNPs with missing values in either of the columns will be excluded.')
parser_qc.add_argument("--fix-dtype-cols", type=str, nargs='+',
help='List of column names. Ensure appropriate data type for the columns (CHR, BP - int, PVAL - float, etc)')
parser_qc.add_argument("--require-cols", type=str, nargs='+',
help='List of column names to require in the input. '
'Adding "EFFECT"" to the list will have a special meaning: at least one of BETA, OR, LOGODDS, Z columns must be present in the input.')
parser_qc.add_argument("--maf", type=float, default=None,
help='filters out all variants with minor allele frequency below the provided threshold'
'This parameter is ignored when FRQ column is not present in the sumstats file. ')
parser_qc.add_argument("--info", type=float, default=None,
help='filters out all variants with imputation INFO score below the provided threshold'
'This parameter is ignored when INFO column is not present in the sumstats file. ')
parser_qc.add_argument("--qc-substudies", default=False, action="store_true",
help='filters out variants that pass QC and imputation is less than half of all studies in the meta-analysis '
'(i.e. "?" was seen in more than 1/2*N_studies in the METAL "direction" column)'
'This parameter is ignored when DIRECTION column is not present in the sumstats file. ')
parser_qc.add_argument("--max-or", type=float, default=None,
help='Filter SNPs with OR exceeding threshold. Also applies to OR smaller than the inverse value of the threshold, '
'e.i. for --max-or 25 this QC procedure will exclude SNPs with OR above 25 and below 1/25. '
'--max-or values below 1 are also acceptable (they will be inverted). '
'This parameter is ignored when OR column is not present in the sumstats file. ')
parser_qc.add_argument("--min-pval", type=float, default=None,
help='Filter SNPs with p-value below given threshold (for example, to exclude genome-wide significant SNPs from analysis')
parser_qc.add_argument("--update-z-col-from-beta-and-se", action="store_true", default=False,
help='Create or update Z score column from BETA and SE columns. This parameter is ignored when BETA or SE columns are not present in the sumstats file. ')
parser_qc.add_argument("--snps-only", action="store_true", default=False,
help="excludes all variants with one or more multi-character allele codes. Require A1 and A2 columns in sumstats file. ")
parser_qc.add_argument("--just-acgt", action="store_true",
help="similar to --snps-only, but variants with single-character allele codes outside of {'A', 'C', 'G', 'T' } are also excluded. Require A1 and A2 columns in sumstats file. ")
parser_qc.add_argument("--drop-strand-ambiguous-snps", action="store_true", default=False,
help="excludes strand ambiguous SNPs (AT, CG). Require A1 and A2 columns in sumstats file. ")
parser_qc.add_argument("--just-rs-variants", action="store_true", default=False,
help="keeps only variants with an RS number. Require SNP column in sumstats file. ")
parser_qc.set_defaults(func=make_qc)
# 'zscore' utility: calculate z-score from p-value column and effect size column
parser_zscore = subparsers.add_parser("zscore", parents=[parent_parser],
help="Calculate z-score from p-value column and effect size column")
parser_zscore.add_argument("--sumstats", type=str, help="[REQUIRED] Raw input file with summary statistics. ")
parser_zscore.add_argument("--out", type=str, default='-',
help="[required] File to output the result. "
"Default is '-', e.i. to write to sys.stdout (output pipe).")
parser_zscore.add_argument("--force", action="store_true", default=False, help="Allow sumstats.py to overwrite output file if it exists.")
parser_zscore.add_argument("--effect", default=None, type=str, choices=['BETA', 'OR', 'Z', 'LOGODDS'],
help="Effect column. Default is to auto-detect. In case if multiple effect columns are present in the input file"
" a warning will be shown and the first column is taken according to the priority list: "
"Z (highest priority), BETA, OR, LOGODDS (lowest priority).")
parser_zscore.add_argument("--a1-inc", action="store_true", default=False,
help='A1 is the increasing risk (effect) allele.')
parser_zscore.add_argument("--chunksize", default=100000, type=int,
help="Size of chunk to read the file.")
parser_zscore.set_defaults(func=make_zscore)
# 'pvalue' utility: calculate p-value column from 'z'' or 'beta'/'se' columns
parser_pvalue = subparsers.add_parser("pvalue", parents=[parent_parser],
help="Calculate p-value column from 'z'' or 'beta'/'se' columns")
parser_pvalue.add_argument("--sumstats", type=str, help="[REQUIRED] Raw input file with summary statistics. ")
parser_pvalue.add_argument("--out", type=str, default='-',
help="[required] File to output the result. "
"Default is '-', e.i. to write to sys.stdout (output pipe).")
parser_pvalue.add_argument("--force", action="store_true", default=False, help="Allow sumstats.py to overwrite output file if it exists.")
parser_pvalue.add_argument("--chunksize", default=100000, type=int,
help="Size of chunk to read the file.")
parser_pvalue.set_defaults(func=make_pvalue)
# 'beta' utility: calculate BETA column from OR and LOGODDS columns
parser_beta = subparsers.add_parser("beta", parents=[parent_parser],
help="Calculate BETA column from OR and LOGODDS columns")
parser_beta.add_argument("--sumstats", type=str, help="[REQUIRED] Raw input file with summary statistics. ")
parser_beta.add_argument("--out", type=str, default='-',
help="[required] File to output the result. "
"Default is '-', e.i. to write to sys.stdout (output pipe).")
parser_beta.add_argument("--force", action="store_true", default=False, help="Allow sumstats.py to overwrite output file if it exists.")
parser_beta.set_defaults(func=make_beta)
# 'mat' utility: load summary statistics into matlab format
parser_mat = subparsers.add_parser("mat", parents=[parent_parser], help="Create mat files that can "
"be used as an input for cond/conj FDR and for CM3 model. "
"Takes csv files (created with the csv task of this script). "
"Require columns: SNP, P, and one of the signed summary statistics columns (BETA, OR, Z, LOGODDS). "
"Creates corresponding mat files which can be used as an input for the conditional fdr model. "
"Only SNPs from the reference file are considered. Zscores of strand ambiguous SNPs are set to NA. "
"To use CHR:POS for merging summary statistics with reference file consider 'rs' utility "
"which auguments summary statistics with SNP column (first run 'sumstats.py rs ...', "
"then feed the resulting file into sumstats.py mat ...)")
parser_mat.add_argument("--sumstats", type=str, default='-',
help="Raw input file with summary statistics. "
"Default is '-', e.i. to read from sys.stdin (input pipe).")
parser_mat.add_argument("--ref", type=str, help="[required] Tab-separated file with list of referense SNPs.")
parser_mat.add_argument("--out", type=str, help="[required] File to output the result. File should end with .mat extension.")
parser_mat.add_argument("--force", action="store_true", default=False, help="Allow sumstats.py to overwrite output file if it exists.")
parser_mat.add_argument("--keep-cols", nargs='*', choices=cols._fields,
default=[], type=lambda col: col.upper(), metavar='COLUMN_NAME',
help="Columns from csv file to keep in mat file")
parser_mat.add_argument("--keep-all-cols", action="store_true",
default=False, help="Keep all columns from cvs file in mat file, except SNP, CHR, BP, A1 and A2")
parser_mat.add_argument("--trait", type=str, default='',
help="Trait name that will be used in mat file. Can be kept empty, in this case the variables will be named 'logpvec', 'zvec' and 'nvec'")
parser_mat.add_argument("--ignore-alleles", action="store_true", default=False,
help="Load summary stats file ignoring alleles (only 'logpvec' is created in this case, entire 'zvec' is set to nan).")
parser_mat.add_argument("--without-n", action="store_true", default=False,
help="Proceed without sample size (N or NCASE/NCONTROL)")
parser_mat.add_argument("--chunksize", default=100000, type=int,
help="Size of chunk to read the file.")
parser_mat.set_defaults(func=make_mat)
# 'lift' utility: lift RS numbers to a newer version of SNPdb, and/or liftover chr:pos to another genomic build using UCSC chain files
parser_lift = subparsers.add_parser("lift", parents=[parent_parser],
help="Lift RS numbers to a newer version of SNPdb, "
"and/or liftover chr:pos to another genomic build using UCSC chain files. "
"WARNING: this utility may use excessive amount of memory (up and beyong 32 GB of RAM).")
parser_lift.add_argument("--sumstats", type=str, default='-',
help="Raw input file with summary statistics. "
"Default is '-', e.i. to read from sys.stdin (input pipe).")
parser_lift.add_argument("--out", type=str, default='-',
help="File to output the result. "
"Default is '-', e.i. to write to sys.stdout (output pipe).")
parser_lift.add_argument("--force", action="store_true", default=False, help="Allow sumstats.py to overwrite output file if it exists.")
parser_lift.add_argument("--chain-file", default=None, type=str,
help="Chain file to use for CHR:BP conversion between genomic builds")
parser_lift.add_argument("--snp-chrpos", default=None, type=str,
help="NCBI SNPChrPosOnRef file.")
parser_lift.add_argument("--snp-history", default=None, type=str,
help="NCBI SNPHistory file.")
parser_lift.add_argument("--rs-merge-arch", default=None, type=str,
help="NCBI RsMergeArch file.")
parser_lift.add_argument("--keep-bad-snps", action="store_true", default=False,
help="Keep SNPs with undefined rs# number or CHR:POS location in the output file.")
parser_lift.add_argument("--na-rep", default='NA', type=str, choices=['NA', ''],
help="Missing data representation.")
parser_lift.add_argument("--gzip", action="store_true", default=False,
help="A flag indicating whether to compress the resulting file with gzip.")
parser_lift.set_defaults(func=make_lift)
# 'clump' utility: clump summary stats, produce lead SNP report, produce candidate SNP report
parser_clump = subparsers.add_parser("clump", parents=[parent_parser],
help="""Perform LD-based clumping of summary stats. This works similar to FUMA snp2gene functionality (http://fuma.ctglab.nl/tutorial#snp2gene).
Step 1. Re-save summary stats into one file for each chromosome.
Step 2a Use 'plink --clump' to find independent significant SNPs (default r2=0.6)
Step 2b Use 'plink --clump' to find lead SNPs, by clumping independent significant SNPs (default r2=0.1)
Step 3. Use 'plink --ld' to find genomic loci around each independent significant SNP (default r2=0.6)
Step 4. Merge together genomic loci which are closer than certain threshold (250 KB)
Step 5. Merge together genomic loci that fall into exclusion regions, such as MHC
Step 6. Output genomic loci report, indicating lead SNPs for each loci
Step 7. Output candidate SNP report""")
parser_clump.add_argument("--sumstats", type=str, help="Input file with summary statistics")
parser_clump.add_argument("--out", type=str, help="[required] File to output the result.")
parser_clump.add_argument("--force", action="store_true", default=False, help="Allow sumstats.py to overwrite output file if it exists.")
parser_clump.add_argument("--chr-labels", type=str, nargs='+',
help="List of chromosome labels to substitute for @, default to 1..22")
parser_clump.add_argument("--clump-field", type=str, default='PVAL', help="Column to clump on.")
parser_clump.add_argument("--clump-snp-field", type=str, default='SNP', help="Column with marker name.")
parser_clump.add_argument("--chr", type=str, default='CHR', help="Column name with chromosome labels. ")
parser_clump.add_argument("--indep-r2", type=float, default=0.6, help="LD r2 threshold for clumping independent significant SNPs.")
parser_clump.add_argument("--lead-r2", type=float, default=0.1, help="LD r2 threshold for clumping lead SNPs.")
parser_clump.add_argument("--clump-p1", type=float, default=5e-8, help="p-value threshold for independent significant SNPs.")
parser_clump.add_argument("--bfile-chr", type=str,
help="prefix for plink .bed/.bim/.fam file. Will automatically concatenate .bed/.bim/.fam files split across 22 chromosomes. "
"If the filename prefix contains the symbol @, sumstats.py will replace the @ symbol with chromosome numbers. "
"Otherwise, sumstats.py will append chromosome numbers to the end of the filename prefix. ")
parser_clump.add_argument("--ld-window-kb", type=float, default=10000, help="Window size in KB to search for clumped SNPs. ")
parser_clump.add_argument("--loci-merge-kb", type=float, default=250, help="Maximum distance in KB of LD blocks to merge. ")
parser_clump.add_argument("--exclude-ranges", type=str, nargs='+',
help='Exclude SNPs in ranges of base pair position, for example MHC. '
'The syntax is chr:from-to, for example 6:25000000-35000000. Multiple regions can be excluded.')
parser_clump.add_argument("--plink", type=str, default='plink', help="Path to plink executable.")
parser_clump.add_argument("--sumstats-chr", type=str, help="Input file with summary statistics, one file per chromosome")
parser_clump.set_defaults(func=make_clump)
# 'rs' utility: augument summary statistic file with SNP RS number from reference file
parser_rs = subparsers.add_parser("rs", parents=[parent_parser],
help="Augument summary statistic file with SNP RS number from reference file. "
"Merging is done on chromosome and position. If SNP column already exists in --sumstats file, it will be overwritten.")
parser_rs.add_argument("--sumstats", type=str, help="[required] Input file with summary statistics in standardized format")
parser_rs.add_argument("--ref", type=str, help="[required] Tab-separated file with list of referense SNPs.")
parser_rs.add_argument("--out", type=str, help="[required] File to output the result.")
parser_rs.add_argument("--force", action="store_true", default=False, help="Allow sumstats.py to overwrite output file if it exists.")
parser_rs.add_argument("--a1a2", action="store_true", default=False,
help="Add A1 and A2 columns from the reference file. "
"Existing A1 and/or A2 columns in --sumstats file will be overwritten.")
parser_rs.add_argument("--chunksize", default=100000, type=int,
help="Size of chunk to read the file.")
parser_rs.set_defaults(func=make_rs)
# 'ls' utility: display information about columns of a standardized summary statistics file
parser_ls = subparsers.add_parser("ls", parents=[parent_parser],
help="Report information about standard sumstat files, "
"including the set of columns available, number of SNPs, etc.")
parser_ls.add_argument("--path", type=str, help="[required] File or regular expresion of the files to include in the report.")
parser_ls.add_argument("--out", type=str, help="[required] File to output the result.")
parser_ls.add_argument("--force", action="store_true", default=False, help="Allow sumstats.py to overwrite output file if it exists.")
parser_ls.set_defaults(func=make_ls)
# 'mat-to-csv' utility: convert matlab .mat file with logpvec and zvec into CSV files
parser_mattocsv = subparsers.add_parser("mat-to-csv", parents=[parent_parser],
help="Convert matlab .mat file with logpvec, zvec and (optionally) nvec into CSV files.")
parser_mattocsv.add_argument("--mat", type=str, help="[required] Input mat file.")
parser_mattocsv.add_argument("--ref", type=str, help="[required] Tab-separated file with list of referense SNPs.")
parser_mattocsv.add_argument("--out", type=str, help="[required] File to output the result.")
parser_mattocsv.add_argument("--force", action="store_true", default=False, help="Allow sumstats.py to overwrite output file if it exists.")
parser_mattocsv.add_argument("--na-rep", default='NA', type=str, choices=['NA', ''],
help="Missing data representation.")
parser_mattocsv.add_argument("--gzip", action="store_true", default=False,
help="A flag indicating whether to compress the resulting file with gzip.")
parser_mattocsv.set_defaults(func=mat_to_csv)
# 'ldsc-to-mat' utility: convert data from LD score regression formats to .mat files
parser_ldsctomat = subparsers.add_parser("ldsc-to-mat", parents=[parent_parser],
help="Convert .sumstats, .ldscore, .M, .M_5_50 and "
"binary .annot files from LD score regression to .mat files.")
parser_ldsctomat.add_argument("--ref", type=str, help="[required] Tab-separated file with list of referense SNPs.")
parser_ldsctomat.add_argument("--out", type=str, help="[required] File to output the result.")
parser_ldsctomat.add_argument("--force", action="store_true", default=False, help="Allow sumstats.py to overwrite output file if it exists.")
parser_ldsctomat.add_argument("--sumstats", type=str, default=None,
help="Name of .sumstats.gz file")
parser_ldsctomat.add_argument("--ldscore", type=str, default=None,
help="Name of .ldscore.gz files, where symbol @ indicates chromosome index. Example: [email protected]")
parser_ldsctomat.add_argument("--annot", type=str, default=None,
help="Name of .annot.gz files, where symbol @ indicates chromosome index. Example: [email protected]")
parser_ldsctomat.add_argument("--M", type=str, default=None,
help="Name of .M files, where symbol @ indicates chromosome index. Example: [email protected]")
parser_ldsctomat.add_argument("--M-5-50", type=str, default=None,
help="Name of .M_5_50 files, where symbol @ indicates chromosome index. Example: [email protected]_5_50")
parser_ldsctomat.add_argument("--chr-labels", type=str, nargs='+',
help="List of chromosome labels to substitute for @, default to 1..22")
parser_ldsctomat.set_defaults(func=ldsc_to_mat)
# 'frq-to-mat' utility: convert allele frequency from FRQ plink format to .mat files
parser_frqtomat = subparsers.add_parser("frq-to-mat", parents=[parent_parser],
help="Convert .frq files plink from .mat files.")
parser_frqtomat.add_argument("--ref", type=str, help="Tab-separated file with list of referense SNPs.")
parser_frqtomat.add_argument("--out", type=str, help="[required] File to output the result.")
parser_frqtomat.add_argument("--force", action="store_true", default=False, help="Allow sumstats.py to overwrite output file if it exists.")
parser_frqtomat.add_argument("--frq", type=str, default=None,
help="Name of .frq files, where symbol @ indicates chromosome index. Example: [email protected]")
parser_frqtomat.add_argument("--afreq", type=str, default=None,
help="Name of .afreq files, where symbol @ indicates chromosome index. Example: [email protected]")
parser_frqtomat.add_argument("--chr-labels", type=str, nargs='+',
help="List of chromosome labels to substitute for @, default to 1..22")
parser_frqtomat.set_defaults(func=frq_to_mat)
# 'ref-to-mat' utility: convert reference files to .mat files
parser_reftomat = subparsers.add_parser("ref-to-mat", parents=[parent_parser],
help="Convert reference files to .mat files.")
parser_reftomat.add_argument("--ref", type=str, help="Tab-separated file with list of referense SNPs.")
parser_reftomat.add_argument("--out", type=str, help="[required] File to output the result.")
parser_reftomat.add_argument("--force", action="store_true", default=False, help="Allow sumstats.py to overwrite output file if it exists.")
parser_reftomat.add_argument("--numeric-only", action="store_true", default=False, help="Save only numeric data (CHR, BP, GP), skip all other column (A1, A2, SNP).")
parser_reftomat.set_defaults(func=ref_to_mat)
# 'ldsum' utility: convert plink .ld.gz files (pairwise ld r2) to ld scores
parser_ldsum = subparsers.add_parser("ldsum", parents=[parent_parser],
help="convert plink .ld.gz files (pairwise ld r2) to ld scores")
parser_ldsum.add_argument("--bim", type=str, help="[required] plink bim file")
parser_ldsum.add_argument("--ld", type=str, help="[required] plink .ld file")
parser_ldsum.add_argument("--out", type=str, help="[required] File to output the result.")
parser_ldsum.add_argument("--force", action="store_true", default=False, help="Allow sumstats.py to overwrite output file if it exists.")
parser_ldsum.add_argument('--r2-min', default=None, type=float, nargs='+',
help='Lower bound (exclusive) of r2 to consider in ld score estimation. '
'Should be used in conjunction with --r2-max. '
'Intended usage of this parameter is to create a binned histogram of l2 or l4 values, for example: '
'"--r2-min 0.00 0.25 0.50 0.75 --r2-max 0.25 0.50 0.75 1.00". '
'Normally --r2-min and --r2-max should cover the range from 0 to 1. '
'In case of --per-allele flag, --r2-min and --r2-max thresholds apply to the product of allelic correlation and heterozigosity, '
'e.i. to r2_{jk} * 2*p_k*(1-p_k), where p_k denotes the MAF of SNP k. '
'To produce a complete histogram in case of --per-allele flag one must use --r2-min and --r2-max that cover the range from 0 to 0.5. ')
parser_ldsum.add_argument('--r2-max', default=None, type=float, nargs='+',
help='Upper bound (inclusive) of r2 to consider in ld score estimation. '
'See description of --r2-min option for additional details. ')
parser_ldsum.add_argument('--per-allele', default=False, action='store_true',
help='Setting this flag causes sumstats.py to compute per-allele LD Scores, '
'i.e., '
'\ell2_j := \sum_k 2*p_k(1-p_k) r^2_{jk}, and '
'\ell4_j := \sum_k (2*p_k(1-p_k))^2 r^4_{jk}, '
'where p_k denotes the MAF of SNP k. '
'Require --frq parameter to be specified. ')
parser_ldsum.add_argument("--frq", type=str, default=None, help="Name of the .frq file.")
parser_ldsum.add_argument('--not-diag', default=False, action='store_true',
help='sumstats.py assume that plink-generated --ld file does not have diagonal elements, '
'e.i. does not contain LD r2 entries of 1.0 for variant r2 with itself. '
'By default sumstats.py adds such diagonal entries to the LD score. '
'Setting --not-diag flag causes sumstats.py to NOT to add the diagonal elements. ')
parser_ldsum.add_argument("--chunksize", default=10000000, type=int,
help="Size of chunk to read the --ld file.")
parser_ldsum.set_defaults(func=ldsum)
# 'diff-mat' utility: compare two .mat files with logpvec, zvec and nvec, and report the differences
parser_diffmat = subparsers.add_parser("diff-mat", parents=[parent_parser],
help="Compare two .mat files with logpvec, zvec and nvec, "
"and report the differences.")
parser_diffmat.add_argument("--mat1", type=str, default=None, help="[required] Name of the first .mat file")
parser_diffmat.add_argument("--mat2", type=str, default=None, help="[required] Name of the second .mat file")
parser_diffmat.add_argument("--ref", type=str, help="[required] Tab-separated file with list of referense SNPs.")
parser_diffmat.add_argument("--out", type=str, help="[required] File to output the result.")
parser_diffmat.add_argument("--force", action="store_true", default=False, help="Allow sumstats.py to overwrite output file if it exists.")
parser_diffmat.add_argument("--sumstats", type=str, default=None,
help="Optionally, the name of the source summary statistics file in standardized .csv format. "
"Assuming that both .mat files originate from this file diff-mat will produce output file "
"to help investigate where the differences came from.")
parser_diffmat.set_defaults(func=diff_mat)
# 'neff' utility: generate N column from NCASE and NCONTROL
parser_neff = subparsers.add_parser("neff", parents=[parent_parser],
help="generate N column from NCASE and NCONTROL, as 4 / (1 / NCASE + 1 / NCONTROL)")
parser_neff.add_argument("--sumstats", type=str, default='-',
help="Raw input file with summary statistics. "
"Default is '-', e.i. to read from sys.stdin (input pipe).")
parser_neff.add_argument("--out", type=str, default='-',
help="[required] File to output the result. "
"Default is '-', e.i. to write to sys.stdout (output pipe).")
parser_neff.add_argument("--force", action="store_true", default=False, help="Allow sumstats.py to overwrite output file if it exists.")
parser_neff.add_argument("--drop", action="store_true", default=False, help="Drop NCASE and NCONTROL columns.")
parser_neff.add_argument("--factor", default=4, type=float,
help="Factor in the numerator of the NEFF formula. Default to 4. Sometimes you may want FACTOR=2. Set FACTOR=0 if you want NEFF = NCASE + NCONTROL.")
parser_neff.set_defaults(func=make_neff)
return parser.parse_args(args)
### =================================================================================
### Implementation for parser_csv
### =================================================================================
def set_clean_args_cnames(args):
"""
Inspect column names in user args, and clean them according to sumstats_utils.clean_header()
Raises an exception if either before or after cleaning some column names are duplicated.
"""
cnames = [x.lower() for x in cols._asdict()]
args_cnames = [args[x] for x in cnames if args[x] is not None]
if len(args_cnames) != len(set(args_cnames)):
raise(ValueError('Duplicated argument: {}'.format(find_duplicates(args_cnames))))
for cname in cnames:
if args[cname] is not None:
args[cname] = clean_header(args[cname])
args_clean_cnames = [args[x] for x in cnames if args[x] is not None]
if len(args_clean_cnames) != len(set(args_clean_cnames)):
raise(ValueError('Cleaning rules yield duplicated argument: {}'.format(find_duplicates(args_clean_cnames))))
def set_clean_file_cnames(df):
"""
Inspect column names in pd.DataFrame, and clean them according to sumstats_utils.clean_header()
Raises an exception if either before or after cleaning some column names are duplicated.
"""
file_cnames = df.columns
if len(file_cnames) != len(set(file_cnames)):
raise(ValueError('Unable to process input file due to duplicated column names'))
clean_file_cnames = [clean_header(x) for x in file_cnames]
if len(clean_file_cnames) != len(set(clean_file_cnames)):
raise(ValueError('Cleaning column names resulted in duplicated column names: {}'.format(clean_file_cnames)))
df.columns = clean_file_cnames
def find_duplicates(values):
return [item for item, count in collections.Counter(values).items() if count > 1]
def find_auto_cnames(args, clean_file_cnames):
"""
Auto-detect column using a set of default columns names
"""
cnames = [x.lower() for x in cols._asdict()]
user_args = [args[x] for x in cnames if args[x] is not None]
for default_cname, cname in default_cnames.items():
# Ignore default cname if it is explicitly provided by the user
if (cname.lower() not in args) or args[cname.lower()]:
continue
# Ignore default cname if it is not present among file columns
if clean_header(default_cname) not in clean_file_cnames:
continue
# Ignore default cname if user took the column for something else
if clean_header(default_cname) in user_args:
continue
# Ignore default cname if user explicitly asked to ignore it
if args['ignore'] and (clean_header(default_cname) in [clean_header(x) for x in args['ignore']]):
continue
args[cname.lower()] = clean_header(default_cname)
def check_input_file(file):
if file == '-':
raise ValueError("sys.stdin is not supported as input file")
if (file != sys.stdin) and not os.path.isfile(file):
raise ValueError("Input file does not exist: {f}".format(f=file))
def check_output_file(file, force=False):
# Delete target file if user specifies --force option
if file == '-':
raise ValueError("sys.stdout is not supported as output file")
if file == sys.stdout:
return
if force:
try:
os.remove(file)
except OSError:
pass
# Otherwise raise an error if target file already exists
if os.path.isfile(file) and not force:
raise ValueError("Output file already exists: {f}".format(f=file))
# Create target folder if it doesn't exist
output_dir = os.path.dirname(file)
if output_dir and not os.path.isdir(output_dir): os.makedirs(output_dir) # ensure that output folder exists
def update_cleansumstats_cols(cleansumstats_cols, cname, original):
if cname == 'CHRPOSA1A2':
cleansumstats_cols.append(('col_CHR', original))
cleansumstats_cols.append(('col_POS', original))
cleansumstats_cols.append(('col_EffectAllele', original))
cleansumstats_cols.append(('col_OtherAllele', original))
return
if cname == 'CHRPOS':
cleansumstats_cols.append(('col_CHR', original))
cleansumstats_cols.append(('col_POS', original))
return
if cname == 'A1A2':
raise(ValueError('--a1a2 not supported for --output-cleansumstats-meta'))
if cname in cname_to_cleansumstats_map:
cleansumstats_cols.append((cname_to_cleansumstats_map[cname], original))
else:
log.log('Warning: {} not supported by --output-cleansumstats-meta'.format(cname))
def get_meta_template():
return '''cleansumstats_metafile_date: '2020-12-31'
cleansumstats_metafile_user: username
cleansumstats_version: 1.0.0-alpha
path_sumStats: {path_sumStats}
{cols_definition}
stats_GCMethod: none
stats_Model: {linear_or_logistic}
stats_Notes: 'dummy description'
stats_TraitType: quantitative
stats_neglog10P: false
study_AccessDate: '2020-12-31'
study_Ancestry: EUR
study_Array: meta
study_FilePortal: http://website.org/dummydata
study_FileURL: http://website.org/dummydata/file.txt.gz
study_Gender: mixed
study_ImputePanel: HapMap
study_ImputeSoftware: meta
study_PMID: 666
study_PhasePanel: meta
study_PhaseSoftware: meta
study_PhenoCode:
- EFO:0000000
study_PhenoDesc: 'phenotype description'
study_Title: dummy_title
study_Use: open
study_Year: 2020
'''
def make_csv(args, log):
"""
Based on file with summary statistics creates a tab-delimited csv file with standard columns.
"""
if args.sumstats == '-': args.sumstats = sys.stdin
if args.out == '-': args.out = sys.stdout
check_input_file(args.sumstats)
if args.all_snp_info_23_and_me: check_input_file(args.all_snp_info_23_and_me)
set_clean_args_cnames(vars(args))
check_output_file(args.out, args.force)
if args.keep_all_cols and args.keep_cols:
err_msg = ("Misleading input arguments! Use either '--keep-cols' or "
"'--keep-all-cols' option, but not both at a time.")
raise(ValueError(err_msg))
if args.keep_cols is None: args.keep_cols = []
log.log('Reading summary statistics file {}...'.format(args.sumstats))
if (args.head > 0) and (args.sumstats != sys.stdin):
log.log('File header:')
header = get_header(args.sumstats, lines=args.head)
for line in header: log.log(line)
if args.header is None:
reader = pd.read_csv(args.sumstats, dtype=str, sep=args.sep, chunksize=args.chunksize, na_values=args.na_values)
else:
reader = pd.read_csv(args.sumstats, dtype=str, sep=args.sep, chunksize=args.chunksize, na_values=args.na_values, header=None, names=args.header.split())
reader_23_and_me = pd.read_csv(args.all_snp_info_23_and_me, dtype=str, sep=args.sep, chunksize=args.chunksize) if args.all_snp_info_23_and_me else None
n_snps = 0
max_n_val = np.nan; max_ncase_val = np.nan; max_ncontrol_val = np.nan
with (open(args.out, 'a') if args.out != sys.stdout else sys.stdout) as out_f:
for chunk_index, chunk in enumerate(reader):
if reader_23_and_me:
chunk = pd.concat([chunk, next(reader_23_and_me)], axis=1)
chunk = chunk.loc[:, ~chunk.columns.duplicated()]
if args.qc_23_and_me:
chunk = chunk[chunk['pass'] != 'N'].copy()
original_file_cname = chunk.columns
set_clean_file_cnames(chunk)
if chunk_index == 0: # First chunk => analyze column names
if args.auto: find_auto_cnames(vars(args), chunk.columns)
# Find the map from (cleaned) column name to a standard cname (as it will appear in the resulting file)
cnames = [x.lower() for x in cols._asdict()]
cname_map = {vars(args)[cname] : cname.upper() for cname in cnames if vars(args)[cname] is not None}
# Report any missing columns that user requested to put in the resulting file
cname_missing = [x for x in cname_map if x not in chunk.columns]
if cname_missing: raise(ValueError('Columns {} are missing in the input file'.format(cname_missing)))
# Describe the mapping between old and new column names that we are going to perform
log.log('Interpret column names as follows:')
cleansumstats_cols = []
for original in original_file_cname:
cname = cname_map.get(clean_header(original))
if cname and args.output_cleansumstats_meta:
update_cleansumstats_cols(cleansumstats_cols, cname, original)
# note that in --output-cleansumstats-meta mode we do take N/NCASE/NCONTROL columns
# but also allow to specify --n-val / --ncontrol-val / --ncase-val as a meta-data
# this is difference from when we actually produce a .csv file - in this case
# --n-val / --ncontrol-val / --ncase-val OVERWRITES the original sample size column(s)
if (args.ncase_val is not None) and (cname==cols.NCASE):
cleansumstats_cols.append(('stats_CaseN', int(args.ncase_val)))
if not args.output_cleansumstats_meta: cname=None
if (args.ncontrol_val is not None) and (cname==cols.NCONTROL):
cleansumstats_cols.append(('stats_ControlN', int(args.ncontrol_val)))
if not args.output_cleansumstats_meta: cname=None
if (args.n_val is not None) and (cname==cols.N):
cleansumstats_cols.append(('stats_TotalN', int(args.n_val)))
if not args.output_cleansumstats_meta: cname=None
if cname: column_status = describe_cname[cname]
elif args.keep_all_cols or (original.upper() in args.keep_cols): column_status = "Will be kept as unrecognized column"
else: column_status = "Will be deleted"
log.log("\t{o} : {d} ({e})".format(o=original, d=cname, e=column_status))
if not cname_map: raise(ValueError('Arguments imply to delete all columns from the input file. Did you forget --auto flag?'))
final_cols = set(cname_map.values()) # final list of columns in the resulting file
if (cols.CHRPOS not in final_cols) and (cols.CHRPOSA1A2 not in final_cols) and (cols.CHR not in final_cols): log.log('Warning: CHR column ({}) is not found'.format(describe_cname[cols.CHR]))
if (cols.CHRPOS not in final_cols) and (cols.CHRPOSA1A2 not in final_cols) and (cols.BP not in final_cols): log.log('Warning: BP column ({}) is not found'.format(describe_cname[cols.BP]))
if cols.SNP not in final_cols: log.log('Warning: SNP column ({}) is not found'.format(describe_cname[cols.SNP]))
if cols.PVAL not in final_cols: log.log('Warning: PVAL column ({}) is not found'.format(describe_cname[cols.PVAL]))
if (cols.A1 not in final_cols) and (cols.A1A2 not in final_cols) and (cols.CHRPOSA1A2 not in final_cols): log.log('Warning: A1 column ({}) is not found'.format(describe_cname[cols.A1]))
if (cols.A2 not in final_cols) and (cols.A1A2 not in final_cols) and (cols.CHRPOSA1A2 not in final_cols): log.log('Warning: A2 column ({}) is not found'.format(describe_cname[cols.A2]))
effect_size_column_count = int(cols.Z in final_cols) + int(cols.OR in final_cols) + int(cols.BETA in final_cols) + int(cols.LOGODDS in final_cols)
if effect_size_column_count == 0: log.log('Warning: None of the columns indicate effect direction: typically either BETA, OR, LOGODDS or Z column is expected')
if effect_size_column_count > 1: log.log('Warning: Multiple columns indicate effect direction: typically only one of BETA, OR, LOGODDS and Z columns is expected')
if args.output_cleansumstats_meta:
# add a dummy stats_TotalN
if 'stats_TotalN' not in dict(cleansumstats_cols): cleansumstats_cols.append(('stats_TotalN', '1'))
out_f.write(get_meta_template().format(
path_sumStats=os.path.basename(args.sumstats),
cols_definition = '\n'.join(['{}: {}'.format(cname, original) for cname, original in cleansumstats_cols]),
linear_or_logistic = 'logistic' if (cols.OR in final_cols) else 'linear'
))
break
if not args.keep_all_cols:
chunk.drop([x for x in chunk.columns if ((x not in cname_map) and (x not in args.keep_cols))], axis=1, inplace=True)
chunk.rename(columns=cname_map, inplace=True)
# Split CHR:POS column into two
if cols.CHRPOS in chunk.columns:
chunk[cols.CHR], chunk[cols.BP] = chunk[cols.CHRPOS].str.replace('_', ':').str.split(':', 1).str
chunk.drop(cols.CHRPOS, axis=1, inplace=True)
# Split A1/A2 column into two
if cols.A1A2 in chunk.columns:
chunk[cols.A1], chunk[cols.A2] = chunk[cols.A1A2].str.split('/', 1).str
chunk.drop(cols.A1A2, axis=1, inplace=True)
# Split CHR:POS:A1:A2 column into four
if cols.CHRPOSA1A2 in chunk.columns:
chunk[cols.CHR], chunk[cols.BP], chunk[cols.A1], chunk[cols.A2] = chunk[cols.CHRPOSA1A2].str.replace('_', ':').str.split(':', 3).str
chunk.drop(cols.CHRPOSA1A2, axis=1, inplace=True)
# Validate that EA has the same values as A1, and drop EA:
if cols.EA in chunk.columns:
if np.any(chunk[cols.EA] != chunk[cols.A1]):
raise('EA column does not match A1 column, unable to read summary stats')
chunk.drop(cols.EA, axis=1, inplace=True)
# Ensure standard labels in CHR column
if cols.CHR in chunk.columns:
chunk[cols.CHR].fillna(-9, inplace=True)
chunk[cols.CHR] = format_chr(chunk[cols.CHR])
# Ensure that alleles are coded as capital letters
if cols.A1 in chunk.columns: chunk[cols.A1] = chunk[cols.A1].str.upper().str.strip()
if cols.A2 in chunk.columns: chunk[cols.A2] = chunk[cols.A2].str.upper().str.strip()
# Populate sample size columns (NCASE, NCONTROL, N)
if args.ncase_val is not None: chunk[cols.NCASE] = args.ncase_val
if args.ncontrol_val is not None: chunk[cols.NCONTROL] = args.ncontrol_val
if args.n_val is not None: chunk[cols.N] = args.n_val
# Keep track of the largest NCASE, NCONTROL and N values
if cols.NCASE in chunk: max_ncase_val = np.nanmax([max_ncase_val, chunk[cols.NCASE].astype(float).max()])
if cols.NCONTROL in chunk: max_ncontrol_val = np.nanmax([max_ncontrol_val, chunk[cols.NCONTROL].astype(float).max()])
if cols.N in chunk: max_n_val = np.nanmax([max_n_val, chunk[cols.N].astype(float).max()])
# Swap A1 and A2 for 23andMe, because in 23andMe summary stats effect size is about A2
if args.all_snp_info_23_and_me:
chunk.columns = [(cols.A1 if x==cols.A2 else cols.A2 if x==cols.A1 else x) for x in chunk.columns]
chunk = chunk.sort_index(axis=1)
fix_columns_order(chunk).to_csv(out_f, index=False, header=(chunk_index==0), sep='\t', na_rep='NA')
n_snps += len(chunk)
eprint("{f}: {n} lines processed".format(f=args.sumstats, n=(chunk_index+1)*args.chunksize))
if args.preview and (chunk_index+1) >= args.preview:
log.log('Abort reading input file due to --preview flag.')
break
if not args.output_cleansumstats_meta:
if n_snps == 0: raise(ValueError('Input summary stats file appears to be empty.'))
log.log("Done. {n} SNPs saved to {f}".format(n=n_snps, f=args.out))
log.log('Sample size: N={} NCASE={} NCONTROL={}'.format(max_n_val, max_ncase_val, max_ncontrol_val))
if (not args.skip_validation) and (not args.output_cleansumstats_meta) and (args.out != sys.stdout):
log.log('Validate the resulting file...')
reader = pd.read_csv(args.out, sep='\t', chunksize=args.chunksize)
n_snps = 0
for chunk_index, chunk in enumerate(reader):
if chunk_index==0:
log.log('Column types: ' + ', '.join([column + ':' + str(dtype) for (column, dtype) in zip(chunk.columns, chunk.dtypes)]))
n_snps += len(chunk)
log.log("Done. {n} SNPs read from {f}".format(n=n_snps, f=args.out))
### =================================================================================
### Implementation for parser_qc
### =================================================================================
def describe_sample_size(sumstats, log):
log.log('Sample size N={} NCASE={} NCONTROL={}'.format(
sumstats[cols.N].max() if cols.N in sumstats else np.nan,
sumstats[cols.NCASE].max() if cols.NCASE in sumstats else np.nan,
sumstats[cols.NCONTROL].max() if cols.NCONTROL in sumstats else np.nan))
def drop_sumstats(sumstats, log, reason, drop_labels=None, dropna_subset=None):
'''Drop labels from sumstats, and log the number of excluded rows.'''
sumstats_len = len(sumstats)
if drop_labels is not None:
sumstats.drop(drop_labels, inplace=True)
if dropna_subset is not None:
sumstats.dropna(subset=dropna_subset, inplace=True)
log.log('Drop {} markers ({})'.format(sumstats_len - len(sumstats), reason))
def make_qc(args, log):
if args.sumstats == '-': args.sumstats = sys.stdin
if args.out == '-': args.out = sys.stdout
check_input_file(args.sumstats)
check_output_file(args.out, args.force)
if (args.max_or is not None) and (args.max_or <= 0): raise(ValueError('--max-or value must not be negative'))
if (args.maf is not None) and ((args.maf < 0) or (args.maf > 1)): raise(ValueError('--maf value must be between 0 and 1'))
if (args.info is not None) and (args.info < 0): raise(ValueError('--info value must not be negative'))
if (args.min_pval is not None) and ((args.min_pval < 0) or (args.min_pval > 1)): raise(ValueError('--min-pval value be between 0 and 1'))
if (args.max_or is not None) and (args.max_or < 1):
log.log('--max-or was changed from {} to {}'.format(args.max_or, 1/args.max_or))
args.max_or = 1 / args.max_or
if args.dropna_cols is None: args.dropna_cols = []
if args.fix_dtype_cols is None: args.fix_dtype_cols = []
if args.require_cols is None: args.require_cols = []
# Read summary sumstats file...
log.log('Reading sumstats file {}...'.format(args.sumstats))
sumstats = pd.read_csv(args.sumstats, sep='\t', dtype=str)
exclude_ranges = make_ranges(args.exclude_ranges, log)
log.log("Sumstats file contains {d} markers.".format(d=len(sumstats)))
if (args.exclude_ranges is not None) and (('BP' not in sumstats) or ('CHR' not in sumstats)):
log.log('Warning: skip --exclude-ranges ("BP" and/or "CHR" columns not found in {})'.format(args.sumstats))
args.exclude_ranges = None
missing_dropna_cols = [x for x in args.dropna_cols if x not in sumstats]
missing_fix_dtype_cols = [x for x in args.fix_dtype_cols if x not in sumstats]
if missing_dropna_cols:
log.log('Warning: can not apply --dropna-cols to {}; columns are missing'.format(', '.join(missing_dropna_cols)))
args.dropna_cols = [x for x in args.dropna_cols if x not in missing_dropna_cols]
if missing_fix_dtype_cols:
log.log('Warning: can not apply --fix-dtype-cols to {}; columns are missing'.format(', '.join(missing_fix_dtype_cols)))
args.fix_dtype_cols = [x for x in args.fix_dtype_cols if x not in missing_fix_dtype_cols]
if args.exclude_ranges is not None:
args.dropna_cols.extend(['CHR', 'BP'])
args.fix_dtype_cols.extend(['CHR', 'BP'])
if args.fix_dtype_cols is not None:
for col in args.fix_dtype_cols:
if cols_type_map[col] == int:
args.dropna_cols.append(col)
# Check all required columns
args.require_cols = [col.upper() for col in args.require_cols]
missing_cols = []
for col in args.require_cols:
if col == 'EFFECT':
if not any(col in sumstats for col in ['BETA', 'OR', 'LOGODDS', 'Z']):
missing_cols.append('"EFFECT" (e.i. BETA, OR, LOGODDS or Z)')
elif col not in sumstats:
missing_cols.append('"{}"'.format(col))
if missing_cols:
raise(ValueError('--require-cols detected that columns {} are not available in the sumstats file'.format(', '.join(missing_cols))))
# Adjust optional parameters (those that can be ignored if certain columns are missing)
if (args.max_or is not None) and ('OR' not in sumstats):
log.log('Warning: skip --max-or ("OR" column not found in {})'.format(args.sumstats))
args.max_or = None
if (args.maf is not None) and ('FRQ' not in sumstats):
log.log('Warning: skip --maf ("FRQ" column not found in {})'.format(args.sumstats))
args.maf = None
if (args.info is not None) and ('INFO' not in sumstats):
log.log('Warning: skip --info ("INFO" column not found in {})'.format(args.sumstats))
args.info = None
if (args.min_pval is not None) and ('PVAL' not in sumstats):
log.log('Warning: skip --min-pval ("PVAL" column not found in {})'.format(args.sumstats))
args.min_pval = None
if args.update_z_col_from_beta_and_se and (('BETA' not in sumstats) or ('SE' not in sumstats)):
log.log('Warning: can not apply --update-z-col-from-beta-and-se ("OR" column not found in {})'.format(args.sumstats))
args.update_z_col_from_beta_and_se = False
if args.qc_substudies and ('DIRECTION' not in sumstats):
log.log('Warning: can not apply --qc-substudies ("DIRECTION" column not found in {})'.format(args.sumstats))
args.qc_substudies = False
nstudies = None
if args.qc_substudies:
nstudies = np.min(sumstats['DIRECTION'].str.len())
max_nstudies = np.max(sumstats['DIRECTION'].str.len())
if max_nstudies != nstudies:
raise(ValueError('Problem with DIRECTION column: number of studies vary between {} and {}'.format(nstudies, max_nstudies)))
log.log('DIRECTION column indicates a meta-analysis of {} sub-studies. --qc-substudies will exclude variants with ? in {} or more substudies.'.format(nstudies, 1+int(nstudies/2)))
if args.max_or is not None: args.fix_dtype_cols.append('OR')
if args.maf is not None: args.fix_dtype_cols.append('FRQ')
if args.info is not None: args.fix_dtype_cols.append('INFO')
if args.update_z_col_from_beta_and_se: args.fix_dtype_cols.extend(['BETA', 'SE'])
if args.min_pval is not None: args.fix_dtype_cols.append('PVAL')
# Validate that all required columns are present
if (args.just_acgt or args.snps_only or args.drop_strand_ambiguous_snps) and (('A1' not in sumstats) or ('A2' not in sumstats)):
raise(ValueError('A1 and A2 columns are required for --just-acgt, --snps-only, --drop-strand-ambiguous-snps'))
if (args.just_rs_variants) and ('SNP' not in sumstats):
raise(ValueError('SNP column is required --just-rs-variants'))
# Perform QC procedures
if len(args.dropna_cols) > 0:
drop_sumstats(sumstats, log, "missing values in either of '{}' columns".format(args.dropna_cols), dropna_subset=args.dropna_cols)
for col in args.fix_dtype_cols:
if col in sumstats:
log.log('Set column {} dtype to {}'.format(col, cols_type_map[col]))
if cols_type_map[col] in [float, np.float64, int]:
sumstats[col] = pd.to_numeric(sumstats[col], errors='coerce')
if col in args.dropna_cols:
drop_sumstats(sumstats, log, "dtype conversion in {} column".format(col), dropna_subset=[col])
if cols_type_map[col] == int:
sumstats[col] = sumstats[col].astype(int)
else:
sumstats[col] = sumstats[col].astype(cols_type_map[col])
for range in exclude_ranges:
idx = sumstats.index[(sumstats[cols.CHR] == range.chr) & (sumstats[cols.BP] >= range.from_bp) & (sumstats[cols.BP] < range.to_bp)]
drop_sumstats(sumstats, log, 'exclude range {}:{}-{}'.format(range.chr, range.from_bp, range.to_bp), drop_labels=idx)
if args.max_or is not None:
drop_sumstats(sumstats, log, 'OR exceeded threshold {}'.format(args.max_or),
drop_labels=sumstats.index[(sumstats.OR > args.max_or) | (sumstats.OR < (1/args.max_or))])
if args.maf is not None:
drop_sumstats(sumstats, log, 'MAF below threshold {}'.format(args.maf),
drop_labels=sumstats.index[(sumstats.FRQ < args.maf) | (sumstats.FRQ>(1-args.maf))])
if args.info is not None:
drop_sumstats(sumstats, log, 'INFO below threshold {}'.format(args.info),
drop_labels=sumstats.index[sumstats.INFO < args.info])
if args.min_pval is not None:
drop_sumstats(sumstats, log, 'PVAL below threshold {} or above 1.0'.format(args.min_pval),
drop_labels=sumstats.index[(sumstats.PVAL < args.min_pval) | (sumstats.PVAL > 1.0)])
if args.update_z_col_from_beta_and_se:
sumstats['Z'] = np.divide(sumstats.BETA.values, sumstats.SE.values)
if args.snps_only:
drop_sumstats(sumstats, log, '--snps-only',
drop_labels=sumstats.index[(sumstats['A1'].str.len() != 1) | (sumstats['A2'].str.len() != 1)])
if args.just_acgt:
drop_sumstats(sumstats, log, '--just-acgt',
drop_labels=sumstats.index[np.logical_not(sumstats['A1'].isin(BASES)) | np.logical_not(sumstats['A2'].isin(BASES))])
if args.drop_strand_ambiguous_snps:
drop_sumstats(sumstats, log, '--drop-strand-ambiguous-snps',
drop_labels=sumstats.index[(sumstats['A1'].map(str) + sumstats['A2']).isin(['AT', 'TA', 'CG', 'GC']) & (sumstats['A1'].str.len() == 1)])
if args.just_rs_variants:
drop_sumstats(sumstats, log, '--just-rs-variants',
drop_labels=sumstats.index[np.logical_not(sumstats['SNP'].str.match('^rs\d+$'))])
if nstudies is not None:
drop_sumstats(sumstats, log, '--qc-substudies',
drop_labels=sumstats.index[sumstats['DIRECTION'].str.count('\?') > int(nstudies/2)])
fix_columns_order(sumstats).to_csv(args.out, index=False, header=True, sep='\t', na_rep='NA')
log.log("{n} SNPs saved to {f}".format(n=len(sumstats), f=args.out))
describe_sample_size(sumstats, log)
### =================================================================================
### Implementation for parser_zscore
### =================================================================================
def get_str_list_sign(str_list):
return np.array([-1 if e[0]=='-' else 1 for e in list(str_list)], dtype=np.int)
def make_zscore(args, log):
"""
Calculate z-score from p-value column and effect size column
"""
"""
Takes csv files (created with the csv task of this script).
Require columns: SNP, P, and one of the signed summary statistics columns (BETA, OR, Z, LOGODDS).
Creates corresponding mat files which can be used as an input for the conditional fdr model.
Only SNPs from the reference file are considered. Zscores of strand ambiguous SNPs are set to NA.
"""
if args.out == '-': args.out = sys.stdout
check_input_file(args.sumstats)