commands.py 10.8 KB
Newer Older
1
# coding=utf-8
fabrice's avatar
fabrice committed
2
3
4
"""
                            Input/Output aria_ec
"""
5
from __future__ import absolute_import, division, print_function
fabrice's avatar
fabrice committed
6
7
8
9
10
11
12
13
14
15

import os
import logging
import argparse as argp

from .ecsettings import AriaEcSettings
from .maplot import AriaEcContactMap
from .econverter import AriaEcBbConverter
from .setup import AriaEcSetup

16
17

LOG = logging.getLogger(__name__)
fabrice's avatar
fabrice committed
18
19
20


def check_file(prospective_file):
21
    """
fabrice's avatar
fabrice committed
22

23
24
    :param prospective_file:
    """
fabrice's avatar
fabrice committed
25
26
27
28
29
30
31
32
33
    if not os.path.exists(prospective_file):
        raise argp.ArgumentTypeError("readable_file:'{0}' is not a valid "
                                     "path".format(prospective_file))
    if not os.access(prospective_file, os.R_OK):
        raise argp.ArgumentTypeError("readable_file:'{0}' is not a readable "
                                     "file".format(prospective_file))


class ReadableFile(argp.Action):
34
35
36
    """
    Class used with argparse action to check if a file is readable
    """
fabrice's avatar
fabrice committed
37

Fabrice Allain's avatar
Fabrice Allain committed
38
39
40
    def __init__(self, *args, **kwargs):
        super(ReadableFile, self).__init__(*args, **kwargs)

fabrice's avatar
fabrice committed
41
42
43
44
45
46
47
48
49
50
51
    def __call__(self, parser, namespace, values, option_string=None):
        if type(values) == list:
            for prospective_file in values:
                check_file(prospective_file)
        elif type(values) == str:
            check_file(values)
        setattr(namespace, self.dest, values)


# TODO: Make parent Command class with _create_argparser, self.args,
# update_logger and run
52
class AriaEcCommand(object):
fabrice's avatar
fabrice committed
53
54
55
56
57
58
59
60
61
    """
    Argparse interface for aria_ec
    """

    command_list = ("setup", "bbconv", "contactmap")
    desc_list = (u"Setup ARIA infrastructure with given contacts translated "
                 u"into ARIA restraints",
                 u"Convert contacts in bbcontact format",
                 u"Contactmap tool")
62
63
64
65
    contact_types = ("plmdca", "evfold", "bbcontacts", "pconsc", "pconsc1",
                     "pconsc2", "psicov", "metapsicovhb", "metapsicov_stg1",
                     "metapsicov_stg2", "gremlin", "pdb", "native",
                     "native_full", "contactlist")
fabrice's avatar
fabrice committed
66
67
68
69
70
71
72
    default_confile = "conf/aria_ec.ini"

    def __init__(self, custom_logging=None):
        # Def Argument parser
        parser = self._create_argparser()
        # parse args
        self.args = parser.parse_args()
73
        # Update LOG with outdir
fabrice's avatar
fabrice committed
74
75
76
77
        self._update_logger(custom_logging)

    def _update_logger(self, log):
        if log and hasattr(self.args, "output_directory"):
fabrice's avatar
fabrice committed
78
79
80
            if not self.args.nolog:
                # Don't generate log files
                # TODO: get handler list from json file or customlogging object
81
82
83
                LOG.removeHandler("info_file_handler")
                LOG.removeHandler("error_file_handler")
                LOG.removeHandler("debug_file_handler")
fabrice's avatar
fabrice committed
84
                log.set_outdir(self.args.output_directory)
fabrice's avatar
fabrice committed
85
86
87
88
89
90
91
92
            log.update_msg(self.args.command)
            log.welcome()

    def _create_argparser(self):
        parser = argp.ArgumentParser(description=u"ARIA Evolutionary "
                                                 u"restraints toolbox",
                                     formatter_class=argp.ArgumentDefaultsHelpFormatter)
        parser.add_argument("-o", "--output", dest="output_directory",
93
                            type=str, help="Output directory", required=True)
94
95
        parser.add_argument("-c", "--conf", action=ReadableFile,
                            dest="conf_file",
fabrice's avatar
fabrice committed
96
                            default=None, help="configuration file")
fabrice's avatar
fabrice committed
97
98
        parser.add_argument("--nolog", action="store_true",
                            default=False, help="Don't generate log files")
fabrice's avatar
fabrice committed
99
100
101
102
103
104
105
106
107
108
109
110
        # Create subcommands
        self._create_subparsers(parser.add_subparsers(dest="command"))
        return parser

    def _create_subparsers(self, parser):
        """
        Generate subcommands
        :param parser: argparser object
        :return:
        """
        for index, command in enumerate(self.command_list):
            # Create subparser defined in command list
111
112
113
            subcommand = getattr(self, "_" + command + "_parser")(
                desc=self.desc_list[
                    index])
fabrice's avatar
fabrice committed
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
            parser.add_parser(command, parents=[subcommand])

    def _setup_parser(self, desc=None):
        """
        setup opt & args
        :param desc: command descriptor
        :return: argparser object
        """
        parser = argp.ArgumentParser(description=desc,
                                     add_help=False)
        # Options
        # Args
        group = parser.add_argument_group('required arguments')
        group.add_argument("seq", action=ReadableFile,
                           help="sequence file [FASTA]")
        group.add_argument("sspred", action=ReadableFile,
                           help="secondary structure prediction file")
        group.add_argument("infiles", nargs="+", metavar="infile",
                           action=ReadableFile,
                           help="contact or pdb file(s) used to build aria "
                                "distance restraints")
        group.add_argument("-d", "--distfile", dest="distfile",
                           help="Pdb or distance matrix iif distance_type "
                                "set  to   distfile in conf  file,  "
                                "use distances in the  given file as "
                                "target  distance to build  distance "
                                "restraints")
        group.add_argument("-t", "--type", required=True,
                           nargs="+", dest="contact_types",
                           choices=self.contact_types, help="Infile(s) contact "
                                                            "type(s)")
        group.add_argument("-r", "--ref", dest="ref",
                           help="Native pdb. Allow TP/FP detection.")
        group.add_argument("--hb", dest="hb",
                           help="H-bonds contact file (eg: metapsicov.hb)")
        group.add_argument("--ssidx", dest="ssidx", action="store_true",
                           default=False, help="Use secondary structure index")
        return parser

    def _bbconv_parser(self, desc=None):
        """
        bbconv opt & args
        :param desc: command descriptor
        :return: argparser object
        """
        parser = argp.ArgumentParser(description=desc,
                                     add_help=False)
        # args
        parser.add_argument("contactfile", help="contacts file (pconsc, plm)",
                            action=ReadableFile)
        parser.add_argument("sspred", help="psipred file",
                            action=ReadableFile)
        parser.add_argument("seq", help="sequence file [FASTA]",
                            action=ReadableFile)
        parser.add_argument("msa", nargs='?',
                            help="MSA [FASTA] for diversityvalue"
                                 "used with bbcontacts")
        parser.add_argument("-t", "--type", required=True, dest="contact_type",
                            choices=self.contact_types, help="Infile contact "
                                                             "type")
        return parser

    def _contactmap_parser(self, desc=None):
        """
        contactmap opt & args
        :param desc: command descriptor
        :return: argparser object
        """
        parser = argp.ArgumentParser(description=desc,
                                     add_help=False)
        parser.add_argument("seq", action=ReadableFile,
                            help="sequence file [FASTA]")
        parser.add_argument("sspred", action=ReadableFile,
                            help="secondary structure prediction file")
        parser.add_argument("infiles", nargs="+", metavar="infile",
                            action=ReadableFile,
                            help="contact or pdb file(s) used to build aria "
                                 "distance restraints")
        parser.add_argument("-t", "--type", required=True,
                            nargs="+", dest="contact_types",
                            choices=self.contact_types, help="Infile(s) "
                                                             "contact "
                                                             "type(s)")
fabrice's avatar
fabrice committed
197
198
199
        parser.add_argument("--merge", nargs="+", dest="merge",
                            choices=self.contact_types,
                            help="Merge given contact types with other maps")
200
201
202
        parser.add_argument("--filter", dest="nofilter", action="store_true",
                            default=False, help="Use contact list filter "
                                                "and top n contacts selection")
fabrice's avatar
fabrice committed
203
204
205
        parser.add_argument("--onlyreport", dest="onlyreport",
                            action="store_true",
                            default=False, help="Generate only report file")
fabrice's avatar
fabrice committed
206
207
208
        parser.add_argument("--ssidx", dest="ssidx", action="store_true",
                            default=False,
                            help="Use secondary structure index")
fabrice's avatar
fabrice committed
209
        parser.add_argument("--prefix", dest="prefix", default="",
210
                            help="Contact map name", nargs="+")
fabrice's avatar
fabrice committed
211
212
213
        return parser

    def create_settings(self):
214
215
216
217
        """
        create settings relative to args.command
        :return:
        """
218
        LOG.debug("Create AriaEcSettings")
219
        settings = AriaEcSettings(self.args.command)
220
        LOG.info("Loading default config file")
fabrice's avatar
fabrice committed
221
222
        settings.load_config(self.default_confile, pkg=True)
        if self.args.conf_file:
223
            LOG.info("Updating settings with conf file")
fabrice's avatar
fabrice committed
224
225
            settings.load_config(self.args.conf_file)
        # Update settings associated to command section
226
        LOG.info("Updating %s settings with args", self.args.command)
fabrice's avatar
fabrice committed
227
228
        getattr(settings, self.args.command).args.update(self.args.__dict__)
        if self.args.output_directory:
229
            LOG.info("Updating output directory")
fabrice's avatar
fabrice committed
230
231
232
233
            settings.infra = self.args.output_directory
        return settings

    def run(self):
234
235
236
        """
        call method relative to args.command
        """
237
        LOG.info("Run %s command", self.args.command)
fabrice's avatar
fabrice committed
238
239
240
        getattr(self, self.args.command)()

    def setup(self):
241
242
243
        """
        Setup call
        """
fabrice's avatar
fabrice committed
244
245
246
247
        setup_inst = AriaEcSetup(self.create_settings())
        setup_inst.run()

    def bbconv(self):
248
249
250
        """
        bbcontacts converter call
        """
fabrice's avatar
fabrice committed
251
252
253
254
        bbconverter = AriaEcBbConverter(self.create_settings())
        bbconverter.run()

    def contactmap(self):
255
256
257
        """
        instantiate AriaEcContactmap with AriaSettings
        """
fabrice's avatar
fabrice committed
258
259
260
261
262
263
264
        econtactmap = AriaEcContactMap(self.create_settings())
        econtactmap.run()


if __name__ == "__main__":
    # Test AriaEcCommand object
    logging.basicConfig(level=logging.DEBUG)
265
    LOG = logging.getLogger("IO")
fabrice's avatar
fabrice committed
266
    argparser = AriaEcCommand()