-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathgenewiseAligner.py
207 lines (158 loc) · 5.84 KB
/
genewiseAligner.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
import re
import os
import csv
#find files
here = os.path.dirname(os.path.abspath(__file__))
files = []
for file in os.listdir(here):
if file.endswith(".gbk"):
files.append(file)
genes = []
def findBackGenes(depth, LineNum, lines):
pattern = r'/gene="([^"]+)"'
product=''
fieldNum = 0
geneAdded = False
for i in range (LineNum, -1, -1):
if depth < 0 :
fillListBack(fieldNum)
break
elif re.search('ORIGIN', lines[i]) != None:
break
if re.search(r'/product="([^"]+)"', lines[i]) != None:
product = re.search(r'/product="([^"]+)"', lines[i]).group(1)
match = re.search(pattern, lines[i])
if (match != None):
gene_value = match.group(1)
genes.insert(0, [(fieldNum), gene_value])
fieldNum = fieldNum-1
depth = depth-1
geneAdded = True
elif (re.search('CDS', lines[i]) != None) and geneAdded == False:
genes.insert(0,[(fieldNum), product])
depth -= 1
fieldNum -= 1
elif (re.search('CDS', lines[i]) != None) and geneAdded == True:
geneAdded = False
def findforwardGenes(depth, LineNum, LinesLen, lines):
pattern = r'/gene="([^"]+)"'
fieldNum = 1
product = ''
geneAdded = False
for i in range (LineNum+1, LinesLen):
if (re.search('CDS', lines[i]) != None):
LineNum = i
break
for i in range (LineNum+1, LinesLen):
if depth <= 0 :
fillListFront(fieldNum)
break
elif re.search('ORIGIN', lines[i]) != None:
break
if re.search(r'/product="([^"]+)"', lines[i]) != None:
product = re.search(r'/product="([^"]+)"', lines[i]).group(1)
match = re.search(pattern, lines[i])
if (match != None):
gene_value = match.group(1)
genes.append([(fieldNum), gene_value])
fieldNum = fieldNum+1
depth = depth-1
geneAdded = True
elif (re.search('CDS', lines[i]) != None) and geneAdded == False:
genes.append([(fieldNum), product])
depth -= 1
fieldNum += 1
elif (re.search('CDS', lines[i]) != None) and geneAdded == True:
geneAdded = False
product =''
def fillListBack(fieldNum):
for i in range (fieldNum, -11, -1):
genes.insert(0,[(i), None])
def fillListFront(fieldNum):
for i in range (fieldNum, 11):
genes.append([(i), None])
def writeToCSV(genes, CSV):
fields = ['filename'] + list(range(-depth, depth+1))
# Initialize the dictionary with all fieldnames and set their default value to None
gene_dict = {field: None for field in fields}
for key, value in genes:
if key == 'filename':
gene_dict['filename'] = value
else:
position = int(key)
if position in gene_dict:
gene_dict[position] = value
file_exists = os.path.isfile(CSV)
with open(CSV, 'a', newline='') as csvfile:
writer = csv.DictWriter(csvfile, fieldnames=fields)
if not file_exists:
writer.writeheader()
writer.writerow(gene_dict)
def searchFile(filename, gene):
#open file
file = os.path.join(here, filename)
GBK = open(file, 'r')
lines = GBK.readlines()
#search for gene
complement = False
for i in range (0, len(lines)):
pattern = 'gene="'+gene+'"'
found = False
if (re.search(pattern, lines[i]) != None):
# check for complement
complement = (re.search('complement', lines[i-1]) != None)
# gene found, find genes before & after
findBackGenes(depth, i, lines)
findforwardGenes(depth, i, len(lines), lines)
found = True
if complement:
for i in range (0, len(genes)):
genes[i][0]= genes[i][0]*-1
genes.insert(0,('filename',filename))
return (found,genes)
return found, genes
'''///////////////////*main*/////////////////'''
#take input
gene = input("Input gene name (case sensitive): ")
while (gene != 'exit'):
depth = -1
while (depth<0):
depth = int(input("Input search depth (>1): "))
instances = 0
filesSearched = 0
fileNum = len(files)
#create CSV
CSV = gene + ".csv"
#delete it ifit exists already
file_exists = os.path.isfile(CSV)
if file_exists:
os.remove(CSV)
#main loop
for file in files:
percentage = int((filesSearched/fileNum)*100)
print(str(percentage)+"% " +"\t|\t"+ "Instances found: "+str(instances) + '\t|\tFiles searched: ' + str(filesSearched)+'/'+str(fileNum), end="\r")
filesSearched+=1
found = False
(found, genesFound) = searchFile(file, gene)
if found:
writeToCSV(genesFound, CSV)
instances+=1
genes = []
variations = 1
if (not found):
found = True
while (found):
nextGene = str(f"{gene}_{variations}")
(found, genesFound) = searchFile(file, nextGene)
if found:
writeToCSV(genesFound, CSV)
instances+=1
genes = []
variations = variations+1
print("100% " +"\t|\t"+ "Instances found: "+str(instances) + '\t|\tFiles searched: ' + str(filesSearched)+'/'+str(fileNum))
if instances > 0:
print("We found "+str(instances)+" instances of " + gene )
print("Search your GBk files' directory for " +gene+".csv")
else:
print("We haven't found any genes " + gene + ", make sure you're searching for the correct gene, check spelling")
gene = input("Enter 'exit' to exit program OR input another gene name (case sensitive) : ")