-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathvarsites2eigenstrat.py
executable file
·76 lines (64 loc) · 1.83 KB
/
varsites2eigenstrat.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
#!/software/bin/python
# Aylwyn Scally 2014
import sys
import getopt
#import os
import os.path
#from math import sqrt
import logging
from logging import error, warning, info, debug, critical
loglevel = logging.WARNING
#os.umask(0002)
def usage():
sys.stderr.write('usage: %s [varsites_file] [-p out_prefix]\n' % (os.path.basename(sys.argv[0])))
# defaults
header = False
outpref = 'eig'
oldsampfmt = False
appendout = False
try:
opts, args = getopt.gnu_getopt(sys.argv[1:], 'p:', ['oldsampfmt', 'append'])
except getopt.GetoptError:
usage()
sys.exit(2)
for (oflag, oarg) in opts:
if oflag == '-p':
outpref = oarg
if oflag == '--append':
appendout = True
if oflag == '--oldsampfmt':
oldsampfmt = True
if len(args) > 1:
fin = open(args[1])
else:
fin = sys.stdin
if appendout:
writemode = 'a'
else:
writemode = 'w'
snpfile = open(outpref + '.snp', writemode)
genofile = open(outpref + '.geno', writemode)
genodict = {'00':'2', '01':'1', '11':'0', '..':'9'}
for line in fin:
if line.startswith('#'):
if line.startswith('#SAMPLES'):
vcfsamps = line.split()[1:]
#indpos = dict([(x, i) for i, line in enumerate(varsamps)])
#print(indpos)
indfile = open(outpref + '.ind', 'w')
for samp in vcfsamps:
if oldsampfmt:
ind = samp.split('/')[-1].split('.')[0] # samples in vcf are mapdir/species_sex_name.bam
indivdat = list(reversed(ind.split('_')))
else: # samples in vcf are species-sex-name
indivdat = list(reversed(samp.split('-')))
indfile.write('\t'.join(indivdat) + '\n') # need to write name sex species for each indiv
continue
tok = line.split()
if tok[0] == 'X':
tok[0] = '23'
snpfile.write('\t'.join(['_'.join(['snp', tok[0], tok[1]]), tok[0], '0.0', tok[1]]) + '\n')
genos = [genodict[x] for x in tok[2].split('-')]
genofile.write(''.join(genos) + '\n')
snpfile.close()
genofile.close()