-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathm2zfast.py
2293 lines (1873 loc) · 74.5 KB
/
m2zfast.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
#===============================================================================
# Copyright (C) 2010 Ryan Welch, Randall Pruim
# edited by F. Uellendahl-Werth ([email protected]) 2021
#
# LocusZoom is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# LocusZoom is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
#===============================================================================
import os
import sys
# Fix path of script to be absolute.
sys.argv[0] = os.path.abspath(sys.argv[0])
# Add the locuszoom bin/ to the PATH.
LZ_ROOT = os.path.abspath(os.path.join(os.path.dirname(sys.argv[0]),".."))
LZ_BIN = os.path.join(LZ_ROOT,"bin")
os.environ['PATH'] = LZ_BIN + os.pathsep + os.environ['PATH']
import time
import re
import tempfile
import platform
import math
import shlex
import json
from m2zutils import *
from FugueFinder import *
from PlinkFinder import *
from LDRegionCache import *
from pquery import *
from glob import glob
from optparse import OptionParser, SUPPRESS_HELP
from subprocess import *
from shutil import move,rmtree
from prettytable import *
from textwrap import fill
from vcf_ld import *
from verboseparser import *
from cStringIO import StringIO
from ordered_set import OrderedSet
# Try importing modules that may not exist on a user's machine.
try:
import gzip
except:
print >> sys.stderr, "Warning: gzip not available on this system"
try:
import bz2
except:
print >> sys.stderr, "Warning: bz2 not available on this system"
try:
import sqlite3
except:
print >> sys.stderr, "Error: your python interpeter is not compiled against sqlite3 (is it really out of date?)"
raise
# Program strings.
M2ZFAST_VERSION = "1.4"
M2ZFAST_DATE = "05/01/2017"
def repeat_char(s,n):
from itertools import repeat
return "".join(repeat(s,n))
def table_pad(lines):
maxw = 0
for l in lines:
maxw = max(len(l),maxw)
pad = 2
print("+" + repeat_char("-",maxw+3) + "+")
for l in lines:
print("| {} {} |".format(l,repeat_char(" ",maxw - len(l))))
print("+" + repeat_char("-",maxw+3) + "+")
M2ZFAST_TITLE = [
"LocusZoom {} ({})".format(M2ZFAST_VERSION,M2ZFAST_DATE),
"Plot regional association results",
"from GWA scans or candidate gene studies"
]
# Program constants.
M2ZFAST_CONF = "conf/m2zfast.conf"
DEFAULT_SNP_FLANK = "200kb"
DEFAULT_GENE_FLANK = "20kb"
RE_SNP_1000G = re.compile("(chr)?([0-9a-zA-z]+):([0-9]+).*")
RE_SNP_RS = re.compile("rs(\d+)")
M2ZCL_FIRST = False
MULTI_CAP = 8;
# Database constants.
SQLITE_SNP_POS = "snp_pos"
SQLITE_REFFLAT = "refFlat"
SQLITE_KNOWNGENE = "knownGene"
SQLITE_GENCODE = "gencode"
SQLITE_SNP_SET = "snp_set"
SQLITE_VAR_ANNOT = "var_annot"
SQLITE_RECOMB_RATE = "recomb_rate"
SQLITE_TRANS = "refsnp_trans"
# Debug flag. Makes all output "more verbose."
_DEBUG = False
class Conf(object):
def __init__(self,conf_file):
self._load(conf_file)
def _load(self,file):
conf_dict = {}
execfile(file,conf_dict)
for k,v in conf_dict.iteritems():
exec "self.%s = v" % str(k)
def getConf(conf_file=M2ZFAST_CONF):
conf_file = find_relative(conf_file)
conf = Conf(conf_file)
return conf
# Get LD file information given parameters.
# Returns a dictionary with 4 elements:
# ped_dir, map_dir, dat_dir, pos_file
def getLDInfo(pop,source,build,ld_db):
if source in ld_db:
node = ld_db[source]
if build in node:
node = node[build]
if pop in node:
# Success! File paths are known for this DB/build/population trio.
return node[pop]
# If we make it here, the supplied combination of source/build/pop is not supported.
return None
def getGWASCat(build,code,gwas_cats):
if build in gwas_cats:
node = gwas_cats[build]
if code in node:
subnode = node[code]
return subnode['file']
return None
# Print a table of all available GWAS catalogs.
def printGWACatalogs(cat_db,build):
print "Available GWAS catalogs for build %s:" % build
print ""
tree = cat_db.get(build)
if tree is None:
print "-- No catalogs available for this build."
return
table = PrettyTable(['Option','Description'])
table.set_field_align('Option','l')
table.set_field_align('Description','l')
exists = False;
for cat_code, cat_tree in tree.iteritems():
table.add_row([
cat_code,
cat_tree['desc']
])
exists = True
if exists:
table.printt()
else:
print "-- No valid options for this build."
def getAllGWACatalogs(cat_db):
table = PrettyTable(['Build','--gwas-cat','Description'])
table.set_field_align('Build','l')
table.set_field_align('Description','l')
table.set_field_align('--gwas-cat','l')
exists = False;
for build in cat_db:
tree = cat_db.get(build)
for cat_code, cat_tree in tree.iteritems():
table.add_row([
build,
cat_code,
cat_tree['desc']
])
exists = True
if exists:
return table.get_string()
else:
return;
# Print a list of all supported population/build/database combinations.
def printSupportedTrios(ld_db):
print "Genotype files available for: "
print getSupportedTrios(ld_db)
def getSupportedTrios(ld_db):
lines = []
for source in ld_db:
lines += ["--source " + source]
for build in ld_db[source]:
lines += [" --build %s" % build]
for pop in ld_db[source][build]:
lines += [" --pop %s" % pop]
lines += [""]
lines.pop()
s = os.linesep.join(lines)
return s
def parse_rargs(arg_list):
args = map(str.strip," ".join(arg_list).split("="))
new_args = {}
try:
for i in xrange(1,len(args)):
k = args[i-1].split()[-1]
vlist = args[i].split()
if len(vlist) == 1:
v = vlist[0]
else:
v = " ".join(vlist[0:-1])
new_args[k] = v
except:
raise Exception, ("Error: something wrong with your plotting arguments. They "
"should all be of the form arg=value, no spaces, value should "
"be quoted if it has spaces. ")
return new_args
#def parse_rargs(args):
# result = []
# for i in xrange(len(args)):
# if args[i] != "=" and args[i].find("=") != -1:
# result.append(args[i])
# elif args[i] == "=":
# result.append(args[i-1] + "=" + args[i + 1])
#
# d = dict()
# for e in result:
# (arg, val) = e.split("=")
# d[arg] = val
# return d
def quoteArgs(m2z_args):
new_args = []
for arg in m2z_args:
test = arg.split("=")
if len(test) == 2:
test[1] = "\"%s\"" % test[1]
new_args.append("=".join(test))
return new_args
# Tests to see if the supplied string is a SNP.
# The SNP should be of the form: rs##### or chr#:pos.
def isSNP(string):
string = str(string)
if RE_SNP_RS.search(string):
return True
elif RE_SNP_1000G.search(string):
return True
else:
return False
def isRSID(string):
p = re.compile(r"^rs(\d+?)$")
if p.search(string) is not None:
return True
else:
return False
# Parse a 1000G SNP into chromosome/position.
# Example: chr4:172274 --> (4,172274)
def parse1000G(snp):
if snp is None:
return None
c = snp.split(":")
if len(c) == 2:
chrom = c[0]
pos = c[1]
if "_" in pos:
pos = pos.split("_")[0]
chrom = chrom2chr(chrom)
try:
pos = long(pos)
except:
return None
return (chrom,pos)
else:
return None
# Pretty string for chromosome/start/stop interval.
def regionString(chr,start,end):
return "chr%s:%s-%s" % (str(chr),str(start),str(end))
# Delete a directory and all files underneath.
def kill_dir(d):
def report_error(function,path,excinfo):
msg = None
if excinfo is not None:
msg = str(excinfo[1])
print >> sys.stderr, "Error: could not remove: %s, message was: %s" % (
path,
msg
)
if os.path.isdir(d):
rmtree(d,onerror=report_error)
else:
print >> sys.stderr, "Error: could not remove %s, not a directory." % d
# Pretty string for a given number of seconds.
def timeString(seconds):
tuple = time.gmtime(seconds)
days = tuple[2] - 1
hours = tuple[3]
mins = tuple[4]
secs = tuple[5]
if sum([days,hours,mins,secs]) == 0:
return "<1s"
else:
string = str(days) + "d"
string += ":" + str(hours) + "h"
string += ":" + str(mins) + "m"
string += ":" + str(secs) + "s"
return string
def transSNP(snp,db_file):
# If this isn't a rs# SNP, it has no translation.
if not isRSID(snp):
return snp
con = sqlite3.connect(db_file)
cur = con.execute("SELECT * FROM %s where rs_orig='%s'" % (SQLITE_TRANS,snp))
new_name = None
while 1:
d = cur.fetchone()
if d is not None:
new_name = d[1]
else:
break
if cur.rowcount > 1:
print >> sys.stderr, "Warning: SNP %s had multiple names in the latest build.." % snp
if new_name is None:
print >> sys.stderr, "Warning: tried to translate SNP %s to latest name in genome build, but it does not exist in the database table.." % str(snp)
elif new_name == snp:
return snp
else:
print >> sys.stderr, "Warning: %s is not the current name in genome build (should be: %s)" % (snp,new_name)
return new_name
# Given a gene, return info for it from the database.
def findGeneInfo(gene,db_file):
con = sqlite3.connect(db_file)
cur = con.execute("SELECT chrom,txStart,txEnd,cdsStart,cdsEnd FROM %s WHERE geneName='%s'" % (SQLITE_REFFLAT,gene))
row = None
while 1:
d = cur.fetchone()
if d is None:
break
# Turn row into dictionary object.
d = dict(zip([i[0] for i in cur.description],d))
# This block of code basically picks out the largest isoform
# as the one we'll use for txstart/txend.
if row is None:
row = d
else:
if abs(row['txEnd']-row['txStart']) < abs(d['txEnd']-d['txStart']):
row = d
# Fix chromosome if possible.
if row is not None:
chrom = chrom2chr(row['chrom'][3:])
if chrom is None:
raise ValueError, "Error: refgene found on non-supported chromosome: %s" % str(row['chrom'])
else:
row['chrom'] = chrom
# Return row, with fixed chromosome (see chrom2chr function.)
return row
class PosLookup:
def __init__(self,db_file):
if not os.path.isfile(db_file):
sys.exit("Error: could not locate SQLite database file: %s. Check conf file setting SQLITE_DB." % db_file)
self.db = sqlite3.connect(db_file)
self.execute = self.db.execute
self.execute("""
CREATE TEMP VIEW snp_pos_trans AS SELECT rs_orig as snp,chr,pos FROM %s p INNER JOIN %s t ON (t.rs_current = p.snp)
""" % (SQLITE_SNP_POS,SQLITE_TRANS))
self.query = """
SELECT snp,chr,pos FROM snp_pos_trans WHERE snp='%s'
"""
def __call__(self,snp):
snp = str(snp)
# If the SNP is a 1000G SNP, it already knows its chrom/pos by definition,
# i.e. the SNP will be chr4:91941.
gcheck = parse1000G(snp)
if gcheck:
return gcheck
cur = self.execute(self.query % snp)
chr = None
pos = None
res = 0
for row in cur:
chr = row[1]
pos = row[2]
res += 1
region = "chr%s:%s" % (chr,pos)
if res > 1:
print >> sys.stderr, "Warning: SNP %s has more than 1 position in database, using: %s" % (str(snp),region)
return (chr,pos)
# Given a list of header elements, determine if col_name is among them.
def findCol(header_elements,col_name):
for i in xrange(len(header_elements)):
if header_elements[i] == col_name:
return i
return None
def is_gzip(file):
b = False
try:
f = gzip.open(file)
f.read(1024)
f.close()
b = True
except:
pass
finally:
f.close()
return b
def is_bz2(file):
try:
f = bz2.BZ2File(file)
except:
return False
try:
f.read(1024)
b = True
except:
b = False
finally:
f.close()
return b
# Given a metal file, this function extracts the region from the file between
# chr/start/end.
def read_metal(metal_file,snp_column,pval_column,no_transform,chr,start,end,db_file,delim):
region = "chr%s:%s-%s" % (str(chr),start,end)
output_file = "temp_metal_%s_%s.txt" % (region.replace(":","_"),tempfile.mktemp(dir=""))
con = sqlite3.connect(db_file)
query = """
SELECT rs_orig as snp,chr,pos
FROM %(snp_table)s p
INNER JOIN %(trans_table)s t on (t.rs_current = p.snp)
WHERE chr = %(chr)i AND pos < %(end)i AND pos > %(start)i
""" % {'snp_table':SQLITE_SNP_POS,'trans_table':SQLITE_TRANS,'chr':chr,'end':end,'start':start}
cur = con.execute(query)
sptable = {}
while 1:
row = cur.fetchone()
if row is not None:
sptable.setdefault(row[0],(int(row[1]),int(row[2])))
else:
break
cur.close()
# Open file for reading. Attempt to determine if file is compressed before opening.
if metal_file == "-":
f = sys.stdin
else:
if is_gzip(metal_file):
try:
f = gzip.open(metal_file); # throws exception if gz not on system
except:
die("Error: gzip is not supported on your system, cannot read --metal file.")
elif is_bz2(metal_file):
try:
f = bz2.BZ2File(metal_file,"rU")
except NameError:
die("Error: bz2 is not supported on your system, cannot read --metal file.")
else:
f = open(metal_file,"rU")
# Find snp column.
metal_header = f.next().split(delim)
metal_header[-1] = metal_header[-1].rstrip()
snp_col = None;
if snp_column is not None:
if type(snp_column) == type(str()):
snp_col = findCol(metal_header,snp_column)
elif type(snp_column) == type(int()):
snp_col = snp_column
else:
die("Error: marker column specified with something other than a string or integer: %s" % str(snp_column))
# After all that, we still couldn't find the snp column. Fail..
if snp_col is None:
msg = "Error: could not locate SNP column in data. You may need to specify "\
"it using --markercol <snp column name>. Your delimiter should also "\
"be specified if it is not a tab by using --delim."
die(msg)
# Find p-value column.
pval_col = None
if pval_column is not None:
if type(pval_column) == type(str()):
pval_col = findCol(metal_header,pval_column)
elif type(pval_column) == type(int()):
pval_col = pval_column
else:
die("Error: pval column specified with something other than a string or integer: %s" % str(pval_column));
# We still couldn't find the p-value column. FAIL!
if pval_col is None:
die("Error: could not locate p-value column in data, column name I'm looking for is: %s. Is your delimiter correct?" % (pval_column))
out = open(output_file,"w")
print >> out, "\t".join(["chr","pos"] + metal_header)
format_str = "\t".join(["%i","%i"] + ["%s" for i in xrange(len(metal_header))])
# P-value check functions
pval_checks = [
lambda x: x.is_finite()
]
if not no_transform:
# If we're transforming to -log10, p-values coming in should be > 0.
pval_checks.append(lambda x: x > 0)
found_in_region = False
found_chrpos = False
min_snp = None
min_pval = decimal.Decimal(1)
marker_count = 0
invalid_pval_count = 0
for line in f:
# Skip blank lines.
if line.rstrip() == "":
continue
e = line.split(delim)
e[-1] = e[-1].rstrip()
snp = e[snp_col]
snp = snp.lower(); # sometimes people put in RS39393 or CHR9:19191...
#here, I want to strip trailing allele specifications from chr9:1313:A:G
if not "rs" in snp:
snpsplit = snp.split(':')
snp = snpsplit[0] + ':' + snpsplit[1]
# Is this a 1000G SNP? If so, we can pull the position from it.
gcheck = parse1000G(snp)
if gcheck:
found_chrpos = True
gchr = gcheck[0]
gpos = gcheck[1]
if gchr == int(chr) and gpos > int(start) and gpos < int(end):
sptable.setdefault(snp,(gchr,gpos))
if snp in sptable:
found_in_region = True
marker_count += 1
# Insert fixed log10 p-value
pval = e[pval_col]
if is_number(pval):
dec_pval = decimal.Decimal(pval)
pval_ok = all((f(dec_pval) for f in pval_checks))
if not pval_ok:
print >> sys.stderr, "Warning: marker %s has invalid p-value: %s, skipping.." % (snp,str(pval))
continue
if dec_pval < min_pval:
min_snp = snp
min_pval = dec_pval;
if not no_transform:
e[pval_col] = str(-1*dec_pval.log10())
(schr,spos) = sptable.get(snp)
e[snp_col] = "chr%i:%i" % (schr,spos)
elements = (schr,spos) + tuple(e)
print >> out, format_str % elements
else:
invalid_pval_count += 1
f.close()
out.close()
if invalid_pval_count > 0:
print >> sys.stderr, "Warning: of %i markers in the region, %i had invalid or missing p-values" % (marker_count,invalid_pval_count)
if found_chrpos:
print >> sys.stderr, ""
print >> sys.stderr, fill("WARNING: your association results file has "
"chr:pos SNP names. Please make sure you have selected the "
"correct genome build by using the --build parameter, or by "
"selecting the appropriate build on the website.")
print >> sys.stderr, ""
return found_in_region, output_file, min_snp
# Given an EPACTS file, this function extracts the region from the file between
# chr/start/end.
def read_epacts(epacts_file,chr,start,end,chr_col,beg_col,end_col,pval_col,no_transform):
conf = getConf()
region = "%s:%s-%s" % (str(chr),start,end)
output_file = "temp_epacts_%s_%s.txt" % (region.replace(":","_"),tempfile.mktemp(dir=""))
chr = int(chr)
start = int(start)
end = int(end)
# Should we just read from STDIN?
if epacts_file == "-":
f = sys.stdin
else:
# Does the EPACTS file have a tabix index with it? If it does, we can use tabix to pull the region out and make
# parsing much faster.
has_index = os.path.isfile(epacts_file + ".tbi")
tabix_path = find_systematic(conf.TABIX_PATH)
if not has_index:
print >> sys.stderr, "Warning: EPACTS file was given, but could not find tabix index for it. " \
"EPACTS should have generated a tabix index for this file."
# Do we have both tabix, and the EPACTS file has a tabix index?
f = None
if has_index and tabix_path is not None:
# Run tabix to pull out our region.
print "Tabix found, using index to extract region.."
proc = subprocess.Popen([tabix_path,"-h",epacts_file,region],stdout=subprocess.PIPE,stderr=subprocess.PIPE)
stdout, stderr = proc.communicate()
# No variants in the region...
if stdout == '':
raise IOError, "Error: no variants in region (%s) when using tabix on EPACTS file" % region
# Unknown error occurred
if stderr != '':
raise IOError, "Error: while grabbing region from EPACTS file, tabix generated an error: \n%s" % stderr
# Setup the input handle for reading.
f = StringIO(stdout)
else:
# Open file for reading. Attempt to determine if file is compressed before opening.
if is_gzip(epacts_file):
try:
f = gzip.open(epacts_file); # throws exception if gz not on system
except:
die("Error: gzip is not supported on your system, cannot read --epacts file.")
elif is_bz2(epacts_file):
try:
f = bz2.BZ2File(epacts_file,"rU")
except NameError:
die("Error: bz2 is not supported on your system, cannot read --epacts file.")
else:
f = open(epacts_file,"rU")
if f is None:
raise IOError, "Unknown error while loading EPACTS file, contact developer with this traceback"
# Find column indices.
epacts_header = f.next().split("\t")
epacts_header[-1] = epacts_header[-1].rstrip()
# Find chr/begin/end columns.
try:
i_chr_col = epacts_header.index(chr_col)
i_begin_col = epacts_header.index(beg_col)
i_end_col = epacts_header.index(end_col)
except:
raise IOError, "Error: could not find chrom/begin/end columns in EPACTS file. Try specifying --epacts-chr-col, --epacts-beg-col, --epacts-end-col."
# Find p-value column.
try:
i_pval_col = epacts_header.index(pval_col)
except:
raise IOError, "Error: could not find p-value column in EPACTS file. Try specifying with --epacts-pval-col."
cols_not_needed = [chr_col,beg_col,end_col,pval_col] + "MARKER_ID NS AC CALLRATE GENOCNT BETA SEBETA STAT MAF SCORE N.CASE N.CTRL AF.CASE AF.CTRL".split()
extra_cols = filter(lambda x: x not in cols_not_needed,epacts_header)
extra_ind = [epacts_header.index(x) for x in extra_cols]
out = open(output_file,"w")
print >> out, "\t".join(['chr','pos','MarkerName','P-value'] + extra_cols)
format_str = "\t".join(['%s','%i','%s','%s'] + ["%s" for _ in xrange(len(extra_cols))])
# Arbitrary arithmetic precision
decimal.getcontext().prec = 8
# P-value check functions
pval_checks = [
lambda x: x.is_finite()
]
if not no_transform:
# If we're transforming to -log10, p-values coming in should be > 0.
pval_checks.append(lambda x: x > 0)
found_in_region = False
min_snp = None
min_pval = decimal.Decimal(1)
skipped_markers = []
marker_count = 0
invalid_pval_count = 0
for line in f:
# Skip blank lines.
if line.rstrip() == "":
continue
e = line.split("\t")
e[-1] = e[-1].rstrip()
marker_name = "chr%s:%s" % (e[i_chr_col],e[i_begin_col])
try:
file_chrom = int(e[i_chr_col])
file_begin = int(e[i_begin_col])
file_end = int(e[i_end_col])
except:
print >> sys.stderr, "Warning: skipping marker %s - could not convert chr/begin/end to integers.." % marker_name
continue
# if file_begin != file_end:
# skipped_markers.append("chr%s:%s-%s" % (file_chrom,file_begin,file_end))
# continue
if file_chrom == chr and file_begin >= start and file_end <= end:
# Did we find a SNP in this region at all?
found_in_region = True
marker_count += 1
pval = e[i_pval_col]
if is_number(pval):
dec_pval = decimal.Decimal(pval)
pval_ok = all((f(dec_pval) for f in pval_checks))
if not pval_ok:
print >> sys.stderr, "Warning: marker %s has invalid p-value: %s, skipping.." % (marker_name,str(pval))
continue
if dec_pval < min_pval:
min_snp = marker_name
min_pval = dec_pval;
if not no_transform:
pval = str(-1*dec_pval.log10())
out_values = tuple([file_chrom,file_begin,marker_name,pval] + [e[x] for x in extra_ind])
print >> out, format_str % out_values
else:
invalid_pval_count += 1
if len(skipped_markers) > 0:
print >> sys.stderr, "Warning: skipped %i markers that did not appear to be SNPs.." % len(skipped_markers)
if invalid_pval_count > 0:
print >> sys.stderr, "Warning: of %i markers in the region, %i had invalid or missing p-values" % (marker_count,invalid_pval_count)
f.close()
out.close()
return found_in_region, output_file, min_snp
# Runs the R script which actually generates the plot.
def runM2Z(metal,metal2zoom_path,ld_files,refsnp,chr,start,end,no_snp_name,verbose,opts,args=""):
conf = getConf()
rscript_path = find_systematic(conf.RSCRIPT_PATH)
if rscript_path is None:
die("Error: could not locate Rscript interpreter. It either needs to be located on your PATH, or set on the configuration file.")
# If no LD file was created, make m2z use the database instead.
refsnp_ld = "NULL"
cond_ld = ""
if (ld_files is None) or (len(ld_files) == 0):
pass
else:
if isinstance(ld_files,type('str')):
refsnp_ld = ld_files
else:
refsnp_ld = ld_files[0]
if len(ld_files) > 1:
cond_ld = "cond_ld=" + ",".join(ld_files[1:])
else:
cond_ld = ""
cond_pos = ""
cond_snps = ""
if opts.condsnps is not None:
cond_pos = "cond_pos=" + ",".join(map(lambda x: x.chrpos,opts.condsnps))
cond_snps = "cond_snps=" + ",".join(map(lambda x: x.snp,opts.condsnps))
if no_snp_name:
refsnpName = r'" "'
else:
refsnpName = refsnp.snp
com = "%s %s metal=%s clobber=F clean=F refsnp=%s refsnpName=%s ld=%s %s %s %s chr=%s start=%s end=%s %s" % (
rscript_path,
metal2zoom_path,
metal,
refsnp.chrpos,
refsnpName,
refsnp_ld,
cond_ld,
cond_pos,
cond_snps,
str(chr),
str(start),
str(end),
args
)
if _DEBUG:
print "DEBUG: locuszoom.R command: %s" % com
#if verbose:
if 1:
proc = Popen(com,shell=True)
else:
proc = Popen(com,shell=True,stdout=PIPE,stderr=PIPE)
proc.wait()
if proc.returncode != 0:
die("Error: locuszoom.R did not complete successfully. Check logs for more information.")
# Attemps to delete a list of files.
# Prints a warning if a file could not be deleted, but does not throw
# an exception.
def cleanup(files):
if _DEBUG:
print "cleanup() called for files: "
for f in files:
print ".. %s" % f
def check_file(f):
return (f is not None) and (f != '') and (f != "NULL") and (f != '/')
files = filter(check_file,files)
for f in files:
try:
os.remove(f)
except:
print >> sys.stderr, "Warning: failed to remove file %s" % f
# Terminates program with a message, and a list of help options.
def die_help(msg,parser):
print >> sys.stderr, msg
parser.print_help()
sys.exit(1)
def safe_int(x):
try:
x = int(x)
except:
x = None
return x
# Reads a "hitspec" or batch run configuration file.
# The file has 6 columns:
# 0 - snp or gene
# 1 - chromosome
# 2 - start
# 3 - stop
# 4 - flank
# 5 - run?
# 6 - m2zargs
#
# Each row is for a SNP or gene, specified in column 0.
# Either chr/start/stop or flank must be specified in each row.
# If neither is specified, a default flank is used (see DEFAULT_*_FLANK variables.)
# Missing values should be entered as "NA"
# Column 5 is either 'yes' or 'no' denoting whether or not this snp/gene should be plotted.
# The final column contains a list of arguments to be passed to locuszoom.R, separated by whitespace.
# The entire file is whitespace delimited.
def readWhitespaceHitList(file,db_file):
if not os.path.isfile(file):
die("Could not open hitspec file for reading - check your path.")
f = open(file,"rU")
h = f.readline()
# This format should have at least 6 columns.
if len(h.split()) < 6:
die("Error: hitspec not formatted properly, see documentation. Should be 6 columns, found: %i " % len(h.split()))
find_pos = PosLookup(db_file)
snplist = []
for line in f:
# Skip blank lines.
if line.strip() == "":
print >> sys.stderr, "Warning: skipping blank line in hitspec file.."
continue
e = line.split()
e[-1] = e[-1].strip()
if len(e) < 6:
print >> sys.stderr, "Error: hitspec line not formatted properly, missing the proper number of columns on line #%i: %s" (lineno,str(line))
continue
if e[5] == 'no'or e[5] == "":
print >> sys.stderr, "Skipping disabled line '%s' in hitspec file.." % " ".join(e)
continue
snp = e[0]
chr = e[1]
start = e[2]
end = e[3]
flank = e[4]
m2z_args = None
if len(e) > 6:
m2z_args = " ".join(e[6:])
if flank != "" and flank != "NA":
flank = convertFlank(flank)
if flank is None:
die("Error: could not parse flank \"%s\", format incorrect." % e[4])
# If they messed up and put "RS" instead of "rs" in the SNP name, fix it.
# The only case in which I can't be sure to fix it is if the gene is RS1.
if snp != "RS1":
snp = re.sub("^RS(\d+)","rs\\1",snp)
if isSNP(snp):
snp = SNP(snp=snp)
snp.tsnp = transSNP(snp.snp,db_file)
(snp.chr,snp.pos) = find_pos(snp.tsnp)
snp.chrpos = "chr%s:%s" % (snp.chr,snp.pos)
if flank is not None and flank != "NA":
if isSNP(snp):
fchr = snp.chr
fpos = snp.pos
try:
chr = int(fchr)
start = fpos - flank