/
arrayworkflow.py
363 lines (306 loc) · 11.4 KB
/
arrayworkflow.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
import parsegenotypes
import sys, getopt
import argparse
import glob
homedir = '/srv/gs1/projects/snyder/mark/genotypes/'
names1KG = ['CEUlowcov','YRIlowcov','CHBJPTlowcov','YRItrio', 'CEUtrio']
homedirnames = map(lambda x: homedir+x, names1KG)
vcffiles = ['../1000GenomesData/CEU.low_coverage.2010_09.genotypes.vcf','../1000GenomesData/YRI.low_coverage.2010_09.genotypes.vcf', '../1000GenomesData/CHBJPT.low_coverage.2010_09.genotypes.vcf',
'../1000GenomesData/YRI.trio.2010_09.genotypes.vcf', '../1000GenomesData/CEU.trio.2010_09.genotypes.vcf']
def getarraysnps(report):
print report
file = open(report)
lines = file.readlines()
file.close()
#header = "SNP Name,Sample ID,Allele1 - Top,Allele2 - Top,GC Score,Allele1 - Plus,Allele2 - Plus,Chr,Position,SNP,Theta,R,X,Y,X Raw,Y Raw,B Allele Freq"
#header = "SNP Name,Sample ID,Allele1 - Top,Allele2 - Top,GC Score,Allele1 - Forward,Allele2 - Forward,Allele1 - Plus,Allele2 - Plus,Chr,Position,GT Score,Cluster Sep,SNP,X,Y,X Raw,Y Raw,B Allele,Freq,Log R Ratio,CNV Value,CNV Confidence"
#h = header.split(',')
#h = ['SNP Name', 'Sample ID', 'Allele1 - Top', 'Allele2 - Top', 'GC Score', 'Allele1 - Forward', 'Allele2 - Forward', 'Allele1 - Plus', 'Allele2 - Plus', 'Chr', 'Position', 'GT Score', 'Cluster Sep', 'SNP', 'X', 'Y', 'X Raw', 'Y Raw', 'B Allele Freq', 'Log R Ratio', 'CNV Value', 'CNV Confidence', 'Top Genomic Sequence', 'Plus/Minus Strand', 'Theta', 'R\r\n']
h = 'SNP Name\tSample ID\tAllele1 - Top\tAllele2 - Top\tGC Score\tSNP Index\tAllele1 - Forward\tAllele2 - Forward\tAllele1 - AB\tAllele2 - AB\tAllele1 - Plus\tAllele2 - Plus\tChr\tPosition\tSNP\tILMN Strand\tTop Genomic Sequence\tPlus/Minus Strand\tTheta\tR\tX\tY\tX Raw\tY Raw\tB Allele Freq\r\n'.split('\t')
snpi = h.index("SNP")
chri = h.index("Chr")
posi = h.index("Position")
Yi = h.index("Y")
Xi = h.index("X")
snplist = []
ref = {}
alt = {}
freq = {}
for l in lines:
t = l.split('\t')
try:
if t[chri] not in map(lambda x: str(x), range(1,23)):
continue
else:
snppos = 'chr'+t[chri]+'pos'+t[posi]
snplist.append(snppos)
ref[snppos] = t[snpi].split('/')[0][1]
alt[snppos] = t[snpi].split('/')[1][0]
freq[snppos] = float(t[Yi])/(float(t[Yi])+float(t[Xi]))
except:
continue
glob.dump(snplist, report+'snps')
glob.dump(ref, report+'RefT')
glob.dump(alt, report+'AltT')
glob.dump(freq, report+'freq')
### get genotype
class Genotypes:
def __init__(self, name, ext = "Geno"):
self.name = name
self.genofile = open('./' + name + ext)
self.__genolen__()
def __genolen__(self):
l = self.genofile.readline()
self.ln = len(l.split(','))
self.genofile.seek(0)
def getsnpgenos(genos, filestruc, chosenSNPs, incarray = 0):
lines = filestruc.genofile.readlines()
snppos = map(lambda x: x.split('\t')[0], lines[1:])
inboth = set(snppos) & set(chosenSNPs)
notingeno = set(filter(lambda x: x not in inboth, chosenSNPs))
try:
genos['lines'] = genos['lines'] +lines[0].split('\t')[1].split(',')
except KeyError:
genos['lines'] = lines[0].split('\t')[1].split(',')
print("Number of Lines in Genotype:" + str(len(lines)))
for l in lines[1:]:
t = l.split('\t')
snp = t[0]
if snp in inboth:
try:
genos[snp] = genos[snp].strip(',') + ','+t[1].strip('\n')
except KeyError:
genos[snp] = t[1].strip('\n')
if incarray == 0:
for s in notingeno:
try:
genos[s] = genos[s].strip(',') + ','+('0,' * filestruc.ln)
except KeyError:
genos[s] = '0,' * filestruc.ln
glob.dump(genos, 'tempgenos')
return genos
def combinegenos(names, chosenSNPs, out = 'combGenosfile', incarray = 0):
genos = {}
if type(names) is str:
f = Genotypes(names)
genos = getsnpgenos(genos, f, chosenSNPs, incarray)
if type(names) is list:
files = map(lambda x: Genotypes(x), names)
genos = reduce(lambda x,y: getsnpgenos(x, y, chosenSNPs, incarray), [genos]+files)
glob.dump(genos, out+'.json')
genos['lines'] = map(lambda x: x.strip('\n'), genos['lines'])
output = open(out, 'w')
linenames = reduce(lambda x,y: x +',' + y, genos['lines'])
output.write('\t' + linenames +'\n')
for g in genos.keys():
if g != 'lines':
output.write(g + '\t' + genos[g].strip(',') + '\n')
def interset(genotypes):
"""the combine genos stuff is predicated on the idea that if a SNP isn't mentioned
it's genotype is 0
in reality, if the snps are genotypes as part of different projects (like 1KG vs. HapMap)
then if a SNP is not present it may be because it was never tested
This functions finds the intersecting set of snps between two genotype files, which can then be
used as part of the "chosen SNPs" to select the ultimate final combined Genos file
"""
snplist = map(lambda x: getsnps(x), genotypes)
print len(snplist)
ineverything = reduce(lambda x,y: set(x) & set(y), snplist)
return ineverything
def getsnps(genotypefile):
f = open(genotypefile)
lines = f.readlines()
print len(lines)
f.close()
snppos = map(lambda x: x.split('\t')[0], lines[1:])
return snppos
def intercomb(genotypes, out = 'intercomb'):
"""the purpose of this function is to do a simple genotype file combine, based on select snps, the
assumption is that the files are from two different categories of genotyping projects, so the snps
used are an output of the interset() function
"""
snps = interset(genotypes)
combinedgenos = {}
combinedgenos['lines'] = []
for g in genotypes:
lines = open(g).readlines()
combinedgenos['lines'].append(lines[0].split('\t')[1])
for l in lines[1:]:
t = l.split('\t')
snp = t[0]
if snp in snps:
try:
combinedgenos[snp] = combinedgenos[snp].strip(',') + ','+t[1].strip('\n')
except KeyError:
combinedgenos[snp] = t[1].strip('\n')
output = open(out, 'w')
combinedgenos['lines'] = map(lambda x: x.strip('\n'), combinedgenos['lines'])
linenames = reduce(lambda x,y: x +',' + y, combinedgenos['lines'])
output.write('\t' +linenames + '\n')
for g in combinedgenos.keys():
if g != 'lines':
output.write(g + '\t' + combinedgenos[g].strip(',') + '\n')
def processhapmap():
print "parsing hapmap genotypes chrom files"
parsegenotypes.parsehapmap()
print "now filtering SNPs"
b = parsegenotypes.filterSNPs('../genotypes/hapmap')
print "{0} SNPs filtered out".format(len(b))
[flips, errors] = parsegenotypes.checkRef('../genotypes/hapmap')
print "{0} flips and {1} errors".format(len(flips),len(errors))
#flips = glob.json('../genotypes/hapmapflips')
#errors = glob.json('../genotypes/hapmaperrors')
parsegenotypes.flipGeno('hapmapGeno', flips, errors)
def processgenotypes():
"""parse genotype files and flip them around according to hg19
"""
for i, n in enumerate(homedirnames):
parsegenotypes.parse1KGvcf(vcffiles[i], names1KG[i])
b = parsegenotypes.filterSNPs(names1KG[i])
print "{0} SNPs filtered out".format(len(b))
c = parsegenotypes.checkRef(n)
print "{0} errors and {1} flipped".format(len(c[1]),len(c[0]))
#parsegenotypes.corrRef(c[0], n)
parsegenotypes.flipGeno(n+'Geno', c[0], c[1])
def getpoollines(genofile, pool, out = "poolgenotype"):
output = open(out, 'w')
pool = glob.json(pool)
g = open(genofile)
lines = g.readlines()
g.close()
linenames = lines[0]
ln = linenames.split('\t')[1].split(',')
ln = map(lambda x: x.strip('\n'), ln)
print pool
poolinds = map(lambda x: ln.index(x), pool)
nl = [ln[i] for i in poolinds]
newlinenames = ','
newlinenames = reduce(lambda x,y: x + ',' + y, nl)
output.write(newlinenames + '\n')
for l in lines[1:]:
t = l.split('\t')
gs = t[1].split(',')
gs = map(lambda x: x.strip('\n'), gs)
if len(filter(lambda x: int(x)!=0, gs)) >0:
newl = t[0] + ','
newg = []
for i in range(0, len(gs)):
if i in poolinds:
newg.append(gs[i])
newg = reduce(lambda x,y: x + ',' + y, newg)
newl = newl + newg + '\n'
output.write(newl)
class Array:
def __init__(self, name):
self.name = name
def makedic(self):
afile = open(self.name+'Rinput')
alines = afile.readlines()
afile.close()
self.dic = {}
for l in alines[1:]:
self.dic[l.split('\t')[0]] = float(l.split('\t')[1].strip('\n'))
self.snps = self.dic.keys()
def mergearraypool(poolgenotypefile, uniformarray, Goutput = 'G.Rinput', *arrays):
pfile = open(poolgenotypefile)
plines = pfile.readlines()
pfile.close()
uarray = Array(uniformarray)
uarray.makedic()
uarraysnps = set(uarray.snps)
arrayobj = map(lambda x: Array(x), arrays)
map(lambda x: x.makedic(), arrayobj)
allarrays = [uarray]
allarrays.extend(arrayobj)
snpsincommon = reduce(lambda x,y: set(x.snps) & set(y.snps), allarrays)
print len(snpsincommon)
output = open(Goutput,'w')
output.write(plines[0])
for g in plines[1:]:
if g.split(',')[0] in snpsincommon:
output.write(g)
output = open(uniformarray+".Uarray.poolRinput", 'w')
for g in plines[1:]:
snp = g.split(',')[0]
if snp in snpsincommon:
output.write(snp +',' + str(uarray.dic[snp]) + '\n')
for a in arrayobj:
a.makedic()
output = open(a.name+'.poolRinput', 'w')
for g in plines[1:]:
snp = g.split(',')[0]
if snp in snpsincommon:
#try:
output.write(snp + ',' + str(a.dic[snp]) + '\n')
#except KeyError:
# "Snp not in this array"
def main(argv):
opts, args = getopt.getopt(argv,"a:ghc:i",["report=", "genonames="])
for opt, arg in opts:
if opt == '-a':
report = arg
print "processing array, getting snps {0}".format(report)
getarraysnps(arg)
[f, e] = parsegenotypes.checkRef(report)
parsegenotypes.flipArray(report, f)
parsegenotypes.filterzeros(report)
parsegenotypes.printtabarray(report)
elif opt == '-g':
processgenotypes()
elif opt == '-h':
processhapmap()
elif opt == '-c':
snps = glob.json('Array251Msnps')
if arg == '':
genofiles = names1KG
else:
genofiles = arg
combinegenos(genofiles, snps)
elif opt == "-i":
genofiles = names.append('hapmap')
if __name__ == "__main__":
#args = sys.argv[1:]
#if len(args) > 0:
# main(args)
parser = argparse.ArgumentParser()
parser.add_argument('-a', help='Extract snps from this Array')
parser.add_argument('-g', action='store_true')
parser.add_argument('-hapmap', action='store_true')
parser.add_argument('-init1KG', action='store_true')
parser.add_argument('-inithapmap', action='store_true')
parser.add_argument('-int', action='store_true')
parser.add_argument('-pool', action='store_true')
parser.add_argument('-merge', action='store_true')
parser.add_argument('-i')
args = parser.parse_args()
print args
if args.a:
print "processing array, getting snps {0}".format(args.a)
report = args.a
getarraysnps(report)
[f, e] = parsegenotypes.checkRef(report)
parsegenotypes.flipArray(report, f, e)
parsegenotypes.filterzeros(report)
parsegenotypes.printtabarray(report)
if args.g:
processgenotypes()
if args.hapmap:
processhapmap()
if args.init1KG:
#snps = glob.json('25M1.1snps')
snps = glob.json('MKReportbySNP1.txtsnps')
#combinegenos(names1KG, snps, 'Genos1kgArray25M')
combinegenos(names1KG, snps, 'Genos1kgArrayOmni')
if args.inithapmap:
snps = glob.json('Array25M1snps')
combinegenos('hapmap', snps, 'hapmapGenosArray25M', 1)
if args.pool:
#getpoollines('intercomb','pool1', 'pool1genotype')
# new arrays
#getpoollines('Genos1kgArray25M', 'pool1', 'pool1genotype')
#old arrays
getpoollines('Genos1kgArrayOmni', 'pool1', 'pool1genotypeOmni')
if args.merge:
mergearraypool('pool1genotypeOmni', 'MKReportbySNP1.txt', 'Gomni.Rinput', 'MKReportbySNP3.txt')
if args.int:
intercomb(['Genos1kgArray25M', 'hapmapGenosArray25M'])