setup.py 12.6 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
"""
                            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 *

19
LOG = logging.getLogger(__name__)
fabrice's avatar
fabrice committed
20
21
22
23


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
        # Check input
47
48
49
50
        LOG.debug("Settings:\n" + json.dumps(self.settings.setup.config,
                                             indent=4))
        LOG.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
        # -------------------------------------------------------------------- #
        # ----------------------------- Input -------------------------------- #
        # -------------------------------------------------------------------- #
        self.outprefix = get_filename(self.settings.setup.args.get("seq",
                                                                   None))
57
        self.converter.outprefix = self.outprefix
fabrice's avatar
fabrice committed
58
59
60
61
62
        # ------------------------- Load sequence ---------------------------- #
        self.protein.set_aa_sequence(self.settings.setup.args.get("seq", None))
        # -------------- Load secondary structure prediction ----------------- #
        self.protein.set_sec_struct(self.settings.setup.args.get("sspred",
                                                                 None),
63
                                    ssdist_filename=self.settings.ssdist,
fabrice's avatar
fabrice committed
64
65
66
67
68
69
                                    ssidx=self.settings.setup.args.get(
                                        "ssidx", False))
        # -------------------------------------------------------------------- #
        # ---------------------------- Processing ---------------------------- #
        # -------------------------------------------------------------------- #
        # TODO: write submatrix in a file
70
        # TODO: change read method in reader to __call__
fabrice's avatar
fabrice committed
71
72
73
74
75
76
77
78
79
80
81
82
        # -------------------------- 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,
83
                        outdir=self.settings.infra.get("others", ''))
fabrice's avatar
fabrice committed
84
85
86
            self.allresmap[fo.filetype] = fo.mapdict

            if fo.filetype != "pdb" and "pdb" in self.allresmap:
87
                fo.contactmap.compareplot(self.allresmap["pdb"])
fabrice's avatar
fabrice committed
88
89
90
91

        # ---------------------------- target map ---------------------------- #
        if self.settings.setup.args.get("distfile") and \
                self.settings.setup.config.get("distance_type") == "distfile":
92
            LOG.info("Loading target distance file")
fabrice's avatar
fabrice committed
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
            # 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"))
143
144
        # Load aria molecule object from generated seq file
        self.converter.load_molecule(self.protein.seqfile_path)
fabrice's avatar
fabrice committed
145
146
147
148
        # --------------------------- 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"))
149
        LOG.info("Writing tbl files ...")
fabrice's avatar
fabrice committed
150
151
152
153
154
        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

        # --------------------------- XML SEQ file --------------------------- #
162
        xmlseq_file = self.converter.write_xmlseq()
fabrice's avatar
fabrice committed
163
164

        # ---------------------- ARIA XML project file ----------------------- #
165
        self.converter.write_ariaproject(self.settings.template,
166
                                         xmlseq_file, dist_files, tbl_files)
fabrice's avatar
fabrice committed
167
168
169
170
        # ------------------------------ others ------------------------------ #
        self.write_optional_files()

    def write_optional_files(self):
fabrice's avatar
fabrice committed
171
172
173
174
        """

        :return:
        """
fabrice's avatar
fabrice committed
175
176
177
178
179
        # Indextableplus file (submatrix)
        # Contacts_refined.out
        for maptype in self.allresmap:
            self.allresmap[maptype].get("contactmap").write_contacts(
                "_".join((self.outprefix, maptype, "filtered")),
180
181
                self.settings.infra.get("others"), scoremap=self.allresmap[
                    maptype].get("scoremap"))
fabrice's avatar
fabrice committed
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
            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
231
            LOG.debug("Contact list %s", contacts)
fabrice's avatar
fabrice committed
232
233
234
235
236
237
238
239
240
241
            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])

242
                LOG.debug("Contact %s", str(contact))
fabrice's avatar
fabrice committed
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
                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)
281
    LOG = logging.getLogger("Setup")
282
    AriaEcSettings('setup').load_config('aria_ec.ini')