-
Notifications
You must be signed in to change notification settings - Fork 3
/
snpload.py
executable file
·444 lines (393 loc) · 12.3 KB
/
snpload.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
import re
import os
import zipfile
import gzip
from shutil import copyfile
import shutil
import uuid
vcf_verbose = True
#fname: filename
#crs: chromosomes to read
def load(fname, crs=[], vcf_sample='', force_build=0):
snpset = {}
meta = {}
meta['build'] = 0
meta['format'] = ''
meta['total'] = 0
vcf_idx = 0
try:
tmpfile = preprocess_file(fname)
(build, fmt) = detect_file_format(tmpfile)
if fmt == 'vcf':
idxs = get_vcf_sample_idx(tmpfile, vcf_sample)
#print(idxs)
if len(idxs) > 0:
vcf_idx = idxs[0]
if vcf_verbose:
print('VCF sample idx:', vcf_idx)
except FileNotFoundError:
print("File not found!")
return (snpset, meta)
except:
print("FORMAT AUTODETECT FAILED!!!!!")
return (snpset, meta)
if force_build:
build = force_build
meta['build'] = build
meta['format'] = fmt
meta['total'] = 0
if fmt == '23andme':
importer = import_line_23andme
elif fmt == 'ancestry':
importer = import_line_ancestry
elif fmt == 'ftdna':
importer = import_line_ftdna
elif fmt == 'myheritage':
importer = import_line_ftdna #same
elif fmt == 'vcf':
importer = import_line_vcf
else:
print("Undetected format: build%d, %s"%(build, fmt))
meta['total'] = 0
return (snpset, meta)
n_total = 0
try:
with open(tmpfile) as f:
for line in f:
try:
(snp, pos, cr, gen) = importer(line, build, vcf_idx)
except RuntimeError:
continue
if gen[0] == "-":
continue
if cr == "0":
continue
if cr == "YAUTO":
cr = "XY" #???
if cr == "Y":
if len(gen) > 1:
snp['gen'] = gen[0]
if cr == "MT":
if len(gen) > 1:
snp['gen'] = gen[0]
snp['gen'] = ''.join(sorted(snp['gen']))
if cr in crs or len(crs) == 0:
if cr not in snpset:
snpset[cr] = {}
#if pos in snpset[cr]:
# if not snp['id'].startswith("i"):
# #print("dup ", snpset[cr][pos], snp)
# pass
snpset[cr][pos]=snp
n_total+=1
continue
except UnicodeDecodeError:
return (snpset, meta)
finally:
os.remove(tmpfile)
if build != 36 and build != 37 and build != 38:
print("BUILD NOT SUPPPORTED!!!!! = %d"%build)
meta['total'] = n_total
return (snpset, meta)
def import_line_23andme(line, build, idx):
if len(line) < 7:
raise RuntimeError()
if line.startswith('#'):
raise RuntimeError()
sline = line.split()
if len(sline) < 4:
raise RuntimeError()
cr = sline[1];
pos = sline[2];
gen = sline[3];
snp = {'id': sline[0],
'cr': cr,
'gen': gen }
if build == 36:
snp['b36'] = pos
elif build == 37:
snp['b37'] = pos
elif build == 38:
snp['b38'] = pos
return (snp, pos, cr, gen)
def import_line_ancestry(line, build, idx):
if 'allele1' in line and 'allele2' in line:
raise RuntimeError()
if len(line) < 7:
raise RuntimeError()
if line.startswith('#'):
raise RuntimeError()
sline = line.split()
if len(sline) < 4:
raise RuntimeError()
cr = sline[1];
if cr == '23':
cr = 'X'
elif cr == '24':
cr = 'Y'
elif cr == '25':
cr = 'YAUTO'
elif cr == '26':
cr = 'MT'
pos = sline[2];
gen = sline[3]+sline[4];
snp = {'id': sline[0],
'cr': cr,
'gen': gen }
if build == 36:
snp['b36'] = pos
elif build == 37:
snp['b37'] = pos
elif build == 38:
snp['b38'] = pos
return (snp, pos, cr, gen)
def import_line_ftdna(line, build, idx):
if len(line) < 7:
raise RuntimeError()
if line.startswith('#'):
raise RuntimeError()
if line.startswith('RSID'):
raise RuntimeError()
sline = line.split(',')
if len(sline) < 4:
raise RuntimeError()
cr = sline[1].strip('"');
pos = sline[2].strip('"');
gen = sline[3].strip().strip('"');
snp = {'id': sline[0].strip('"'),
'cr': cr,
'gen': gen }
if build == 36:
snp['b36'] = pos
elif build == 37:
snp['b37'] = pos
elif build == 38:
snp['b38'] = pos
return (snp, pos, cr, gen)
def import_line_vcf(line, build, idx):
if len(line) < 7:
raise RuntimeError()
if line.startswith('#'):
raise RuntimeError()
sline = line.split()
if len(sline) < 4:
raise RuntimeError()
cr = sline[0];
if cr == 'chrY':
cr = 'Y'
elif cr == 'chrMT':
cr = 'MT'
elif cr == 'M':
cr = 'MT'
elif cr == 'chrM':
cr = 'MT'
else:
cr.replace('chr','')
pos = sline[1]
ref = sline[3]
alt = sline[4]
alls = [ref]
alls+=alt.split(',')
#skip indel
if len(ref) > 1 or len(alt) > 1:
raise RuntimeError()
#GT index from format string
form = sline[8]
gti=0
for i,gtstr in enumerate(form.split(':')):
if gtstr == 'GT':
gti=i
s = sline[9+idx].split(':')
#print(pos, alls, gti, s)
if s[gti][0] == '.':
raise RuntimeError()
g = alls[int(s[gti][0])]
#print(pos, alls, g)
gen = g+g;
snp = {'id': sline[2],
'cr': cr,
'gen': gen }
if build == 36:
snp['b36'] = pos
elif build == 37:
snp['b37'] = pos
elif build == 38:
snp['b38'] = pos
return (snp, pos, cr, gen)
def get_vcf_sample_idx(fname, sname):
lc=0
idxs=[]
with open(fname) as f:
for line in f:
#print(line)
if line.startswith('#CHROM'):
samples=''
for i, sam in enumerate(line.split('\t')[9:]):
if re.search(sname, sam):
idxs.append(i)
samples+=sam+' '
if vcf_verbose:
print('VCF samples:', samples)
break
lc+=1
if lc > 10000:
break
return idxs
def detect_file_format(fname):
lc=0
build=0
fmt=''
with open(fname) as f:
for line in f:
lc += 1
if lc > 4000:
break
if fmt != '' and build != 0:
break
if line.startswith('#'):
if fmt != 'vcf' and 'build ' in line:
build = int(re.findall(r'build \d+', line)[0].split()[1])
if fmt != 'vcf' and 'Build: ' in line:
build = int(re.findall(r'Build: \d+', line)[0].split()[1])
if "23andMe" in line:
fmt = '23andme'
if "AncestryDNA" in line:
fmt = 'ancestry'
if "MyHeritage" in line:
fmt = 'myheritage'
if "##fileformat=VCF" in line:
fmt = 'vcf'
if "##reference" in line:
#hacky autodetect may work for many files
if '37' in line:
build = 37
if '38' in line:
build = 38
if 'rCRS' in line:
build = 38
continue
if lc == 1 and line.startswith('RSID'):
fmt = 'ftdna'
#autodetect build by some rs ids if needed
if build == 0:
sline=line.split(',')
if sline[0].strip('"') == 'rs6681049' and sline[2].strip('"') == '800007':
build = 37
if sline[0].strip('"') == 'rs6681049' and sline[2].strip('"') == '789870':
build = 36
if build == 0:
sline=line.split(',')
if sline[0].strip('"') == 'rs3131972' and sline[2].strip('"') == '752721':
build = 37
if sline[0].strip('"') == 'rs3131972' and sline[2].strip('"') == '742584':
build = 36
if build == 0:
sline=line.split(',')
if sline[0].strip('"') == 'rs3934834' and sline[2].strip('"') == '1005806':
build = 37
if sline[0].strip('"') == 'rs3934834' and sline[2].strip('"') == '995669':
build = 36
if build == 0:
sline=line.split(',')
if sline[0].strip('"') == 'rs11260549' and sline[2].strip('"') == '1121794':
build = 37
if sline[0].strip('"') == 'rs11260549' and sline[2].strip('"') == '1111657':
build = 36
#print("Detected format: build%d, %s"%(build, fmt))
return (build, fmt)
def is_gz_file(fname):
with open(fname, 'rb') as f:
return f.read(2) == b'\x1f\x8b'
def preprocess_file(fname):
#TODO make real temp file
tmpfile = str(uuid.uuid4())
if zipfile.is_zipfile(fname):
with zipfile.ZipFile(fname) as z:
zfname = z.namelist()[0]
#print('ZIP input file: %s'%zfname)
with z.open(zfname) as zf, open(tmpfile, 'wb') as f:
shutil.copyfileobj(zf, f)
elif is_gz_file(fname):
#print('gzip input file: %s'%fname)
with gzip.open(fname, 'rb') as f_in:
with open(tmpfile, 'wb') as f_out:
shutil.copyfileobj(f_in, f_out)
else:
#print('ASCII input file: %s'%fname)
shutil.copyfile(fname, tmpfile);
return tmpfile
def save(fname, snpset, build=37):
b3x='b%d'%build
with open(fname, 'w') as f:
print('# This data file generated by Snipsa, not by 23andMe', file = f)
print('# ', file = f)
print('# ', file = f)
print('# ', file = f)
print('# ', file = f)
print('# ', file = f)
print('# ', file = f)
print('# ', file = f)
print('# ', file = f)
print('# ', file = f)
print('# ', file = f)
print('# We are using reference human assembly build %d '%build, file = f)
print('# ', file = f)
print('# ', file = f)
print('# ', file = f)
print('# ', file = f)
print('# More information on reference human assembly build %d '%build, file = f)
print('# ', file = f)
print('# ', file = f)
print('# rsid chromosome position genotype', file = f)
for cr in snpset:
for i in snpset[cr]:
snp = snpset[cr][i]
if snp[b3x] == '0':
print('TODO:', snp)
continue
if len(snp['gen']) == 1:
snp['gen'] += snp['gen']
row = '%s\t%s\t%s\t%s'%(snp['id'], cr, snp[b3x], snp['gen'])
print(row, file = f)
def index_by_rs(snpset):
snpseto = {}
for cr in snpset:
if cr not in snpseto:
snpseto[cr] = {}
for snp in snpset[cr]:
snpseto[cr][ snpset[cr][snp]['id'] ] = snpset[cr][snp]
return snpseto
def show_stats(snpset):
n_total = 0
for cr in snpset:
n_smps = len(snpset[cr])
print("Chromosome %s: %s SNPs"%(cr, n_smps))
n_total += n_smps
print("Total SNPs: %d"%n_total)
def allele_sort_key(al):
if len(al) == 1:
key = list('_'+al)
else:
key = list(al)
if key[0] == 'D':
key[0] = 'U'
if key[0] == 'I':
key[0] = 'V'
if key[1] == 'D':
key[1] = 'U'
if key[1] == 'I':
key[1] = 'V'
return ''.join(key)
def show_gts(snpset):
d={}
for cr in snpset:
for snp in snpset[cr]:
gt = snpset[cr][snp]['gen']
if gt not in d:
d[gt] = 1
else:
d[gt] += 1
#print(d)
print("Total alleles found:")
for al in sorted(d, key=allele_sort_key):
print("%s: %d"%(al, d[al]))