-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathTaxaAnalysis.py
More file actions
398 lines (290 loc) · 9.32 KB
/
TaxaAnalysis.py
File metadata and controls
398 lines (290 loc) · 9.32 KB
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
#! python
#TaxaAnalysis.py
## Version 1.1
## This program takes a taxonomy file, a shared file, level of classification, and output file
## on the command line. One current limitation is that the number of OTUs in the shared file
## and the taxonomy file must match. The other problem is that at the moment there is no
## relative abundance option and only the total reads are returned. I will work on this for
## later iterations. The program returns a tab text file that can be viewed in excel, etc.
## Examples of the command line entry:
## python TaxaAnalysis.py test.taxonomy test.shared 2 uneven=y taxa=True y output.txt
## python TaxaAnalysis.py test.taxonomy test.shared 6 uneven=y taxa=False n output.txt
## For this program the tax levels are as follows:
## 1 = Domain
## 2 = Phylum
## 3 = Class
## 4 = Order
## 5 = Family
## 6 = Genus
## For this program you can output relative abundance or total reads.
## using y in the command line will create a relative abundance table.
## using n in the command line will create a total read count table.
#################### Need to create unequal files ability.
# Load the needed modules for the program
import sys, re
# need to use sys to get command line input can do len(sys.argv) and str(sys.argv)
# also have to use re to get the regex library
# get argument from command line
def commandLine():
commands = sys.argv
taxFile = commands[1]
sharedFile = commands[2]
taxLevel = commands[3]
uneven = commands[4]
taxaPrint = commands[5]
RelAbund = commands[6]
outputFile = commands[7]
return taxFile, taxLevel, sharedFile, uneven, taxaPrint, RelAbund, outputFile
# use argument to read in file and seperate out each respective taxonomy component
# with header stored seperate
def seperateTaxFile(taxa):
infile = open(taxa, 'r')
x = 0
header = []
OTU = []
total = []
taxonomy = []
for line in infile:
if x == 0:
for i in line.split("\t"):
header.append(i)
else:
OTUs, totals, taxonomies = line.split("\t")
unit = OTUs.strip('\n')
OTU.append(unit)
total.append(totals)
taxonomy.append(taxonomies)
x = x + 1
infile.close()
return header, OTU, total, taxonomy
def equalizeData(taxonomy, OTU, shared):
taxaFile = {}
NewTaxonomy = []
NewOTU = []
OTUList = []
x = 0
for i in OTU:
taxaFile[i] = taxonomy[x]
x = x + 1
x = 0
infile = open(shared, 'r')
for line in infile:
for i in line.split("\t"):
if x == 0:
unit = i.strip('\n')
OTUList.append(unit)
x = x + 1
infile.close()
for j in OTU:
for k in OTUList:
if j == k:
NewTaxonomy.append(taxaFile[j])
NewOTU.append(j)
return NewTaxonomy, NewOTU
# Use split to seperate into taxonomic groups
def splitTaxonomy(taxonomy, taxLevel):
# Create list file to hold tax classifications
domain = []
phylum = []
BClass = []
BOrder = []
family = []
genus = []
for line in taxonomy:
x = 1
for i in line.split(";"):
if x == 1:
domain.append(i)
elif x == 2:
phylum.append(i)
elif x == 3:
BClass.append(i)
elif x == 4:
BOrder.append(i)
elif x == 5:
family.append(i)
elif x == 6:
genus.append(i)
x = x + 1
# Generate the table to return based on user defined original input
taxSelection = eval(taxLevel)
if taxSelection == 1:
return domain
elif taxSelection == 2:
return phylum
elif taxSelection == 3:
return BClass
elif taxSelection == 4:
return BOrder
elif taxSelection == 5:
return family
if taxSelection == 6:
return genus
# regex to only take the characters
def removeNumbers(result):
table = []
characterRegex = re.compile(r'''\w+''', re.VERBOSE)
for i in result:
mo = characterRegex.search(i)
table.append(mo.group())
return table
# need to recombine all the components back together
def taxaKey(OTU, table):
tableKey = []
for i in range(len(table)):
tableKey.append((OTU[i], table[i]))
return tableKey
# output a file as named by user (Only does taxonomy file, unused function at the moment)
# Want to make this as an option in the workflow entry
def createOutput(header, OTU, total, table):
temptable = []
outfile = open("taxonomyKey.txt", 'w')
x = 0
for i in range(len(table)):
if x == 0:
print("{0}\t{1}\t{2}".format(header[0], header[1], header[2]), end ='', file = outfile)
print("{0}\t{1}\t{2}".format(OTU[i], total[i], table[i]), end ='\n', file = outfile)
elif x > 0 and x < len(table):
print("{0}\t{1}\t{2}".format(OTU[i], total[i], table[i]), end ='\n', file = outfile)
elif x == len(table):
print("{0}\t{1}\t{2}".format(OTU[i], total[i], table[i]), end ='', file = outfile)
x = x + 1
outfile.close()
# A function to generate a list of all groups in the user defined taxonomic level
def generateUniqueTax(table):
uniqueTable = []
for i in table:
if i in uniqueTable:
uniqueTable = uniqueTable
else:
uniqueTable.append(i)
return uniqueTable
# A function to generate a list of all the individual sample names in the inputed data set
def generateGroupInfo(shared):
infile = open(shared, 'r')
sampleNames = []
x = 0
for line in infile:
if x > 0:
y = 0
for k in line.split("\t"):
if y == 1:
sampleNames.append(k)
else:
sampleNames = sampleNames
y = y + 1
x = x + 1
infile.close()
return sampleNames
# A function to add all those that match a specific group for every individual in the data set
# Like to use a dictionary here instead of lists
# Needs sample name as the key and taxonomic level group, and totals as values
def generateTotals(uniqueTable, table, sampleNames, shared):
infile = open(shared, 'r')
otuHeader = []
finalData = {}
x = 0
for line in infile:
if x == 0:
for i in line.split("\t"):
otuHeader.append(i)
else:
tempNumbers = []
y = 0
for k in line.split("\t"):
if y <= 2:
tempNumbers = tempNumbers
else:
tempNumbers.append(k)
y = y + 1
taxaData = {}
for i in uniqueTable:
total = 0
for j in range(len(table)):
if i == table[j]:
total = total + eval(tempNumbers[j])
taxaData[i] = total
#Before Reset Need to add all of the data to a file to be parsed later
finalData[sampleNames[x-1]] = taxaData
x = x + 1
infile.close()
return finalData
# This function creates the total counts to generate the relative abundance table
def totalCounts(finalData, sampleNames, uniqueTable):
countsTable = {}
for i in sampleNames:
test = finalData[i]
x = 0
for j in uniqueTable:
tempValue = test[j]
x = x + tempValue
countsTable[i] = x
return countsTable
# This function generates the relative abundance table
def relativeAbundance(finalData, countsTable, uniqueTable, sampleNames):
for i in sampleNames:
total = countsTable[i]
tempdata = finalData[i]
for j in uniqueTable:
counts = tempdata[j]
relabund = (counts/total)*100
tempdata[j] = relabund
finalData[i] = tempdata
return finalData
#Print to file
def createDataTable(finalData, sampleNames, uniqueTable, final):
outfile = open(final, 'w')
x = 0
for i in sampleNames:
if x == 0:
for j in range(len(uniqueTable)):
if j == 0:
print("{0}".format("SampleIDs"), end ='\t', file = outfile)
print("{0}".format(uniqueTable[j]), end ='\t', file = outfile)
elif j < len(uniqueTable)-1:
print("{0}".format(uniqueTable[j]), end ='\t', file = outfile)
elif j == len(uniqueTable)-1:
print("{0}".format(uniqueTable[j]), end='\n', file = outfile)
tempData = finalData[i]
for k in range(len(uniqueTable)):
if k == 0:
print("{0}".format(i), end ='\t', file = outfile)
print("{0}".format(tempData[uniqueTable[k]]), end ='\t', file = outfile)
elif k < len(uniqueTable)-1:
print("{0}".format(tempData[uniqueTable[k]]), end ='\t', file = outfile)
elif k == len(uniqueTable)-1:
print("{0}".format(tempData[uniqueTable[k]]), end ='\n', file = outfile)
else:
tempData = finalData[i]
for k in range(len(uniqueTable)):
if k == 0:
print("{0}".format(i), end ='\t', file = outfile)
print("{0}".format(tempData[uniqueTable[k]]), end ='\t', file = outfile)
elif k < len(uniqueTable)-1:
print("{0}".format(tempData[uniqueTable[k]]), end ='\t', file = outfile)
elif k == len(uniqueTable)-1:
print("{0}".format(tempData[uniqueTable[k]]), end ='\n', file = outfile)
x = x + 1
outfile.close()
# Run the program
def main():
taxa, taxLevel, shared, uneven, taxaPrint, RelAbund, final = commandLine()
header, OTU, total, taxonomy = seperateTaxFile(taxa)
if uneven[7] in "Yy":
taxonomy, OTU = equalizeData(taxonomy, OTU, shared)
result = splitTaxonomy(taxonomy, taxLevel)
table = removeNumbers(result)
if taxaPrint[5] in "Tt":
createOutput(header, OTU, total, table)
test = taxaKey(OTU, table)
uniqueTable = generateUniqueTax(table)
sampleNames = generateGroupInfo(shared)
finalData = generateTotals(uniqueTable, table, sampleNames, shared)
# This controls whether a relative abundance or total count table is used
if RelAbund[0] in 'yY':
countsTable = totalCounts(finalData, sampleNames, uniqueTable)
relabund = relativeAbundance(finalData, countsTable, uniqueTable, sampleNames)
createDataTable(relabund, sampleNames, uniqueTable, final)
else:
createDataTable(finalData, sampleNames, uniqueTable, final)
if __name__ == '__main__': main()