-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathagmdbf.py
executable file
·222 lines (199 loc) · 8.9 KB
/
agmdbf.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
#! /usr/bin/env python
import os
import re
import argparse
from Bio import Entrez, SeqIO, SeqRecord, Phylo
import pandas as pd
from tqdm import tqdm
__author__ = "Dariusz Izak IBB PAS"
__version = "testing"
def db_dwn(output_file_name,
db,
term,
email="[email protected]"):
Entrez.email = email
db_handle = Entrez.esearch(db=db, term=term)
db_record = Entrez.read(db_handle)
db_full_size = db_record["Count"]
db_handle = Entrez.esearch(db=db, term=term, retmax=db_full_size)
db_record = Entrez.read(db_handle)
with open(output_file_name, "w") as fout:
for i in tqdm(db_record["IdList"]):
hand = Entrez.efetch(db=db, id=i, rettype="fasta", retmode="text")
rec = SeqIO.read(hand, "fasta")
SeqIO.write(rec, fout, "fasta")
def id_reform(input_file_name,
output_file_name):
output_ids = []
output_recs = []
with open(output_file_name, "w") as fout:
for i in tqdm(SeqIO.parse(input_file_name, "fasta")):
record = SeqRecord(id="{0}.{1}".format(i.description.split(";")[-1],
i.id.split(".")[0]),
seq=i.seq,
description="")
SeqIO.write(record, fout, "fasta")
def sanitize_ref_clade(line,
bad_words=["bacterium",
"miscellaneous",
"sp."]):
it = iter(line.split(" "))
genus = None
species = None
bad_words = bad_words
for i in it:
if i.istitle() is True and any([x.isdigit() for x in i]) is False:
genus = i
species = next(it, None)
if species and genus is not None:
if any(i in species for i in bad_words) is True:
return genus
else:
return "{} {}\n".format(genus, species)
elif genus is not None and species is None:
return genus
else:
return "unknown"
def sanitize_ref_tree(input_file_name,
output_file_name,
file_format="newick",
remove_whtspc=True):
tree = Phylo.read(input_file_name, file_format)
for i in tqdm(tree.find_clades()):
if remove_whtspc is True:
i.name = sanitize_ref_clade(i.name).replace(" ", "_")
else:
i.name = sanitize_ref_clade(i.name)
Phylo.write(tree, output_file_name, file_format)
def gene_tab_sum_reform(input_file_name,
sep="\t",
cols2rename={"genomic_nucleotide_accession.version":
"ACC_NO",
"start_position_on_the_genomic_accession":
"START",
"end_position_on_the_genomic_accession":
"END"},
essenatial_cols=["ACC_NO", "START", "END"]):
tab_sum_df = pd.read_csv(input_file_name, sep=sep)
tab_sum_ren = tab_sum_df.rename(columns=cols2rename)
tab_sum_nona = tab_sum_ren[essenatial_cols].dropna()
tab_sum_nona.ACC_NO = tab_sum_nona.ACC_NO.map(lambda x: re.sub("\.\d+",
"",
x))
tab_sum_nona.START = tab_sum_nona.START.map(lambda x: re.sub("\.\d+",
"",
str(x)))
tab_sum_nona.END = tab_sum_nona.END.map(lambda x: re.sub("\.\d+",
"",
str(x)))
return tab_sum_nona
def gene_seq_dwn(sum_df,
output_file_name,
rettype="fasta",
email="[email protected]"):
Entrez.email = email
with open(output_file_name, "w") as fout:
for i in tqdm(sum_df.itertuples()):
id = getattr(i, "ACC_NO")
start = getattr(i, "START")
end = getattr(i, "END")
hand = Entrez.efetch(db="nucleotide",
id=id,
seq_start=start,
seq_stop=end,
rettype=rettype,
retmode="text")
rec = SeqIO.read(hand, rettype)
SeqIO.write(rec, fout, rettype)
def gene_sanit_desc(input_file_name,
output_file_name,
file_format,
sep="_",
increment=True):
count = 0
with open(input_file_name) as fin:
with open(output_file_name, "w") as fout:
for i in tqdm(SeqIO.parse(fin, file_format)):
if increment is True:
count += 1
i.id = ""
desc_split = i.description.split(" ")[1:3]
desc_split_str = sep.join(desc_split)
if increment is True:
i.description = "{}_{}".format(desc_split_str, count)
else:
i.description = "{}".format(desc_split_str)
SeqIO.write(i, fout, file_format)
def main():
parser = argparse.ArgumentParser(prog="agmdbf",
usage="agmdbf.py [FILE] [OPTION]",
description="Part of \
ALternativeGEnomicMAppingPYpeline.\
Holds algemapy built-in database\
formatting.",
version="testing")
parser.add_argument(action="store",
dest="input_file_name",
metavar="",
help="Input file path.")
parser.add_argument("-o",
"--output",
action="store",
dest="output_file_name",
metavar="",
required=True,
help="Output file name.")
parser.add_argument("--download-from-tab-summary",
action="store_true",
dest="dwn_from_tab_sum",
default=False,
help="Download genes from nucleotide database by\
entries from Gene tabular summary.")
parser.add_argument("--sanitize-ref-tree",
action="store_true",
dest="sanitize_ref_tree",
default=False,
help="Sanitize reference tree by leaving just\
taxonomical names.")
parser.add_argument("--leave-raw",
action="store_true",
dest="leave_raw",
default=False,
help="Do not remove raw file downloaded from\
nucleotide db.")
args = parser.parse_args()
if args.dwn_from_tab_sum is True:
raw_seqs_file_name = "raw.{}".format(args.output_file_name)
print "Reformatting Gene database tabular summary..."
gene_tab_sum = gene_tab_sum_reform(input_file_name=args.input_file_name,
sep="\t",
cols2rename={"genomic_nucleotide_accession.version":
"ACC_NO",
"start_position_on_the_genomic_accession":
"START",
"end_position_on_the_genomic_accession":
"END"},
essenatial_cols=["ACC_NO", "START", "END"])
print "Downloading sequences by ID and coordinates from Gene database tabular summary..."
gene_seq_dwn(sum_df=gene_tab_sum,
output_file_name=raw_seqs_file_name,
rettype="fasta")
print "Removing unwanted part of sequences names..."
gene_sanit_desc(input_file_name=raw_seqs_file_name,
output_file_name=args.output_file_name,
file_format="fasta",
sep="_",
increment=True)
if args.leave_raw is False:
os.remove(raw_seqs_file_name)
print "Done!"
exit()
if args.sanitize_ref_tree is True:
sanitize_ref_tree(input_file_name=args.input_file_name,
output_file_name=args.output_file_name,
file_format="newick",
remove_whtspc=True)
print "Done!"
exit()
if __name__ == '__main__':
main()