/
scenario_1.py
executable file
·348 lines (275 loc) · 12.9 KB
/
scenario_1.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
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
#!/usr/bin/env python
from shutil import move, copy
import sys
import logging
from os import chdir, mkdir, getcwd, listdir, makedirs
from os.path import join, exists, isdir, isfile, dirname, realpath, \
basename, relpath, splitext, abspath, expanduser
from Bio import SeqIO
from src.fetch_annotations import fetch_annotations_for_species_from_ftp, \
fetch_annotations_for_ids, fetch_annotations_species_name_entrez
from src.make_proteomes import adjust_proteomes, make_proteomes
from src.steps import check_results_existence
from src import steps
from src.argparse import ArgumentParser
from src.utils import make_workflow_id, read_list, set_up_config, \
get_starting_step, interrupt, register_ctrl_c, \
test_entrez_conn, test_blast_conn, test_ftp_conn, check_and_install_tools
from src.parse_args import arg_parse_error, check_file, check_dir, \
add_common_arguments, check_common_args
from src.logger import set_up_logging
from src.Workflow import Workflow, Step
from src import config
from src.config import log_fname
log = logging.getLogger(log_fname)
script_path = dirname(realpath(__file__))
#def run_workflow(working_dir,
# species_list, ids_list, annotations, proteomes, prot_id_field,
# min_length, max_percent_stop, evalue,
# ask_before=False,
# start_after=None, start_from=None, overwrite=True,
# threads=1,
# proxy=None,
# **kwargs):
def parse_args(args):
op = ArgumentParser(description='Find groups of orthologous genes.')
#op.add_argument(dest='directory')
op.add_argument('-o', '--out', '--dir', dest='out', required=True)
op.add_argument('-g', '--gbs', '--annotations', dest='annotations')
op.add_argument('-p', '--proteins', '--proteomes', dest='proteomes')
op.add_argument('--no-download', dest='download_anno', action='store_false', default=True)
op.add_argument('-s', '--species', '--species-list', dest='species_list')
op.add_argument('-i', '--ids', '--ids-list', dest='ids_list')
op.add_argument('--prot-id-field', dest='prot_id_field', default=1)
op.usage = '''Finding orthogroups for a list of annotations / proteomes / ref ids / species.
Test runs:
python scenario_1.py --ids test_input/ids.txt -o test_ids
python scenario_1.py --proteomes test_input/proteins -o test_proteomes
Usage: %s [-p <proteomes dir>] [-a <.gb files dir>] [-i <gb ids file>] [-s <strain names file>]
[-o <dir>] [--jobs 30] [--start-from <step num>]
-o Output directory.
-g Directory with .gb files for references with annotations.
-p Directory with fasta (or faa, fa) files of protein sequences. If they
are named by their reference ids (i.e. NC_005816.1.fasta), annotations
will be downloaded from NCBI.
-i File with reference ids (will be fetched from NCBI).
-s File with a list of organism names as in Genbank.
--prot-id-field
When specifying proteomes, use this fasta id field number
to retrieve protein ids (default if 1, like >NC_005816.1|NP_995567.1 ...).
''' % basename(__file__)
#-a --annotations-dir Directory with .gb files.
#-p --proteomes-dir Directory with fasta files of proteomes.
#-i --ids-list File with reference ids (will be fetched from Genbank).
#-s --species-list File with a list of organism names as in Genbank.
# For example, "Salmonella enterica subsp. enterica serovar Typhi str. P-stx-12".
#'''
#indent = ' ' * len('usage: ' + basename(__file__) + ' ')
#op.usage = basename(__file__) + ' [--annotations-dir DIR]\n' + \
# indent + '[--proteomes-dir DIR]\n' + \
# indent + '[--ids-file FILE]\n' + \
# indent + '[--species-file FILE]\n'
add_common_arguments(op)
p = op.parse_args(args)
check_common_args(p)
if not p.out:
arg_parse_error('Specify output directory with -o.')
if isfile(expanduser(p.out)):
arg_parse_error('%s is a file' % p.out)
p.out = abspath(expanduser(p.out))
if not isdir(p.out):
makedirs(p.out)
if p.species_list:
check_file(expanduser(p.species_list))
p.species_list = abspath(expanduser(p.species_list))
if p.ids_list:
check_file(expanduser(p.ids_list))
p.ids_list = abspath(expanduser(p.ids_list))
if p.proteomes:
check_dir(expanduser(p.proteomes))
p.proteomes = abspath(expanduser(p.proteomes))
if p.annotations:
check_dir(expanduser(p.annotations))
p.annotations = abspath(expanduser(p.annotations))
#if p.species_list or p.ids_list:
# if not isdir(p.out):
# mkdir(p.out)
#else:
# if not p.directory:
# arg_parse_error('Directory or file must be specified.')
# check_dir(p.directory)
return p
def collect_proteomes_and_annotaitons(input_dir):
proteomes = []
annotations = []
files = listdir(input_dir)
if not files:
interrupt('Directory contains no files.')
for f in (join(input_dir, f) for f in files if isfile(join(input_dir, f))):
if '.' in f and splitext(f)[1] in ['.fasta', '.faa', '.fa', '.fsa']:
try:
log.debug(' Checking if %s is fasta.' % f)
next(SeqIO.parse(f, 'fasta'))
except ValueError, e:
pass
else:
proteomes.append(f)
continue
if '.' in f and splitext(f)[1] in ['.gb', '.genbank', '.gbk']:
try:
log.debug(' Checking if %s is genbank.' % f)
SeqIO.read(f, 'genbank')
except Exception, e:
log.debug(str(e) + ', ' + f)
else:
annotations.append(f)
log.debug('')
return proteomes, annotations
def step_prepare_proteomes_and_annotations(p):
def run(starting_from_here=False):
if p.species_list:
if not test_entrez_conn():
log.error(' No internet connection: cannot fetch annotations.')
return 4
log.debug(' Using species list: ' + str(p.species_list))
gb_ids = read_list(p.species_list)
log.debug('species_list: ' + str(gb_ids))
res = fetch_annotations_species_name_entrez(config.annotations_dir, gb_ids, p.proxy)
if res != 0: return res
return make_proteomes(config.annotations_dir, config.proteomes_dir)
elif p.ids_list:
if not test_entrez_conn():
log.error('No internet connection: cannot fetch annotations.')
return 4
log.debug(' Using ref ids: ' + str(p.ids_list))
ref_ids = read_list(p.ids_list)
res = fetch_annotations_for_ids(config.annotations_dir, ref_ids)
if res != 0: return res
return make_proteomes(config.annotations_dir, config.proteomes_dir)
else:
proteomes, annotations = [], []
if p.proteomes:
proteomes, annotations = collect_proteomes_and_annotaitons(p.proteomes)
if proteomes == []:
interrupt('No fasta found in ' + p.proteomes)
if p.annotations:
proteomes, annotations = collect_proteomes_and_annotaitons(p.annotations)
if annotations == []:
interrupt('No gb files found in ' + p.annotations)
#if not proteomes and not annotations:
# interrupt('Directory must contain fasta or genbank files.')
#
#if proteomes and annotations:
# log.warn('Directory %s contains both fasta and genbank files, using fasta.')
if annotations:
if not isdir(config.annotations_dir):
mkdir(config.annotations_dir)
for annotation in annotations:
copy(annotation, config.annotations_dir)
return make_proteomes(config.annotations_dir, config.proteomes_dir)
elif proteomes:
if not isdir(config.proteomes_dir):
mkdir(config.proteomes_dir)
if p.download_anno:
if not test_entrez_conn():
#log.error(' Error: no internet connection, cannot fetch annotations. '
# 'You can start without a --no-fetch option, in this case '
# 'a reduced version of orthogroups.txt with no annotations will be produced.')
#return 1
log.error(' Warning: no internet connection, cannot fetch annotations. '
'A reduced version of orthogroups.txt with no annotations will be produced.')
else:
# ref_ids = [splitext(basename(prot_file))[0] for prot_file in proteomes]
# fetch_annotations_for_ids(config.annotations_dir, ref_ids)
gb_ids = [splitext(basename(prot_file))[0] for prot_file in proteomes]
log.debug('ids_list: ' + str(gb_ids))
res = fetch_annotations_for_ids(config.annotations_dir, gb_ids, p.proxy)
if res > 0:
return res
if res == -1:
p.download_anno = False
return adjust_proteomes(proteomes, config.proteomes_dir, p.prot_id_field)
return Step(
'Preparing proteomes and annotations',
run=run,
prod_files=[config.proteomes_dir, config.annotations_dir])
def main(args):
register_ctrl_c()
p = parse_args(args)
log_path = set_up_logging(p.debug, p.out)
log.info('python ' + __file__ + ' ' + ' '.join(args))
log.info('logging to ' + log_path)
log.info('')
try:
working_dir = p.out
with open(config.config_file) as f:
conf = dict(l.strip().lower().split('=', 1)
for l in f.readlines() if l.strip() and l.strip()[0] != '#')
check_and_install_tools(p.debug, conf.get('db_vendor', 'sqlite') == 'sqlite', log_path)
start_from, start_after = get_starting_step(p.start_from, join(p.out, log_fname))
log.debug('Changing to %s' % working_dir)
chdir(working_dir)
if not p.overwrite:
check_results_existence()
if not exists(config.intermediate_dir):
mkdir(config.intermediate_dir)
set_up_config(working_dir)
# Building the workflow
workflow = Workflow(working_dir, id=make_workflow_id(working_dir),
cmdline_args=['python', __file__] + args)
log.debug('Workflow id is "' + workflow.id + '"')
log.debug('')
suffix = '' if conf.get('db_vendor', 'sqlite') == 'sqlite' else '_' + workflow.id
njobs = p.threads or p.jobs or 30
workflow.extend([
step_prepare_proteomes_and_annotations(p),
steps.filter_proteomes(
min_length=int(p.min_length),
max_percent_stop=int(p.max_percent_stop)),
steps.make_blast_db(),
steps.blast(
workflow.id,
int(p.threads) or int(p.jobs) or 30,
on_cluster=njobs and not p.threads,
evalue=float(p.evalue)),
steps.parse_blast_results(),
steps.clean_database(suffix),
steps.install_schema(suffix),
steps.load_blast_results(suffix),
steps.find_pairs(suffix),
steps.dump_pairs_to_files(suffix),
steps.mcl(p.debug),
steps.step_save_orthogroups()])
result = workflow.run(
start_after, start_from,
overwrite=True,
ask_before=p.ask_each_step)
if result == 0:
log.info('Done.')
log.info('Log is in ' + join(working_dir, log_fname))
if isfile(join(working_dir, config.orthogroups_file)):
log.info('Groups are in ' + join(working_dir, config.orthogroups_file))
if isfile(config.nice_orthogroups_file):
log.info('Groups with aligned columns are in ' +
join(working_dir, config.nice_orthogroups_file))
else:
log.info('Groups in short format are in ' +
join(working_dir, config.short_orthogroups_file))
if isfile(log_fname):
with open(log_fname, 'a') as f:
f.write('\n')
return result
except (KeyboardInterrupt, SystemExit, GeneratorExit):
if isfile(log_fname):
with open(log_fname, 'a') as f:
f.write('\n')
return 1
except Exception as e:
log.error('')
log.exception('Unexpected error!')
if isfile(log_fname):
with open(log_fname, 'a') as f:
f.write('\n')
return 2
if __name__ == '__main__':
exit(main(sys.argv[1:]))