protmap.py 49.3 KB
Newer Older
fabrice's avatar
fabrice committed
1
2
3
4
5
"""
                    ARIA Evolutionary Constraints Tools
"""
from __future__ import absolute_import, division, print_function

6
import matplotlib
7

8
matplotlib.use("Agg", warn=False)
9
10
11

import os
import re
fabrice's avatar
fabrice committed
12
13
14
15
16
17
18
import logging
import collections
import itertools
import operator
import pandas as pd
import seaborn as sns
import numpy as np
19
import datetime
20
from matplotlib import pyplot as plt
fabrice's avatar
fabrice committed
21
22
23
24
import aria.ConversionTable as ConversionTable
import aria.legacy.AminoAcid as AminoAcid
from matplotlib.lines import Line2D
from .base import (tickmin, tickrot, titleprint)
25
26
import sklearn.metrics as skm

fabrice's avatar
fabrice committed
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45

logger = logging.getLogger(__name__)


# TODO: check dataframe symmetry or always use unstack
# TODO: objet MapContainer contenant les differentes maps en attributs ! (et
# non en clef de dict)

class Map(pd.DataFrame):
    """
    Distance/contact matrix
    """

    mtype_choices = {'contact': bool, 'distance': float, "score": float}

    def _constructor_expanddim(self):
        super(Map, self)._constructor_expanddim()

    def __init__(self, index=None, columns=None, mtype='distance',
46
47
                 duplicate_levels=False, data=None, dtype=None, sym=True,
                 desc=""):
fabrice's avatar
fabrice committed
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
        """
        :param index:
        :param columns:
        :param mtype:
        :param duplicate_levels: Allow duplicate levels in dataframe humanidx
        :param data:
        :param dtype:
        :param sym:
        :return:
        """
        if not dtype:
            dtype = self.check_type(mtype)
        if data is None:
            data = False if mtype == bool else 0.
        super(Map, self).__init__(data, dtype=dtype, index=index,
                                  columns=columns)
        self.duplicate_levels = duplicate_levels
        self.dtype = dtype
        if mtype == "score":
            self.sort_list = []
        self.sym = sym
69
        self.desc = desc
fabrice's avatar
fabrice committed
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

    def sortedset(self, human_idx=False):
        # Remove duplicate in sort_list
        n = 1 if human_idx else 0
        if hasattr(self, "sort_list"):
            if self.sym:
                # Use OrderedDict to keep the order
                return [(x + n, y + n)
                        for x, y in
                        collections.OrderedDict.fromkeys(frozenset(x)
                                                         for x in
                                                         self.sort_list)]
            else:
                # Asym matrix, no need to remove duplicate
                return [(x + n, y + n) for x, y in self.sort_list]
        else:
            return None

    def check_type(self, mtype):
        value = self.mtype_choices.get(mtype)
        if value:
            return value
        else:
            logger.error("Map type should be in list %s" %
                         self.mtype_choices.keys())
            return None

    def reduce(self):
        columns = ['-'.join(idx) for idx in self.columns]
        index = ['-'.join(idx) for idx in self.index]
        return getattr(self, '__init__')(self.sequence,
                                         data=self.as_matrix(),
102
103
                                         index=index, desc=self.desc,
                                         sym=self.sym, mtype=self.mtype,
fabrice's avatar
fabrice committed
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
                                         columns=columns, dtype=self.dtype)

    def remove(self, rm_list):
        # Reset values at positions in rm_list
        value = False if self.dtype == bool else 0.0
        for contact in rm_list:
            idx1, idx2 = self.index[contact[0]], self.index[contact[1]]
            self.set_value(idx1, idx2, value)
            # self.iat[(contact[0], contact[1])] = value
            # self.iat[(contact[1], contact[0])] = value
            if hasattr(self, 'sort_list'):
                # ! sort_list start at 1
                if (contact[0], contact[1]) in self.sort_list:
                    self.sort_list.remove((contact[0], contact[1]))
                if (contact[1], contact[0]) in self.sort_list and self.sym:
                    self.sort_list.remove((contact[1], contact[0]))

    def to_series(self):
        # Return panda series related to lower triangle
        df = self.copy()
        df = df.astype(float)
        # remove values from upper triangle
        df.values[np.triu_indices_from(df, k=1)] = np.nan
        # pd.series with only lower triangle values
        return df.unstack().dropna()

    def topmap(self, scoremap, nb_topcontact):
        if self.dtype != bool:
            logger.info("Error when retrieving top contact map. The type of "
                        "the given map is not a contact type!")
            return self
        self[:] = False
        if self.shape == scoremap.shape:
            pair_list = scoremap.sortedset()[:nb_topcontact]
            for contact in pair_list:
                self.iat[(contact[1], contact[0])] = True
                self.iat[(contact[0], contact[1])] = True
            return self
        else:
            logger.error("Given scoremap has not the same dimension !")
            return None

    def subfill(self, pairdict, level=0):
        """
        Fill map with dict giving
        :param pairdict:
        :param level:
        :return:
        """
        pairdict = {k.upper(): v for k, v in pairdict.items()}
        if "def" in pairdict:
            self[:] = pairdict["def"]
        for idxval in pairdict:
            idx = self.index.get_level_values(level) == idxval
            self.loc[idx, idx] = pairdict[idxval]

    def set_value(self, index, col, value, **kwargs):
        super(Map, self).set_value(index, col, value, **kwargs)
        if self.sym:
            super(Map, self).set_value(col, index, value, **kwargs)


class ProteinMap(Map):

    # TODO: Matrices PosAaAtmMap, AaAtmMap, AtmMap
    def __init__(self, sequence, flaglist=None, seqidx=None, index=None,
                 columns=None, **kwargs):
        idx, col = self.create_index(sequence, seqidx=seqidx, idxnames=index,
                                     colnames=columns)
        kwargs["index"] = idx
        kwargs["columns"] = col
        super(ProteinMap, self).__init__(**kwargs)
        self.contact_flags = flaglist if flaglist else None
fabrice's avatar
fabrice committed
177
        self._maplot = None
fabrice's avatar
fabrice committed
178
179
180
181
182
183
184
185

    def _constructor_expanddim(self):
        super(ProteinMap, self)._constructor_expanddim()

    @property
    def sequence(self):
        raise NotImplementedError

fabrice's avatar
fabrice committed
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
    @property
    def maplot(self):
        # Contact map Plot
        if not self._maplot:
            minticks = tickmin(self, shift=1)  # Nb graduations

            self._maplot = sns.heatmap(self, square=True, cbar=False,
                                       linewidths=1, vmax=1, vmin=-1,
                                       cmap=sns.diverging_palette(20, 220, n=7,
                                                                  as_cmap=True),
                                       xticklabels=minticks[0],
                                       yticklabels=minticks[1])
        return self._maplot

    def saveplot(self, outdir='', outprefix="protein", size_fig=10,
                 plot_ext="pdf", plot_dpi=200):
202
203
        plotpath = os.path.join(outdir, "%s.contactmap.%s" % (
            outprefix, plot_ext))
204
        logger.info("Generate contact map plot (%s)" % plotpath)
205
        f, ax = plt.subplots(figsize=(12, 9))
fabrice's avatar
fabrice committed
206
207
208
209
210
211
212
        tickrot(self.maplot.axes, self.maplot.figure,
                rotype='horizontal')
        self.maplot.figure.set_size_inches(size_fig, size_fig)
        map_title = "%s contacts map" % outprefix
        self.maplot.set_title(map_title)
        self.maplot.figure.tight_layout()

213
        f.tight_layout()
214
        self.maplot.figure.savefig(plotpath, dpi=plot_dpi)
fabrice's avatar
fabrice committed
215

fabrice's avatar
fabrice committed
216
217
218
    def contactset(self, human_idx=False):
        # Remove duplicate in contact_list
        if self.contact_list():
219
220
            return sorted(set((tuple(sorted((x, y)))
                               for x, y in self.contact_list(human_idx))))
fabrice's avatar
fabrice committed
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
        else:
            return None

    def contact_list(self, human_idx=False):
        # Return contact list
        contact_list = []
        n = 1 if human_idx else 0
        if self.dtype is bool:
            for irow, row in enumerate(self):
                for icol, value in enumerate(self[row]):
                    if value:
                        contact_list.append((irow + n, icol + n))
            return contact_list
        else:
            return None

    def create_heatmap(self):
        raise NotImplementedError

    def contact_map(self, contactdef, scsc_min=None):
        raise NotImplementedError

    def create_index(self, sequence, seqidx=None, idxnames=None, colnames=None):
        """
        :param colnames:
        :param idxnames:
        :param seqidx:
        :param sequence: amino acid sequence
        :return: humanidx, columns (pd.Index or pd.MultiIndex)
        """
        # Indexation matrice (tous les atomes ou tous les residus)
        raise NotImplementedError

254
    def compareplot(self, protmap, save_fig=True, alpha=None, **kwargs):
fabrice's avatar
fabrice committed
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
        # Contact map plot
        if getattr(protmap, "shape") and self.shape != protmap.shape:
            logging.error("Cant't compare %s map with %s" % (
                protmap.__class__.__name__, self.__class__.__name__))
            return None
        else:
            cmplist = protmap.contact_list()

            ymax = len(self.sequence) - 1

            if protmap.contact_flags:
                flags = set(protmap.contact_flags.values())
                # Color palette
                pal = sns.color_palette("hls", len(flags))
                for i, flag in enumerate(flags):
                    conlist = [contact for contact in protmap.contact_flags if
                               protmap.contact_flags[contact] == flag]
                    xind = [x + .5 for x in
                            zip(*conlist)[0] + zip(*conlist)[1]]
                    yind = [ymax - y + .5 for y in
                            zip(*conlist)[1] + zip(*conlist)[0]]
                    color = pal[i]
                    mark = Line2D.filled_markers[i]
                    for x, y in zip(xind, yind):
fabrice's avatar
fabrice committed
279
280
281
                        self.maplot.axes.scatter(x, y, s=20, c=color,
                                                 linewidths=0, alpha=alpha,
                                                 marker=mark)
fabrice's avatar
fabrice committed
282
283
284
285
286
287
288
289
290
            else:
                xind = [x + .5 for x in
                        zip(*cmplist)[0] + zip(*cmplist)[1]]
                yind = [ymax - y + .5 for y in
                        zip(*cmplist)[1] + zip(*cmplist)[0]]
                color = "red"
                # width = [0.3 for _ in xind]
                # for x, y, h in zip(xind, yind, width):
                for x, y in zip(xind, yind):
fabrice's avatar
fabrice committed
291
292
                    self.maplot.axes.scatter(x, y, s=20, c=color, linewidths=0,
                                             alpha=alpha)
fabrice's avatar
fabrice committed
293
            if save_fig:
fabrice's avatar
fabrice committed
294
                self.saveplot(**kwargs)
fabrice's avatar
fabrice committed
295

296
297
    def report(self, cmpmap, scoremap, outprefix="", outdir="", plotdir="",
               plot_ext="pdf"):
298
299
300
        reportpath = "%s/%s.report" % (outdir, outprefix)
        logger.info("Generate report file (%s)" % reportpath)
        with open(reportpath, 'w') as reportf:
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
            y_true = list(self.values.astype(int).flat)
            y_pred = list(cmpmap.values.astype(int).flat)
            y_scores = list(scoremap.values.astype(float).flat)

            map1name = self.desc
            map2name = cmpmap.desc

            # ROC plot
            allfpr, alltpr, rocthresholds = skm.roc_curve(y_true, y_scores,
                                                          pos_label=1)
            roc_auc = skm.roc_auc_score(y_true, y_scores)
            plotpath = os.path.join(plotdir, "%s.roc.%s" % (outprefix,
                                                            plot_ext))
            plt.figure()
            plt.plot(allfpr, alltpr, label='ROC curve (area = %0.2f)' % roc_auc)
            plt.plot([0, 1], [0, 1], 'k--')
            plt.xlim([0.0, 1.0])
318
            plt.ylim([0.0, 1.0])
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
            plt.xlabel('False Positive Rate')
            plt.ylabel('True Positive Rate')
            plt.title('Receiver operating characteristic %s vs. %s' % (
                map1name, map2name))
            plt.legend(loc="lower right")
            plt.savefig(plotpath)

            allprec, allrec, prthresholds = skm.precision_recall_curve(
                y_true, y_scores)
            aver_prec = skm.average_precision_score(y_true, y_scores)
            plotpath = os.path.join(plotdir, "%s.precall.%s" % (outprefix,
                                                                plot_ext))
            # Precision recall curve
            plt.clf()
            plt.plot(allrec, allprec, label='Precision-Recall curve')
            plt.xlabel('Recall')
            plt.ylabel('Precision')
336
            plt.ylim([0.0, 1.0])
337
            plt.xlim([0.0, 1.0])
338
            plt.title('Precision-Recall {1} vs. {2}: AUC={0:0.2f}'.format(
fabrice's avatar
fabrice committed
339
                aver_prec, map1name, map2name))
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
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
            plt.legend(loc="lower left")
            plt.savefig(plotpath)

            msg = """\
## Report {map1name} vs. {map2name}
##
## Date: {date}
## Path: {outdir}
##
## -----------------------------------------------------------------------------
##
## Accuracy: {accuracy}
## Precision: {precision}
## Recall (Sensibility): {recall}
##
## Matthews correlation coefficient (MCC): {mcc}
## F1 score: {f1s}
## F2 score: {f2s}
## F0.5 score: {f05s}
##
## Hamming loss: {hamm}
## Hinge loss: {hin}
##
## -----------------------------------------------------------------------------
##
##                          Precision recall curve
##
## Precision values:
## {allprec}
## Recall values:
## {allrec}
## Score tresholds ({map2name}):
## {prthres}
##
## -----------------------------------------------------------------------------
##
##                               ROC curve
## Area Under Curve: {roc_auc}
## True Positive Rate (Sensibility) values:
## {alltpr}
## False Positive Rate (1 - Specificity) values:
## {allfpr}
## Score tresholds ({map2name}):
## {rocthres}
""".format(map1name=map1name, map2name=map2name,
                date=datetime.date.today().strftime("%A %d. %B %Y"),
                outdir=outdir, accuracy=skm.accuracy_score(y_true, y_pred),
                precision=skm.precision_score(y_true, y_pred),
                recall=skm.recall_score(y_true, y_pred),
                mcc=skm.matthews_corrcoef(y_true, y_pred),
                f1s=skm.f1_score(y_true, y_pred),
                f2s=skm.fbeta_score(y_true, y_pred, 2),
                f05s=skm.fbeta_score(y_true, y_pred, 0.5),
                hamm=skm.hamming_loss(y_true, y_pred),
                hin=skm.hinge_loss(y_true, y_pred),
                roc_auc=roc_auc, allprec=allprec, allrec=allrec,
                prthres=prthresholds, alltpr=alltpr, allfpr=allfpr,
                rocthres=rocthresholds)
            logger.debug("\n" + msg)
            reportf.write(msg)

    def compare_contactmap(self, cmpmap, contactlist, outprefix,
402
                           outdir="", distmap=None, human_idx=True):
fabrice's avatar
fabrice committed
403
        # CSV file giving TP/FP contacts
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
        outpath = "%s/%s.contactcmp.csv" % (outdir, outprefix)
        logger.info("Generate stat file (%s)" % outpath)
        with open(outpath, 'w') as outfile:
            offset = 1 if human_idx else 0
            extra_header = "" if distmap is None else ",dmin"
            print("#resid1,resid2,res1,res2,TP/FP%s" % extra_header, file=outfile)
            for x in contactlist:
                if extra_header:
                    dmin = "," + str(distmap.iat[(int(x[0]) - offset, int(x[1]) -
                                                  offset)])
                else:
                    dmin = ""
                contact = self.iat[(int(x[0]) - offset, int(x[1]) - offset)]
                cmpcontact = cmpmap.iat[(int(x[0]) - offset, int(x[1]) - offset)]
                if contact and cmpcontact:
                    eq = "TP"
                elif contact and not cmpcontact:
                    eq = "FP"
                elif not contact and cmpcontact:
                    eq = "FN"
                else:
                    eq = "TN"
                msg = "%s,%s,%s,%s,%s%s" % (x[0], x[1],
                                            self.sequence[int(x[0]) - offset],
                                            self.sequence[int(x[1]) - offset], eq,
                                            dmin)
                print(msg, file=outfile)
fabrice's avatar
fabrice committed
431

432
433
    def write_contacts(self, filename, outdir="", human_idx=True,
                       scoremap=None):
434
        filepath = "%s/%s.contact.txt" % (outdir, filename)
435
        logger.info("Generate contact file (%s)" % filepath)
436
437
438
439
440
441
        with open(filepath, 'w') as outfile:
            offset = 1 if human_idx else 0
            # contacts = [sorted(contact) for contact in self.contactset()]
            # for contact in sorted(contacts):
            for contact in self.contactset():
                contact = sorted([contact[0] + offset, contact[1] + offset])
442
443
444
445
446
447
448
                if scoremap is not None:
                    score = scoremap.iat[(int(contact[0]) - offset,
                                          int(contact[1]) - offset)]
                    print("%d %d %.4f" % (contact[0], contact[1], score),
                          file=outfile)
                else:
                    print("%d %d" % (contact[0], contact[1]), file=outfile)
fabrice's avatar
fabrice committed
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540

class ResAtmMap(ProteinMap):
    """
    Protein distance/contact matrix for all atom pairs. If no sequence given,
    protein distance/contact matrix for all amino acids
    Ex:
    residue           PHE1                                                    \
    atom               CD1       CD2        CB        CA        CG        CZ
    residue atom
    PHE1    CD1   0.000000  2.394145  2.455440  3.269219  1.391024  2.421148
            CD2   2.394145  0.000000  2.509243  3.407996  1.379875  2.401098
            CB    2.455440  2.509243  0.000000  1.507025  1.478053  4.267602
            CA    3.269219  3.407996  1.507025  0.000000  2.505414  5.085997
            CG    1.391024  1.379875  1.478053  2.505414  0.000000  2.790403

    """
    # Matrix only for heavy atoms.
    heavy_reg = re.compile("[CNOS][ABGDEZH][0-9]?")
    # TODO: Autre methodes de dist
    distance_method = 'euclidean'

    def _constructor_expanddim(self):
        super(ResAtmMap, self)._constructor_expanddim()

    def __init__(self, sequence=None, **kwargs):
        # Sequence: 1L string or MultiIndex object
        # Dataframe is in 3L code
        if not sequence:
            sequence = ConversionTable.ConversionTable().table['AMINO_ACID'][
                'iupac'].keys()
        super(ResAtmMap, self).__init__(sequence, **kwargs)

    @property
    def sequence(self):
        # Amino Acid sequence string in humanidx
        return "".join(AminoAcid.AminoAcid(_.split("-")[1])[0] for _ in
                       self.index.levels[0])

    def create_index(self, sequence, seq_pos=True, seqidx=None,
                     idxnames=None, colnames=None):
        logger.info("Indexing res - res dataframe")
        # Atom table for residues (keys are in 3L code)
        seqidx = seqidx if seqidx and len(seqidx) == len(sequence) else None
        iupac_aa = ConversionTable.ConversionTable().table['AMINO_ACID'][
            'iupac']
        # Amino acid conversion table 1L -> 3L
        # Making humanidx list for pandas dataframe
        seq = [AminoAcid.AminoAcid(aa)[1] for aa in sequence]
        # Repeat each res for each heavy atm (humanidx value + 1 in order to
        # start at 1 as in pdb file)
        if set(sequence) == sequence:
            # General ResAtmMap for 20 aminoacid
            res_list = ["%s" % aa for aa in seq for _ in
                        (filter(self.heavy_reg.match, iupac_aa[aa].keys()))]
        elif seqidx:
            res_list = [
                "%03d-%s" % (seqidx[i], aa) for i, aa in enumerate(seq)
                for _ in (filter(self.heavy_reg.match, iupac_aa[aa].keys()))]
        else:
            res_list = ["%03d-%s" % (i + 1, aa) for i, aa in enumerate(seq) for
                        _
                        in (filter(self.heavy_reg.match, iupac_aa[aa].keys()))]
        # TODO: Inutile de repeter a chaque fois le calcul des listes
        # d'atomes lourd pour chaque residu -> Deplacer au niveau de l'init
        atm_list = [atm for aa in seq for atm in filter(self.heavy_reg.match,
                                                        iupac_aa[aa].keys())]
        if len(atm_list) != len(res_list):
            logger.error("Index lists aren't the same size\n%s\n%s" % (
                res_list, atm_list))

        idxnames = idxnames if idxnames and len(idxnames) == 2 else [
            "residuex", "atomx"]
        colnames = colnames if colnames and len(colnames) == 2 else [
            "residuey", "atomy"]
        index = pd.MultiIndex.from_tuples(list(zip(*[res_list, atm_list])),
                                          names=idxnames)
        columns = pd.MultiIndex.from_tuples(list(zip(*[res_list,
                                                       atm_list])),
                                            names=colnames)
        logger.debug("Index:\n%s" % index)
        return index, columns

    def create_heatmap(self):
        unidf = self.reduce()
        if unidf.isnull().values.sum() == 0:
            # If there's no nan values
            return sns.heatmap(unidf)
        return None

    def reduce(self, groupby="min"):
        if self.index.nlevels == 1 or not groupby:
            return self
541
542
        newmap = ResMap(self.sequence, dtype=self.dtype, desc=self.desc,
                        sym=self.sym)
fabrice's avatar
fabrice committed
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
        if self.dtype == bool:
            newmap[:] = self.copy().stack().groupby(level=0).any()
        elif groupby == "mean":
            newmap[:] = self.copy().stack().groupby(level=0).mean()
        elif groupby == "min":
            newmap[:] = self.copy().stack().groupby(level=0).min()
        return newmap

    def contact_map(self, contactdef, scsc_min=None):
        """
        Contact map generator from all atoms distance map. There's a contact
        with 2 residues iff dist between 2 atoms are below the given treshold
        :param scsc_min:
        :param contactdef:
        for all atom pair
        :return:
        """
        if self.dtype == bool:
            # If self is already a contact map
            return None
fabrice's avatar
fabrice committed
563
        # TODO: issue with sc_sc treshold !!!!!
fabrice's avatar
fabrice committed
564
565
        logger.info("Generate contact map using contact definition %s" %
                    contactdef)
566
567
568
        # Initialize contact map to a boolean matrix filled with False
        contact_map = ResAtmMap(sequence=self.sequence, mtype="contact",
                                desc=self.desc, sym=self.sym)
fabrice's avatar
fabrice committed
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583

        if type(contactdef) == float:
            contact_map[:] = self.applymap(lambda x: x < contactdef)

        elif sum(x is not None for x in contactdef.values()) == 1 and \
                contactdef.get("default_cutoff"):
            logger.info("Using default cutoff")
            contact_map[:] = self.applymap(lambda x: x < contactdef.get("default_cutoff"))

        elif sum(x is not None for x in contactdef.values()) > 1:
            # treshconv = lambda x: x < contactdef.get("default_cutoff")
            # contact_map[:] = self.applymap(treshconv)
            atm_list = set(self.index.get_level_values(1))
            atms_list = set([(a, b) for a in atm_list for b in atm_list])
            for pair in contactdef.keys():
fabrice's avatar
fabrice committed
584
585
                if pair == "default_cutoff":
                    continue
fabrice's avatar
fabrice committed
586
587
                treshold = contactdef[pair]
                pair = tuple(pair.upper().split("_"))
fabrice's avatar
fabrice committed
588
589
590
591
                logger.info(
                    "Filtering values in matrix related to %s (%s)" %
                    (str(pair), str(treshold)))
                if pair in (("SC", "SC"), ("sc", "sc")):
fabrice's avatar
fabrice committed
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
                    # Use scsc_min to apply treshold only for selected atom
                    # sidechain
                    idx_list = []
                    col_list = []
                    for res1 in scsc_min:
                        for res2 in scsc_min[res1]:
                            pair = (AminoAcid.AminoAcid(res1)[1],
                                    AminoAcid.AminoAcid(res2)[1])
                            atm1, atm2 = scsc_min[res1][res2]
                            idx_list.append(
                                self.index.map(lambda x: x[0].endswith(
                                    pair[0]) and x[1] == atm1))
                            col_list.append(
                                self.index.map(lambda x: x[0].endswith(
                                    pair[1]) and x[1] == atm2))
                    mask = ([any(tup) for tup in zip(*idx_list)],
                            [any(tup) for tup in zip(*col_list)])
fabrice's avatar
fabrice committed
609
610
611
612
                elif pair not in atms_list:
                    logger.error("Pair %s doesn't exist ..." % str(pair))
                    # Already applied a treshold for this pair
                    continue
fabrice's avatar
fabrice committed
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
                else:
                    logger.debug("Apply treshold for %s" % str(pair))
                    atms_list.discard(pair)
                    # Selecting rows for each atom
                    mask = (self.index.get_level_values(1) == pair[0],
                            self.index.get_level_values(1) == pair[1])
                tmp = self.loc[mask].apply(lambda x: x < float(treshold))
                contact_map.update(tmp)
        else:
            logger.error("Missing values in contact definition section. Add "
                         "at least a default_cutoff value.")
        logger.debug("Contact map\n%s" % (contact_map.head()))
        return contact_map


class ResMap(ResAtmMap):
    """
    Res - res distance/contact matrix
    """

    def __init__(self, sequence, **kwargs):
        super(ResMap, self).__init__(sequence=sequence, **kwargs)

    def _constructor_expanddim(self):
        super(ResMap, self)._constructor_expanddim()

    @property
    def sequence(self):
        # Amino Acid sequence string in humanidx
        return "".join(AminoAcid.AminoAcid(aa.split("-")[1])[0] for aa in
                       self.index)

    def create_index(self, sequence, seqidx=None, idxnames=None,
                     colnames=None, **kwargs):
        # Index correspondant a la liste de residus
        seq = [AminoAcid.AminoAcid(aa)[1] for aa in sequence]
        seqidx = seqidx if seqidx and len(seqidx) == len(sequence) else None
        if seqidx:
            res_list = ["%03d-%s" % (seqidx[i], aa) for i, aa in enumerate(seq)]
        else:
            res_list = ["%03d-%s" % (i + 1, aa) for i, aa in enumerate(seq)]
        idxnames = idxnames if idxnames and len(idxnames) == 1 else ["residuex"]
        colnames = colnames if colnames and len(colnames) == 1 else ["residuey"]
        index = pd.Index(res_list, name=idxnames)
        col = pd.Index(res_list, name=colnames)
        return index, col

    def create_heatmap(self):
        if self.as_matrix().isnull().values.sum() == 0:
            # If there's no nan values
            return sns.heatmap(self.as_matrix())
        return None

    def contact_map(self, contactdef, **kwargs):
667
668
        contact_map = ResMap(self.sequence, mtype="contact", desc=self.desc,
                             sym=self.sym)
fabrice's avatar
fabrice committed
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000

        def treshconv(x):
            return x <= treshold

        # Applique treshold sur la matrice ssi c'est une matrice de distance
        if self.dtype == bool:
            # If self is already a contact map
            return None
        treshold = contactdef.get("default_cutoff", 5)
        contact_map[:] = self.applymap(treshconv)
        return contact_map


class AaMap(Map):
    """
    Amino Acid Distance Matrix
    """

    def _constructor_expanddim(self):
        super(AaMap, self)._constructor_expanddim()

    def __init__(self, *args, **kwargs):
        if ("humanidx", "columns") not in kwargs:
            idx, col = self.create_index()
            kwargs["humanidx"] = idx
            kwargs["columns"] = col
        super(AaMap, self).__init__(*args, **kwargs)

    @staticmethod
    def create_index():
        res_list = ConversionTable.ConversionTable().table['AMINO_ACID'][
            'iupac'].keys()
        index = pd.Index(res_list, name="residuex")
        col = pd.Index(res_list, name="residuey")
        return index, col


class AtmMap(Map):
    """
    Atom Distance Matrix
    """

    def _constructor_expanddim(self):
        super(AtmMap, self)._constructor_expanddim()

    def __init__(self, *args, **kwargs):
        super(AtmMap, self).__init__(*args, **kwargs)

    def create_index(self):
        pass


class MapFilter:
    """
    Filter contactmap/distancemap
        nd      : Network deconvolution
        pos     : remove close contacts
        cons    : remove contacts with highly conservated residues
        cys-cys : unicity of ss contacts
        ssclash : secondary structure conflict
    """
    filter_types = ("nd", "pos", "cons", "ssclash", "cys")
    clash_dict = {
        "nd": {
            "clash": "nd",
            "desc": "network deconvolution"},
        "pos": {
            "clash": "physical proximity",
            "desc": "sequence position"},
        "cons": {
            "clash": "888",
            "desc": "high conservation"},
        "ssclash": {
            "clash": "999",
            "desc": "secondary structure prediction conflict"},
        "cys": {
            "clash": "222",
            "desc": "disulfide bond unicity"}}

    def __init__(self, settings):
        self.settings = settings

    def nd_filter(self, mapdict, **kwargs):
        # TODO: build ROC curve with number of top contacts as the parameter
        logger.info("...Network deconvolution filter (alpha=%.2f, beta=%.2f, "
                    "control = %.2f)" % (self.settings["nd_beta"],
                                         self.settings["nd_alpha"],
                                         self.settings["nd_control"]))
        logger.warning("Not fully implemented !!")
        # (if refmap given !!!!)
        # To apply ND on regulatory networks, follow steps explained in
        # Supplementary notes 1.4.1 and 2.1 and 2.3 of the paper.
        return {'clash': None, 'desc': None}

    def pos_filter(self, mapdict, **kwargs):
        """
        Position filter on contactmap
        :param kwargs:
        :param mapdict: dict with contactmap key
        :return: 2-tuple of irrelevant pairs
        """
        # Liste les contacts proches
        clash_list = kwargs.get("clash_list")
        logger.info("...Position filter")
        close_list = []
        contact_list = mapdict["contactmap"].contact_list()

        for contact in contact_list:
            gap = abs(int(contact[0]) - int(contact[1]))
            if gap <= self.settings['position_treshold']:
                if clash_list and contact in clash_list:
                    continue
                close_list.append((contact[0], contact[1]))
        return {'clash': close_list, 'desc': None}

    def cons_filter(self, mapdict, **kwargs):
        # Liste les contacts aves des residus fortement conserves
        logger.info("...Conservation filter")
        sec_struct = kwargs.get("sec_struct")
        clash_list = kwargs.get("clash_list")
        cons_pair = []
        cons_res = []
        contact_list = mapdict["contactmap"].contact_list()

        if sec_struct.filetype != "indextableplus":
            logger.warning("Conservation filter only works with indextableplus "
                           "files !")
            return {'clash': None, 'desc': None}

        # parcours la liste de paires dans la matrice struct secondaire
        for index, reslist in enumerate(sec_struct.ss_matrix):
            if int(reslist[5]) > self.settings["conservation_treshold"] \
                    and reslist[1] != 'C':
                cons_res.append(index)

        for contact in contact_list:
            if contact[0] in cons_res or contact[1] in cons_res:
                if clash_list and contact in clash_list:
                    # If this clash already exist
                    continue
                cons_pair.append(contact)
        logger.debug("Highly conserverd residue list: %s" % cons_res)
        return {'clash': cons_pair, 'desc': None}

    @staticmethod
    def cys_filter(mapdict, **kwargs):
        # Si scoremap existe, selectionner les contacts cys-cys qui ont les
        # meilleurs scores, fournit une liste des contacts disulfures qui
        # possedent des scores plus faibles
        logger.info("...Disulfure bridge unicity filter")
        clash_list = kwargs.get("clash_list")
        unidisbridge_list = []  # Liste les ponts disulfures uniques
        clashdisbridge_list = []  # Liste les ponts disulfures incompatibles
        desc = []

        if mapdict.get("scoremap") is not None:
            scoremap = mapdict.get("scoremap")
            cys_list = [idx for idx, val in enumerate(scoremap.index.values)
                        if val.endswith('CYS')]
            dis_bridge_list = {ss: scoremap.iat[ss] for ss
                               in list(itertools.combinations(cys_list, 2))}
            if dis_bridge_list:
                sorted_ss = zip(*sorted(dis_bridge_list.items(),
                                        key=operator.itemgetter(1),
                                        reverse=True))[0]
            else:
                return {'clash': None, 'desc': None}
            for dis_bridge in sorted_ss:
                if dis_bridge in clash_list:
                    # given contact already removed with previous filters
                    continue
                else:
                    # Check for each cys in dis_bridge if they aready exists
                    # in unidisbridge_list
                    exdis = next((unidis for cys in dis_bridge for unidis in
                                  unidisbridge_list if cys in unidis), None)
                    if exdis:
                        if scoremap.iat[dis_bridge] > scoremap.iat[exdis]:
                            # Better cys--cys contact
                            # List cys-cys contacts that will be removed in
                            #  unidisbridge_list
                            remcys = (unidis for cys in dis_bridge for unidis
                                      in unidisbridge_list if cys in unidis)
                            for dis in remcys:
                                # PB si un des dis supprime est
                                clashdisbridge_list.append(dis)
                                clashdisbridge_list.append(dis[::-1])
                                unidisbridge_list.remove(dis)
                            unidisbridge_list.append(dis_bridge)
                        else:
                            clashdisbridge_list.append(dis_bridge)
                            clashdisbridge_list.append(dis_bridge[::-1])
                    else:
                        # New cys-cys contact
                        unidisbridge_list.append(dis_bridge)
            return {'clash': clashdisbridge_list, 'desc': desc}
        else:
            # If no score given, return empty list
            return {'clash': None, 'desc': None}

    @staticmethod
    def ssclash_filter(mapdict, **kwargs):

        def hum_contact(xy):
            return xy[0] + 1, xy[1] + 1

        # TODO: better add clash list and sec_struct as object attribute
        sec_struct = kwargs.get("sec_struct")
        clash_list = kwargs.get("clash_list")
        logger.info("...Secondary structure clash filter")
        ss_matrix = sec_struct.ss_matrix
        ss_list = zip(*ss_matrix)[2]
        # contact_list from contact map start at 0 !!
        contact_list = mapdict["contactmap"].contact_list()
        ssclash_pair = []
        desc_dict = {}
        ss_start_end = collections.defaultdict(lambda: [None, None])

        # TODO: deplacer construction du dic ss_start_end dans SsList
        for res_ind in xrange(len(ss_matrix)):
            # Construction du dict ss_start_end
            if res_ind == 0:
                # If first residue
                # Save ss start humanidx related to res_ind
                ss_start_end[ss_matrix[res_ind][2]][0] = res_ind
                if ss_matrix[res_ind][2][0] != ss_matrix[res_ind + 1][2][0]:
                    # If next res is not in the same ss
                    ss_start_end[ss_matrix[res_ind][2]][1] = res_ind
                    ss_start_end[ss_matrix[res_ind + 1][2]][0] = res_ind + 1
            elif res_ind == len(ss_matrix) - 1:
                # Si dernier res
                ss_start_end[ss_matrix[res_ind][2]][1] = res_ind
            elif ss_matrix[res_ind][2][0] != ss_matrix[res_ind + 1][2][0]:
                # If next res not in the same ss
                ss_start_end[ss_matrix[res_ind][2]][1] = res_ind
                ss_start_end[ss_matrix[res_ind + 1][2]][0] = res_ind + 1

        start_list = [ss_start_end[elm][0] for elm in ss_start_end]
        end_list = [ss_start_end[elm][1] for elm in ss_start_end]

        for icontact, contact in enumerate(contact_list):
            # For each res-res contact
            outcontact = str(hum_contact(contact))
            if contact in clash_list:
                continue
            resi = contact[0]  # Pos number (0...n-1)
            resj = contact[1]
            ssi = ss_list[resi]
            ssj = ss_list[resj]

            if ssi == ssj and (ssi[0], ssj[0]) in (("H", "H"), ("E", "E")):
                # If both residues are in same helix or strand
                desc = "%s,%s" % (ssi[0], ssj[0])
                desc_dict[contact] = desc
                logger.debug("Ss conflict for contact %d %s (%s)" % (
                    icontact, outcontact, desc))
                ssclash_pair.append(contact)
            # ELIF encadre H ou E
            elif ssi != ssj:
                # If both residues are not in the same ss
                ssclash = None
                for n in (1, 2, 3, 4):

                    # Search type of the bond (H-1 H, E-2 E, ...)
                    for i in xrange(2):
                        # Test both sides

                        resi = contact[i]
                        resj = contact[i - 1]
                        ssi = ss_list[resi]
                        ssj = ss_list[resj]

                        try:
                            ssi_pn = ss_list[resi + n]
                            ssi_mn = ss_list[resi - n]
                            ssj_pn = ss_list[resj + n]
                            ssj_mn = ss_list[resj - n]
                        except IndexError:
                            continue

                        # (E-n, E) OR (H-n, H)
                        if ssj[0] in ("H", "E") \
                                and resi + n in start_list \
                                and ssi_pn == ssj:
                            # --i**[-----j-----]--- (n: **)
                            #           E/H
                            ssclash = "%s-%d,%s" % (ssi_pn[0], n, ssj[0])
                            break
                        if ssj[0] in ("H", "E") \
                                and resi - n in end_list \
                                and ssi_mn == ssj:
                            # -----[-----j-----]**i--- (n: **)
                            #           E/H
                            ssclash = "%s+%d,%s" % (ssi_mn[0], n, ssj[0])
                            break
                        if ssi[0] in ("H", "E") \
                                and resj + n in start_list \
                                and ssj_pn == ssi:
                            # --j**[-----i-----]--- (n: **)
                            #           E/H
                            ssclash = "%s-%d,%s" % (ssj_pn[0], n, ssi[0])
                            break
                        if ssi[0] in ("H", "E") \
                                and resj - n in end_list \
                                and ssj_mn == ssi:
                            # -----[-----i-----]**j--- (n: **)
                            #           E/H
                            ssclash = "%s+%d,%s" % (ssj_mn[0], n, ssi[0])
                            break

                        # (E+n, E-n), (H+n, H-n)
                        if ssi_mn[0] in ("H", "E") \
                                and resi - n in end_list \
                                and resj + n in start_list \
                                and ssi_mn == ssj_pn:
                            # --j**[-----H/E-----]**i-- (n: **)
                            ssclash = "%s+%d,%s-%d" % (ssi_mn[0], n,
                                                       ssj_pn[0], n)
                            break
                        if ssi_pn[0] in ("H", "E") \
                                and resi + n in start_list \
                                and resj - n in end_list \
                                and ssi_pn == ssj_mn:
                            # --i**[-----H/E-----]**j-- (n: **)
                            ssclash = "%s-%d,%s+%d" % (ssi_pn[0], n,
                                                       ssj_mn[0], n)
                            break

                    if ssclash:
                        logger.debug("Ss clash for contact %d %s (%s)" % (
                            icontact, outcontact, ssclash))
                        if ssclash in ("H-2,H", "H+2,H") \
For faster browsing, not all history is shown. View entire blame