4
|
1 '''Takes tab-delimited SNP tables from user input and merges them into one.'''
|
|
2
|
|
3 import sys
|
|
4 files = []
|
|
5 filenames = []
|
|
6
|
|
7 try:
|
|
8 output = open(sys.argv[1], "w")
|
|
9 output.write('Position\tReference')
|
|
10 except:
|
|
11 exit("No output file given or unable to open output file.")
|
|
12 for name in sys.argv[2:]:
|
|
13 try:
|
|
14 files.append(open(name, "rU"))
|
|
15 except:
|
|
16 continue
|
|
17
|
|
18 # Fetch headers and print them to output file;
|
7
|
19 headers = [File.readline()[:-1].split('\t')[1:] for File in files]
|
|
20 columns = [len(strains[1:]) for strains in headers]
|
|
21 output.write('\t'.join(['Position']+[headers[0][0]]+[a for b in headers for a in b[1:]]))
|
|
22 ##headers = [header.readline()[:-1].split('\t')[2:] for header in files]
|
|
23 ##columns = [len(strains) for strains in headers]
|
|
24 ##for strain in [a for b in headers for a in b]:
|
|
25 ## output.write('\t'+strain)
|
|
26 ## output.flush()
|
4
|
27
|
|
28 file_active = [True]*len(files)
|
|
29 snps = [row.readline()[:-1].split('\t') for row in files]
|
|
30
|
|
31 while True in file_active:
|
|
32 for h in range(0,len(snps)):
|
|
33 if file_active[h]:
|
|
34 cur_pos = [h]
|
|
35 lowest = int(snps[h][0])
|
|
36 break
|
|
37 i = 1
|
|
38
|
|
39 # Determine lowest position
|
|
40 while i < len(snps):
|
|
41 if int(snps[i][0]) < lowest and file_active[i]:
|
|
42 lowest = int(snps[i][0])
|
|
43 cur_pos = [i]
|
|
44 elif int(snps[i][0]) == lowest:
|
|
45 cur_pos.append(i)
|
|
46 i+=1
|
|
47
|
|
48 # Check if all SNPs sharing a position have the same reference base, exit with message otherwise;
|
|
49 if len(cur_pos) > 1:
|
|
50 ref_base = snps[cur_pos[0]][1].lower()
|
|
51 for j in cur_pos[1:]:
|
|
52 if snps[j][1].lower() != ref_base:
|
|
53 error = '\nError: Reference bases not the same for position %s, present in following files:' % lowest
|
|
54 for k in cur_pos:
|
|
55 error += ' '+filenames[k]
|
|
56 exit(error+'.')
|
|
57
|
|
58 # Write line to output file containing position, ref base and snps/empty cells;
|
|
59 output.write('\n'+snps[cur_pos[0]][0]+'\t'+snps[cur_pos[0]][1].lower())
|
|
60 for l,row in enumerate(snps):
|
|
61 if l in cur_pos:
|
|
62 for snp in row[2:]:
|
|
63 output.write('\t'+snp)
|
|
64 else:
|
|
65 output.write('\t'*columns[l])
|
|
66
|
|
67 # Read new line in files that had snp at current position;
|
|
68 for m in cur_pos:
|
|
69 line = files[m].readline()
|
|
70 if line == '': file_active[m] = False
|
|
71 else:
|
|
72 snps[m] = line.split('\t')
|
|
73 snps[m][-1] = snps[m][-1].rstrip()# Remove newline character at end of line;
|
|
74
|
|
75 for it in files: it.close()
|
|
76 output.close()
|