setup.py 12.9 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
"""
                            Input/Output aria_ec scripts
"""
from __future__ import absolute_import, division, print_function

import logging
import json
import os

from .protein import Protein
from .reader import ProtFileListReader
from .base import get_filename
from .protmap import MapFilter
from .econverter import AriaEcXMLConverter

# TODO: S'inspirer de pandas/__init__.py pour les dependances
# from basictools import *

logger = logging.getLogger(__name__)


class AriaEcSetup:
    def __init__(self, settings):
fabrice's avatar
fabrice committed
24
25
26
27
28
        """

        :param settings:
        :return:
        """
fabrice's avatar
fabrice committed
29
30
31
32
33
34
35
36
37
38
39
40
41
        # TODO: check_type settings (AriaEcSettings)
        self.settings = settings
        self.protein = Protein(settings)
        self.outprefix = ''
        self.reader = ProtFileListReader(cont_def=settings.contactdef.config)
        self.allresmap = {}
        self.targetmap = None
        self.refmaps = None
        self.hbmaps = None
        self.filter = MapFilter(settings.setup.config)
        self.converter = AriaEcXMLConverter(settings)

    def run(self):
fabrice's avatar
fabrice committed
42
43
44
45
        """

        :return:
        """
fabrice's avatar
fabrice committed
46
47
48
49
50
        # Check input
        logger.debug("Settings:\n" + json.dumps(self.settings.setup.config,
                                                indent=4))
        logger.debug("Args:\n" + json.dumps(self.settings.setup.args,
                                            indent=4))
fabrice's avatar
fabrice committed
51
        self.settings.make_infra()
fabrice's avatar
fabrice committed
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
        # -------------------------------------------------------------------- #
        # ----------------------------- Input -------------------------------- #
        # -------------------------------------------------------------------- #
        self.outprefix = get_filename(self.settings.setup.args.get("seq",
                                                                   None))
        self.converter.outprefix = self.outprefix
        # ------------------------- Load sequence ---------------------------- #
        self.protein.set_aa_sequence(self.settings.setup.args.get("seq", None))
        # -------------- Load secondary structure prediction ----------------- #
        ss_file = self.settings.main.config["ss_dist_file"] if \
            self.settings.main.config["ss_dist_file"] else None
        self.protein.set_sec_struct(self.settings.setup.args.get("sspred",
                                                                 None),
                                    ss_file,
                                    ssidx=self.settings.setup.args.get(
                                        "ssidx", False))
        # -------------------------------------------------------------------- #
        # ---------------------------- Processing ---------------------------- #
        # -------------------------------------------------------------------- #
        # TODO: write submatrix in a file
        # TODO: change read method in reader to __call__ ?
        # -------------------------- contact maps ---------------------------- #
        self.reader.read(self.settings.setup.args.get("infiles"),
                         filetypelist=self.settings.setup.args.get("contact_types"),
                         protein=self.protein,
                         groupby_method=self.settings.setup.config['groupby_method'],
                         scsc=self.settings.scsc_min)
        for fo in self.reader.filelist:
            # fo need a contactmap in order to wite XML dist restraints
            # TODO: filter pour toutes les map de mapdict !! (fonction remove
            #  s'applique sur l'humanidx contenant les residus)
            self.filter(fo.mapdict, fo.filetype, fo.contactlist, self.protein,
                        clashlist=fo.clashlist, outprefix=self.outprefix,
                        outdir=self.settings.outdir)
            self.allresmap[fo.filetype] = fo.mapdict

            if fo.filetype != "pdb" and "pdb" in self.allresmap:
89
                fo.contactmap.compareplot(self.allresmap["pdb"])
fabrice's avatar
fabrice committed
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

        # ---------------------------- target map ---------------------------- #
        if self.settings.setup.args.get("distfile") and \
                self.settings.setup.config.get("distance_type") == "distfile":
            logger.info("Loading target distance file")
            # Read distance file
            self.reader.read(
                self.settings.setup.args.get("distfile"),
                filetypelist="distfile",
                protein=self.protein,
                groupby_method=self.settings.setup.config['groupby_method'],
                scsc=self.settings.scsc_min)
            self.targetmap = self.converter.targetdistmap(
                self.settings.setup.config.get("distance_type"),
                self.protein.aa_sequence.sequence,
                distfile=self.reader.filelist[0],
                groupby=self.settings.setup.config['groupby_method'])
        else:
            # Default targetmap using config parameters
            self.targetmap = self.converter.targetdistmap(
                self.settings.setup.config.get("distance_type"),
                self.protein.aa_sequence.sequence,
                groupby=self.settings.setup.config['groupby_method'])

        # ---------------------------- ref map ----------------------------- #
        if self.settings.setup.args.get("ref"):
            self.reader.read(
                self.settings.setup.args.get("ref"),
                filetypelist="pdb",
                protein=self.protein,
                groupby_method=self.settings.setup.config['groupby_method'],
                scsc=self.settings.scsc_min)
            self.refmaps = self.reader.filelist[0].mapdict

        # ---------------------------- hbond map ----------------------------- #
        if self.settings.setup.args.get("hb") and \
                self.settings.setup.config.get("longrange_hb", False):
            self.reader.read(
                self.settings.setup.args.get("hb"),
                filetypelist="metapsicovhb",
                protein=self.protein,
                groupby_method=self.settings.setup.config['groupby_method'],
                scsc=self.settings.scsc_min)
            self.hbmaps = self.reader.filelist[0].mapdict
        elif self.settings.setup.config.get("longrange_hb", False):
            # Create HBMAP with naive metapsicov method
            # Consider as hbond ec predicted between beta strand
            raise NotImplementedError

        # -------------------------------------------------------------------- #
        # ------------------------------ Output ------------------------------ #

        # ----------------------------- SEQ file ----------------------------- #
        self.protein.write_seq(os.path.join(self.settings.infra.get("others", ''),
                                            self.outprefix + ".seq"))

        # --------------------------- TBL restraints ------------------------- #
        # Setting contact number limit for hbmap
        n_hb = int(len(self.protein.aa_sequence.sequence) *
                   self.settings.setup.config.get("nf_longrange_hb"))
        tbl_files = self.converter.write_tbl_restraints(
            self.protein, hbmap=self.hbmaps, n_hb=n_hb)

        # --------------------------- XML restraints ------------------------- #
        # Setting contact number limit for map restraints (native, ec, ...)
155
156
157
        # nb_c = int(len(self.protein.aa_sequence.sequence) *
        #            self.settings.setup.config.get("n_factor"))

fabrice's avatar
fabrice committed
158
        dist_files, pair_lists = self.converter.write_maplist_restraints(
159
            self.allresmap, self.targetmap)
fabrice's avatar
fabrice committed
160
161
162
163
164
165

        # --------------------------- XML SEQ file --------------------------- #
        seq_file = self.converter.write_xmlseq(self.protein.seqfile_path)

        # ---------------------- ARIA XML project file ----------------------- #
        aria_template = self.settings.main.config["ariaproject_template"] if \
166
            self.settings.main.config["ariaproject_template"] and \
fabrice's avatar
fabrice committed
167
            os.path.exists(self.settings.main.config["ariaproject_template"])\
168
            else None
fabrice's avatar
fabrice committed
169
170
171
172
173
174
175
        self.converter.write_project(aria_template,
                                     seq_file, dist_files, tbl_files,
                                     desc="_".join(sorted(self.allresmap.keys())))
        # ------------------------------ others ------------------------------ #
        self.write_optional_files()

    def write_optional_files(self):
fabrice's avatar
fabrice committed
176
177
178
179
        """

        :return:
        """
fabrice's avatar
fabrice committed
180
181
182
183
184
        # Indextableplus file (submatrix)
        # Contacts_refined.out
        for maptype in self.allresmap:
            self.allresmap[maptype].get("contactmap").write_contacts(
                "_".join((self.outprefix, maptype, "filtered")),
185
186
                self.settings.infra.get("others"), scoremap=self.allresmap[
                    maptype].get("scoremap"))
fabrice's avatar
fabrice committed
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
            if self.allresmap[maptype]["alldistmap"] is not None:
                self.allresmap[maptype]["alldistmap"].to_csv(
                    "%s/%s.distmap.csv" % (self.settings.infra.get("others"),
                                           maptype))
            if self.refmaps:
                self._write_contacts(self.allresmap[maptype].get(
                    "filteredlist", None), self.protein.aa_sequence.sequence,
                    self.settings.infra.get("others", ''), "_".join((
                        self.outprefix, maptype, "filtered")),
                    ref=self.refmaps["contactmap"],
                    distmap=self.refmaps["distmap"])
        if self.refmaps:
            self.refmaps["alldistmap"].to_csv(
                "%s/%s_%s.distmap.csv" % (self.settings.infra.get("others"),
                                          self.outprefix, self.refmaps.filetype))

    def _write_contacts(self, contacts_list, seq, out, prefix, nc=None,
                        append=False, ref=None, distmap=None):
        """
        Write contacts from contact_list (sorted !)
        :param contacts_list:
        :param seq:
        :param out:
        :param prefix:
        :param nc:
        :param append:
        :param ref:
        :return:
        """
        mapy = []
        tp = 0
        filemode = 'a' if append else 'w'
        dist_desc = '\tTP/FP\tdist%s(ref)' % self.settings.setup.config[
            "groupby_method"] if \
            distmap is not None \
            else ''
        with open("%s/%s.contacts.txt" % (out, prefix), filemode) as outfile:
            if not append:
                outfile.write('''# resid1\tresid2\tres1\tres2%s\n''' % dist_desc)

            if type(contacts_list) is dict:
                contacts = contacts_list.keys() if not nc else contacts_list.keys()[:nc]
                d_type = True
            else:
                # Check if contacts is 2-tuple
                if False in [len(item) == 2 for item in contacts_list]:
                    raise TypeError('Contact list must be 2-tuple !')
                contacts = contacts_list if not nc else contacts_list[:nc]
                d_type = False
            logger.debug("Contact list %s" % contacts)
            for contact in contacts:

                if d_type:
                    # If dictionary
                    resid1 = int(contacts_list[contact].setdefault('res1_nb'))
                    resid2 = int(contacts_list[contact].setdefault('res2_nb'))
                else:
                    resid1 = int(contact[0])
                    resid2 = int(contact[1])

                logger.debug("Contact %s" % (str(contact)))
                if distmap is not None:
                    dist = distmap.ix[(resid1, resid2)]
                else:
                    dist = {'dist': '', 'atoms': ''}

                if (resid1, resid2) not in mapy:
                    mapy.append((resid1, resid2))
                    if ref is not None:
                        if ref.ix[(resid1, resid2)]:
                            asses = 'TP'
                            tp += 1
                        else:
                            asses = 'FP'
                        outfile.write(
                            "%s\t%s\t%s\t%s\t%s\t%s\n" % (resid1 + 1,
                                                          resid2 + 1,
                                                          seq[resid1],
                                                          seq[resid2], asses,
                                                          dist))
                    else:
                        outfile.write("%s\t%s\t%s\t%s\n" % (resid1 + 1,
                                                            resid2 + 1,
                                                            seq[resid1],
                                                            seq[resid2]))

            ptp = (tp / float(len(contacts))) * 100.0 if ref is not None else \
                None
            outfile.write('''
# TP number : {tp} ({ptp:.2f} %)
# Number of contacts : {nc}
    '''.format(tp=tp, ptp=ptp, nc=len(contacts)))


if __name__ == "__main__":
    # Test AriaEcCommand object
    from .ecsettings import AriaEcSettings

    logging.basicConfig(level=logging.DEBUG)
    logger = logging.getLogger("Setup")
287
    AriaEcSettings('setup').load_config('aria_ec.ini')