commands.py 10.3 KB
Newer Older
fabrice's avatar
fabrice committed
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
"""
                            Input/Output aria_ec
"""
from __future__ import absolute_import, division, print_function

import os
import logging
import argparse as argp

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

logger = logging.getLogger(__name__)


def check_file(prospective_file):

    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):

    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
class AriaEcCommand:
    """
    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")
51
52
53
54
    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
55
56
57
58
59
60
61
62
63
64
65
66
    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()
        # Update logger with outdir
        self._update_logger(custom_logging)

    def _update_logger(self, log):
        if log and hasattr(self.args, "output_directory"):
fabrice's avatar
fabrice committed
67
68
69
70
71
72
73
            if not self.args.nolog:
                # Don't generate log files
                # TODO: get handler list from json file or customlogging object
                logger.removeHandler("info_file_handler")
                logger.removeHandler("error_file_handler")
                logger.removeHandler("debug_file_handler")
                log.set_outdir(self.args.output_directory)
fabrice's avatar
fabrice committed
74
75
76
77
78
79
80
81
            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",
82
                            type=str, help="Output directory", required=True)
fabrice's avatar
fabrice committed
83
84
        parser.add_argument("-c", "--conf", action=ReadableFile, dest="conf_file",
                            default=None, help="configuration file")
fabrice's avatar
fabrice committed
85
86
        parser.add_argument("--nolog", action="store_true",
                            default=False, help="Don't generate log files")
fabrice's avatar
fabrice committed
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
        # 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
            subcommand = getattr(self, "_" + command + "_parser")(desc=self.desc_list[
                index])
            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
184
185
186
        parser.add_argument("--merge", nargs="+", dest="merge",
                            choices=self.contact_types,
                            help="Merge given contact types with other maps")
fabrice's avatar
fabrice committed
187
188
189
190
        parser.add_argument("--nofilter", dest="nofilter", action="store_true",
                            default=None, help="Do not use contact list "
                                               "filter and select top n "
                                               "contacts")
fabrice's avatar
fabrice committed
191
192
193
        parser.add_argument("--onlyreport", dest="onlyreport",
                            action="store_true",
                            default=False, help="Generate only report file")
fabrice's avatar
fabrice committed
194
195
196
        parser.add_argument("--ssidx", dest="ssidx", action="store_true",
                            default=False,
                            help="Use secondary structure index")
fabrice's avatar
fabrice committed
197
        parser.add_argument("--prefix", dest="prefix", default="",
198
                            help="Contact map name", nargs="+")
fabrice's avatar
fabrice committed
199
200
201
202
        return parser

    def create_settings(self):
        logger.debug("Create AriaEcSettings")
203
        settings = AriaEcSettings(self.args.command)
fabrice's avatar
fabrice committed
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
        logger.info("Loading default config file")
        settings.load_config(self.default_confile, pkg=True)
        if self.args.conf_file:
            logger.info("Updating settings with conf file")
            settings.load_config(self.args.conf_file)
        # Update settings associated to command section
        logger.info("Updating %s settings with args" % self.args.command)
        getattr(settings, self.args.command).args.update(self.args.__dict__)
        if self.args.output_directory:
            logger.info("Updating output directory")
            settings.infra = self.args.output_directory
        return settings

    def run(self):
        # call method relative to args.command
        logger.info("Run %s command" % self.args.command)
        getattr(self, self.args.command)()

    def setup(self):
        setup_inst = AriaEcSetup(self.create_settings())
        setup_inst.run()

    def bbconv(self):
        bbconverter = AriaEcBbConverter(self.create_settings())
        bbconverter.run()

    def contactmap(self):
        # instantiate AriaEcContactmap with AriaSettings
        econtactmap = AriaEcContactMap(self.create_settings())
        econtactmap.run()


if __name__ == "__main__":
    # Test AriaEcCommand object
    logging.basicConfig(level=logging.DEBUG)
    logger = logging.getLogger("IO")
    argparser = AriaEcCommand()