File: macsyfinder

package info (click to toggle)
macsyfinder 1.0.5-3
  • links: PTS, VCS
  • area: main
  • in suites: sid
  • size: 54,800 kB
  • sloc: python: 6,060; xml: 780; makefile: 156; sh: 12
file content (383 lines) | stat: -rwxr-xr-x 20,148 bytes parent folder | download | duplicates (2)
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
#!/usr/bin/env python
# -*- coding: utf-8 -*-

################################################################################
# MacSyFinder - Detection of macromolecular systems in protein datasets        #
#               using systems modelling and similarity search.                 #
# Authors: Sophie Abby, Bertrand Néron                                         #
# Copyright © 2014  Institut Pasteur, Paris.                                   #
# See the COPYRIGHT file for details                                           #
#                                                                              #
# MacsyFinder is distributed under the terms of the GNU General Public License #
# (GPLv3). See the COPYING file for details.                                   #
################################################################################


import sys
import os
import argparse
import logging

if 'MACSY_HOME' in os.environ:
    MACSY_HOME = os.environ.get('MACSY_HOME')
    MACSY_HOME = os.path.abspath(os.path.realpath(MACSY_HOME))
    if MACSY_HOME not in sys.path:
        sys.path.insert(0, MACSY_HOME)
try:
    from macsypy.config import Config
except ImportError as err:
    msg = "Cannot import macsypy, check your installation or your MACSY_HOME variable : {0!s}".format(err)
    sys.exit( msg )

from operator import attrgetter # To be used with "sorted"
from textwrap import dedent
from macsypy.system_parser import SystemParser
from macsypy.search_genes import search_genes
from macsypy.database import Indexes
from macsypy.search_systems import search_systems
from macsypy.system import system_bank
from macsypy.gene import gene_bank

parser = argparse.ArgumentParser(epilog="For more details, visit the MacSyFinder website and see the MacSyFinder documentation.",
                                 formatter_class=argparse.RawDescriptionHelpFormatter,
                                 description=dedent('''


     *            *               *                   *
*           *               *   *   *  *    **                *   *
  **     *    *   *  *     *                    *               *
    __  __  *              ____ *        *  *  *    **     *
|| |  \/  | __ _  ___  || / ___| _   _  ||   ___ _         _        *
|| | |\/| |/ _` |/ __| || \___ \| | | | ||  | __(_)_ _  __| |___ _ _
|| | |  | | (_| | (__  ||  ___) | |_| | ||  | _|| | ' \/ _` / -_) '_|
|| |_|  |_|\__,_|\___| || |____/ \__, | ||  |_| |_|_||_\__,_\___|_|
           *             *       |___/         *                   *
 *      *   * *     *   **         *   *  *           *
  *      *         *        *    *              *
             *                           *  *           *     *


MacSyFinder is a tool for the detection of protein secretion systems
of diderm bacteria from a protein dataset.
     ''') )
#, formatter_class=argparse.RawDescriptionHelpFormatter)
#, formatter_class=argparse.ArgumentDefaultsHelpFormatter)

parser.add_argument("systems",
                    nargs = '*',
                    help = "The systems to detect. This is an obligatory option with no keyword associated to it. To detect all the protein secretion systems and related appendages: set to \"all\" (case insensitive). Otherwise, a single or multiple systems can be specified. For example: \"T2SS T4P\". ")
genome_options = parser.add_argument_group(title = "Input dataset options")
genome_options.add_argument("--sequence-db",
                    action = 'store',
                    dest = 'sequence_db',
                    help = "Path to the sequence dataset in fasta format.")
genome_options.add_argument("--db-type" ,
                       choices = ['unordered_replicon', 'ordered_replicon', 'gembase', 'unordered'],
                       dest = "db_type",
                       default = None,
                       help = "The type of dataset to deal with. \"unordered_replicon\" corresponds to a non-assembled genome, \"unordered\" to a metagenomic dataset, \"ordered_replicon\" to an assembled genome, and \"gembase\" to a set of replicons where sequence identifiers follow this convention: \">RepliconName SequenceID\"." )
genome_options.add_argument("--replicon-topology" ,
                       choices = ['linear', 'circular'],
                       dest = "replicon_topology",
                       default = None,
                       help = "The topology of the replicons (this option is meaningful only if the db_type is 'ordered_replicon' or 'gembase'. ")
genome_options.add_argument("--topology-file" ,
                       dest = "topology_file",
                       default = None,
                       help = "Topology file path. The topology file allows to specify a topology (linear or circular) for each replicon (this option is meaningful only if the db_type is 'ordered_replicon' or 'gembase'. A topology file is a tabular file with two columns: the 1st is the replicon name, and the 2nd the corresponding topology:\n\"RepliconA\tlinear\" ")
genome_options.add_argument("--idx" ,
                       action = 'store_true',
                       dest = "build_indexes",
                       default = False,
                       help = "Forces to build the indexes for the sequence dataset even if they were presviously computed and present at the dataset location (default = False)")

system_options =  parser.add_argument_group(title = "Systems detection options")
system_options.add_argument("--inter-gene-max-space",
                             action = 'append',
                             nargs = 2,
                             dest = 'inter_gene_max_space',
                             default = None,
                             help = "Co-localization criterion: maximum number of components non-matched by a profile allowed between two matched components for them to be considered contiguous. Option only meaningful for 'ordered' datasets. The first value must match to a system, the second to a number of components.\
                              This option can be repeated several times:\n \"--inter-gene-max-space T2SS 12 --inter-gene-max-space Flagellum 20\""
                             )
system_options.add_argument("--min-mandatory-genes-required",
                             action = 'append',
                             nargs = 2,
                             dest = 'min_mandatory_genes_required',
                             default = None,
                             help = "The minimal number of mandatory genes required for system assessment. The first value must correspond to a system name, the second value to an integer.\
                              This option can be repeated several times:\n \"--min-mandatory-genes-required T2SS 15 --min-mandatory-genes-required Flagellum 10\""
                             )

system_options.add_argument("--min-genes-required",
                             action = 'append',
                             nargs = 2,
                             dest = 'min_genes_required',
                             default = None,
                             help = "The minimal number of genes required for system assessment (includes both 'mandatory' and 'accessory' components). The first value must correspond to a system name, the second value to an integer.\
                              This option can be repeated several times:\n \"--min-genes-required T2SS 15 --min-genes-required Flagellum 10\""
                             )

system_options.add_argument("--max-nb-genes",
                             action = 'append',
                             nargs = 2,
                             dest = 'max_nb_genes',
                             default = None,
                             help = "The maximal number of genes required for system assessment. The first value must correspond to a system name, the second value to an integer.\
                              This option can be repeated several times:\n \"--max-nb-genes T2SS 5 --max-nb-genes Flagellum 10"
                             )

system_options.add_argument("--multi-loci",
                             action = 'store',
                             dest = 'multi_loci',
                             default = None,
                             help = "Allow the storage of multi-loci systems for the specified systems.\
                              The systems are specified as a comma separated list (--multi-loci sys1,sys2) default is False"
                             )

hmmer_options =  parser.add_argument_group(title = "Options for Hmmer execution and hits filtering")
hmmer_options.add_argument('--hmmer',
                            action = 'store',
                            dest = 'hmmer_exe',
                            default = None,
                            help = 'Path to the Hmmer program.')
hmmer_options.add_argument('--index-db',
                            action = 'store',
                            dest = 'index_db_exe',
                            default = None,
                            help = "The indexer to be used for Hmmer. The value can be either 'makeblastdb' or 'formatdb' or the path to one of these binary (default = makeblastb)")

hmmer_options.add_argument('--e-value-search',
                     action = 'store',
                     dest = 'e_value_res',
                     type = float,
                     default = None,
                     help = 'Maximal e-value for hits to be reported during Hmmer search. (default = 1)')

hmmer_options.add_argument('--i-evalue-select',
                     action = 'store',
                    dest = 'i_evalue_sel',
                    type = float,
                    default = None ,
                    help = 'Maximal independent e-value for Hmmer hits to be selected for system detection. (default = 0.001)')

hmmer_options.add_argument('--coverage-profile',
                     action = 'store',
                    dest = 'coverage_profile',
                    type = float,
                    default = None ,
                    help = 'Minimal profile coverage required in the hit alignment to allow the hit selection for system detection. (default = 0.5)')

dir_options =  parser.add_argument_group(title = "Path options", description = None)
dir_options.add_argument('-d', '--def',
                    action = 'store',
                    dest = 'def_dir',
                    default = None,
                    help = 'Path to the systems definition files.')
dir_options.add_argument('-o', '--out-dir',
                    action = 'store',
                    dest = 'out_dir',
                    default = None,
                    help = 'Path to the directory where to store results. if out-dir is specified res-search-dir will be ignored.')
dir_options.add_argument('-r', '--res-search-dir',
                    action = 'store',
                    dest = 'res_search_dir',
                    default = None,
                    help = 'Path to the directory where to store MacSyFinder search results directories (default current working directory).')
dir_options.add_argument('--res-search-suffix',
                    action = 'store',
                    dest = 'res_search_suffix',
                    default = None,
                    help = 'The suffix to give to Hmmer raw output files.')
dir_options.add_argument('--res-extract-suffix',
                    action = 'store',
                    dest = 'res_extract_suffix',
                    default = None,
                    help = 'The suffix to give to filtered hits output files.')
dir_options.add_argument('-p', '--profile-dir',
                    action = 'store',
                    dest = 'profile_dir',
                    default = None,
                    help = 'Path to the profiles directory.')
dir_options.add_argument('--profile-suffix',
                    action = 'store',
                    dest = 'profile_suffix',
                    default = None,
                    help = "The suffix of profile files. For each 'Gene' element, the corresponding profile is searched in the 'profile_dir', in a file which name is based on the Gene name + the profile suffix. For instance, if the Gene is named 'gspG' and the suffix is '.hmm3', then the profile should be placed at the specified location and be named 'gspG.hmm3'")

general_options =  parser.add_argument_group(title = "General options", description = None)
general_options.add_argument("-w", "--worker",
                    action = 'store',
                    dest = 'worker_nb',
                    type = int,
                    default = None,
                    help = "Number of workers to be used by MacSyFinder. In the case the user wants to run MacSyFinder in a multi-thread mode. (0 mean all cores will be used, default 1)")
general_options.add_argument("-v" , "--verbosity",
                      action= "count",
                      dest = "verbosity",
                      default = 0,
                      help = "Increases the verbosity level. There are 4 levels: Error messages (default), Warning (-v), Info (-vv) and Debug.(-vvv)")
general_options.add_argument("--version",
                      action= "store_true",
                      dest = "version",
                      default = False,
                      help = "display the version information and quit")
general_options.add_argument("--log",
                    action = 'store',
                    dest = 'log_file',
                    default = None,
                    help = "Path to the directory where to store the 'macsyfinder.log' log file.")
general_options.add_argument("--config",
                    action = 'store',
                    dest = 'cfg_file',
                    default = None,
                    help = "Path to a putative MacSyFinder configuration file to be used.")
general_options.add_argument("--previous-run",
                    action = 'store',
                    dest = 'previous_run',
                    default = None,
                    help = """Path to a previous MacSyFinder run directory. It allows to skip the Hmmer search step on same dataset, as it uses previous run results and thus parameters regarding Hmmer detection. The configuration file from this previous run will be used.
(conflict with options  --config, --sequence-db, --profile-suffix, --res-extract-suffix,
--e-value-res, --db-type, --hmmer)""")

args = parser.parse_args()
if args.version:
    import macsypy
    if macsypy.__version__ == '$VERSION':
        version = "NOT packaged, development version"
    else:
        version = macsypy.__version__
    print >> sys.stderr, """Macsyfinder {0}
Python {1}

MacsyFinder is distributed under the terms of the GNU General Public License (GPLv3).
See the COPYING file for details.

If you use this software please cite:
Abby SS, Néron B, Ménager H, Touchon M, Rocha EPC (2014)
MacSyFinder: A Program to Mine Genomes for Molecular Systems with an Application to CRISPR-Cas Systems.
PLoS ONE 9(10): e110726. doi:10.1371/journal.pone.0110726""".format(version, sys.version)
    sys.exit(0)

if not args.systems:
    parser.error("you MUST provided systems to search.")

if not args.previous_run and not args.sequence_db:
    parser.error("argument --sequence-db is required.")

if not args.previous_run and not args.db_type:
    parser.error("argument --db-type is required.")

if args.previous_run and (args.cfg_file or
                          args.sequence_db or
                          args.profile_suffix or
                          args.profile_dir or
                          args.res_extract_suffix or
                          args.e_value_res or
                          args.db_type or
                          args.hmmer_exe):
    parser.error(""" --previous-run conficts with --config, --sequence-db, --profile-suffix, --profile-dir, --res-extract-suffix, --e-value-res, --db-type, --hmmer""")

sh_formatter = logging.Formatter("%(levelname)-8s : L %(lineno)d : %(message)s")
sh = logging.StreamHandler(sys.stderr)
sh.setFormatter(sh_formatter)

if args.verbosity == 0:
    log_level = None
elif args.verbosity == 1:
    log_level = logging.WARNING
elif args.verbosity == 2:
    log_level = logging.INFO
elif args.verbosity == 3:
    log_level = logging.DEBUG
else:
    log_level = logging.NOTSET

config = Config(previous_run = args.previous_run,
                cfg_file = args.cfg_file,
                sequence_db = args.sequence_db,
                db_type = args.db_type,
                build_indexes = args.build_indexes,
                replicon_topology = args.replicon_topology,
                topology_file = args.topology_file,
                inter_gene_max_space = args.inter_gene_max_space,
                min_mandatory_genes_required = args.min_mandatory_genes_required,
                min_genes_required = args.min_genes_required,
                max_nb_genes = args.max_nb_genes,
                multi_loci = args.multi_loci,
                hmmer_exe = args.hmmer_exe,
                index_db_exe = args.index_db_exe,
                e_value_res = args.e_value_res,
                i_evalue_sel = args.i_evalue_sel,
                coverage_profile = args.coverage_profile,
                def_dir = args.def_dir,
                res_search_dir = args.res_search_dir,
                out_dir = args.out_dir,
                res_search_suffix = args.res_search_suffix,
                profile_dir = args.profile_dir,
                profile_suffix = args.profile_suffix,
                res_extract_suffix = args.res_extract_suffix,
                log_level = log_level,
                log_file = args.log_file,
                worker_nb = args.worker_nb
                )
logger = logging.getLogger('macsyfinder')
config.save(config.working_dir)

#build indexes
idx = Indexes(config)
idx.build(force = config.build_indexes)

parser = SystemParser(config, system_bank, gene_bank)
if ('all' or 'All' or 'ALL') in args.systems:
    import glob
    systems_name_to_detect = glob.glob(os.path.join(config.def_dir, '*.xml'))
    systems_name_to_detect = [os.path.basename(s)[:-4] for s in systems_name_to_detect]
else:
    systems_name_to_detect = args.systems
parser.parse(systems_name_to_detect)


out_logger = logging.getLogger('macsyfinder.out')
out_logger.info("MacSyFinder's results will be stored in {0}".format(config.working_dir))
out_logger.info("Analysis launched on {0} for system(s):".format(config.sequence_db))
for s in systems_name_to_detect:
    out_logger.info("\t- {}".format(s))

systems_to_detect = [system_bank[system_name] for system_name  in systems_name_to_detect]
all_genes = []
for system in systems_to_detect:
    genes = system.mandatory_genes + system.accessory_genes + system.forbidden_genes
    # Exchangeable homologs/analogs are also added cause they can "replace" an important gene...
    ex_genes = []

    for g in genes:
        if g.exchangeable:
            h_s = g.get_homologs()
            ex_genes += h_s
            a_s = g.get_analogs()
            ex_genes += a_s
    all_genes +=  (genes + ex_genes)
#############################################
# this part of code is executed in parallel
#############################################
try:
    all_reports = search_genes(all_genes, config)
except Exception as err:
    sys.exit(str(err))
#############################################
# end of parallel code
#############################################
all_hits = [hit for subl in [report.hits for report in all_reports ] for hit in subl]

if len(all_hits) > 0:
    # It's important to keep this sorting to have in last  all_hits version
    # the hits with the same replicon_name and position sorted by score
    # the best score in first
    all_hits = sorted(all_hits, key = attrgetter('score'), reverse = True)
    all_hits = sorted(all_hits, key = attrgetter('replicon_name', 'position'))
    systems_to_detect = sorted(systems_to_detect, key = attrgetter('name'))
    search_systems(all_hits, systems_to_detect, config)
else:
    logger.info("No hits found in this dataset.")
logger.debug("END")