tasks.py 13.4 KB
Newer Older
1
2
3
4
5
6
7
8
from __future__ import absolute_import, unicode_literals
import json
import tempfile
import io
import base64
import itertools


9
10
from celery import shared_task, task, states
from ippisite.decorator import IppidbTask
11
import matplotlib.pyplot as plt
12
13
14

plt.switch_backend("Agg")
import seaborn as sns
15
16
17
18
19
20
21
22
23
24
import numpy as np
import pandas as pd
from sklearn.decomposition import PCA
from sklearn.preprocessing import StandardScaler

# TODO send email from django.core.mail import mail_managers
from django.forms.models import model_to_dict

from .models import (
    Compound,
25
    Contribution,
26
27
28
    update_compound_cached_properties,
    LeLleBiplotData,
    PcaBiplotData,
29
    Job,
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
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
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
)
from .utils import smi2sdf
from .gx import GalaxyCompoundPropertiesRunner


def dec(decimal_places):
    def func(number):
        return round(float(number), decimal_places)

    return func


def compute_compound_properties(compound_ids):
    compounds = Compound.objects.filter(id__in=compound_ids)
    runner = GalaxyCompoundPropertiesRunner()
    smiles_dict = {}
    for c in compounds:
        smiles_dict[c.id] = c.canonical_smile
    # create SDF file for the selection
    sdf_string = smi2sdf(smiles_dict)
    fh = tempfile.NamedTemporaryFile(mode="w", delete=False)
    fh.write(sdf_string)
    fh.close()
    print(f"Galaxy input SDF file for compounds {smiles_dict.keys()}: {fh.name}")
    # run computations on Galaxy
    pc_properties = runner.compute_properties_for_sdf_file(fh.name)
    pc_properties_dict = {compound["Name"]: compound for compound in pc_properties}
    fh = tempfile.NamedTemporaryFile(mode="w", delete=False)
    json.dump(pc_properties_dict, fh, indent=4)
    fh.close()
    print(
        f"Properties added for compounds {smiles_dict.keys()} in JSON file: {fh.name}"
    )
    # report and update database
    property_mapping = {
        "CanonicalSmile": ("canonical_smile", str),
        "IUPAC": ("iupac_name", str),
        "TPSA": ("tpsa", dec(2)),
        "NbMultBonds": ("nb_multiple_bonds", int),
        "BalabanIndex": ("balaban_index", dec(2)),
        "NbDoubleBonds": ("nb_double_bonds", int),
        "RDF070m": ("rdf070m", dec(2)),
        "SumAtomPolar": ("sum_atom_polar", dec(2)),
        "SumAtomVolVdW": ("sum_atom_vol_vdw", dec(2)),
        "MolecularWeight": ("molecular_weight", dec(2)),
        "NbCircuits": ("nb_circuits", int),
        "NbAromaticsSSSR": ("nb_aromatic_sssr", int),
        "NbAcceptorH": ("nb_acceptor_h", int),
        "NbF": ("nb_f", int),
        "Ui": ("ui", dec(2)),
        "NbO": ("nb_o", int),
        "NbCl": ("nb_cl", int),
        "NbBonds": ("nb_bonds", int),
        "LogP": ("a_log_p", dec(2)),
        "RandicIndex": ("randic_index", dec(2)),
        "NbBondsNonH": ("nb_bonds_non_h", int),
        "NbAromaticsEther": ("nb_aromatic_ether", int),
        "NbChiralCenters": ("nb_chiral_centers", int),
        "NbBenzLikeRings": ("nb_benzene_like_rings", int),
        "RotatableBondFraction": ("rotatable_bond_fraction", dec(2)),
        "LogD": ("log_d", dec(2)),
        "WienerIndex": ("wiener_index", int),
        "NbN": ("nb_n", int),
        "NbC": ("nb_c", int),
        "NbAtom": ("nb_atom", int),
        "NbAromaticsBonds": ("nb_aromatic_bonds", int),
        "MeanAtomVolVdW": ("mean_atom_vol_vdw", dec(2)),
        "AromaticRatio": ("aromatic_ratio", dec(2)),
        "NbAtomNonH": ("nb_atom_non_h", int),
        "NbDonorH": ("nb_donor_h", int),
        "NbI": ("nb_i", int),
        "NbRotatableBonds": ("nb_rotatable_bonds", int),
        "NbRings": ("nb_rings", int),
        "NbCsp2": ("nb_csp2", int),
        "NbCsp3": ("nb_csp3", int),
        "NbBr": ("nb_br", int),
        "GCMolarRefractivity": ("gc_molar_refractivity", dec(2)),
        "NbAliphaticsAmines": ("nb_aliphatic_amines", int),
    }
    ippidb_convs = {value[0]: value[1] for key, value in property_mapping.items()}
    ippidb_convs["id"] = int
    for cid, item in pc_properties_dict.items():
        compound = Compound.objects.get(id=cid)
        updated_properties = {}
        for galaxy_prop, prop in property_mapping.items():
            ippidb_prop = prop[0]
            ippidb_conv = prop[1]
            try:
                updated_properties[ippidb_prop] = ippidb_conv(item[galaxy_prop])
            except ValueError as ve:
                print(
121
122
                    f"Error setting property {ippidb_prop} to {item[galaxy_prop]}"
                    f" in compound {compound.id} \ndetails:{ve}"
123
124
125
                )
        for key, value in updated_properties.items():
            setattr(compound, key, value)
126
        compound.compute_fsp3()
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
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
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
        compound.save()


def compute_drugbank_similarity(compound_ids):
    compounds = Compound.objects.filter(id__in=compound_ids)
    for c in compounds:
        c.save(autofill=True)
    pass


def validate(compound_ids):
    compounds = Compound.objects.filter(id__in=compound_ids)
    for c in compounds:
        for ca in c.compoundaction_set.all():
            for contribution in ca.ppi.contribution_set.filter(validated=False):
                contribution.validated = True
                contribution.save()


def generate_le_lle_plot():
    print("Generating the LE vs. LLE biplot...")
    le_lle_data = []
    LeLleBiplotData.objects.all().delete()
    print("Successfully flushed LE-LLE biplot data")
    for comp in Compound.objects.validated():
        if comp.le is not None:
            le = round(comp.le, 7)
            lle = round(comp.lle, 7)
            le_lle_data.append(
                {
                    "x": le,
                    "y": lle,
                    "id": comp.id,
                    "family_name": comp.best_activity_ppi_family_name,
                    "smiles": comp.canonical_smile,
                }
            )
        else:
            print("compound %s has no LE" % comp.id)
    le_lle_json = json.dumps(le_lle_data, separators=(",", ":"))
    new = LeLleBiplotData()
    new.le_lle_biplot_data = le_lle_json
    new.save()
    print("Successfully generated LE-LLE biplot data")


def plot_circle():
    theta = np.linspace(0, 2 * np.pi, 100)
    r = np.sqrt(1.0)
    x1 = r * np.cos(theta)
    x2 = r * np.sin(theta)
    return x1, x2


def generate_pca_plot():
    print("Generating the PCA biplot...")
    pca_data = []
    features = [
        "molecular_weight",
        "a_log_p",
        "nb_donor_h",
        "nb_acceptor_h",
        "tpsa",
        "nb_rotatable_bonds",
        "nb_benzene_like_rings",
        "fsp3",
        "nb_chiral_centers",
        "nb_csp3",
        "nb_atom",
        "nb_bonds",
        "nb_atom_non_h",
        "nb_rings",
        "nb_multiple_bonds",
        "nb_aromatic_bonds",
        "aromatic_ratio",
    ]
    PcaBiplotData.objects.all().delete()
    print("Successfully flushed PCA biplot data")
    values_list = []
    for comp in Compound.objects.validated():
        values = model_to_dict(comp, fields=features + ["id", "family"])
        values["family"] = comp.best_activity_ppi_family_name
        values_list.append(values)
    df = pd.DataFrame(values_list)
    # drop compounds with undefined property values
    df.dropna(how="any", inplace=True)
    # prepare correlation circle figure
    plt.switch_backend("Agg")
    fig_, ax = plt.subplots(figsize=(6, 6))
    x1, x2 = plot_circle()
    plt.plot(x1, x2)
    ax.set_aspect(1)
    ax.yaxis.set_label_coords(-0.1, 0.5)
    ax.xaxis.set_label_coords(0.5, -0.08)
    # do not process the data unless there are compounds in the dataframe
    if len(df.index) > 0:
        x = df.loc[:, features].values
        y = df.loc[:, ["family"]].values
        x = StandardScaler().fit_transform(x)
        n = x.shape[0]  # retrieve number of individuals
        p = x.shape[1]  # retrieve number of variables
        pca = PCA(n_components=p)
        principal_components = pca.fit_transform(x)
        # compute correlation circle
        variance_ratio = pd.Series(pca.explained_variance_ratio_)
        coef = np.transpose(pca.components_)
        cols = ["PC-" + str(x) for x in range(len(variance_ratio))]
        pc_infos = pd.DataFrame(coef, columns=cols, index=features)
        # we might remove the line below if the PCA remains grayscale
        pal = itertools.cycle(sns.color_palette("dark", len(features)))  # noqa: F841
        # compute the length of each feature arrow in the correlation circle
        pc_infos["DIST"] = pc_infos[["PC-0", "PC-1"]].pow(2).sum(1).pow(0.5)
        # store the maximal length for normalization purposes
        best_distance = max(pc_infos["DIST"])
        # compute corvar for the correlation circle
        eigval = (float(n) - 1) / float(n) * pca.explained_variance_
        sqrt_eigval = np.sqrt(eigval)
        sqrt_eigval = np.sqrt(eigval)
        corvar = np.zeros((p, p))
        for k in range(p):
            corvar[:, k] = pca.components_[k, :] * sqrt_eigval[k]
        for idx in range(len(pc_infos["PC-0"])):
            x = corvar[idx, 0]  # use corvar to plot the variable map
            y = corvar[idx, 1]  # use corvar to plot the variable map
            color = "black"
            # alpha is the feature length normalized
            # to the longest feature's length
            alpha = pc_infos["DIST"][idx] / best_distance
            plt.arrow(0.0, 0.0, x, y, head_width=0.02, color="black", alpha=alpha)
            plt.annotate(
                Compound._meta.get_field(pc_infos.index[idx]).verbose_name,
                xy=(x, y),
                xycoords="data",
                xytext=np.asarray((x, y)) + (0.02, -0.02),
                fontsize=6,
                color=color,
                alpha=alpha,
            )
        plt.xlabel("PC-1 (%s%%)" % str(variance_ratio[0])[:4].lstrip("0."))
        plt.ylabel("PC-2 (%s%%)" % str(variance_ratio[1])[:4].lstrip("0."))
        plt.xlim((-1, 1))
        plt.ylim((-1, 1))
        principal_df = pd.DataFrame(data=principal_components)
        # only select the two first dimensions for the plot, and rename them to x and y
        principal_df = principal_df.iloc[:, 0:2]
        principal_df = principal_df.rename(columns={0: "x", 1: "y"})
        final_df = pd.concat([principal_df, df[["family", "id"]]], axis=1)
        for index, row in final_df.iterrows():
            smiles = Compound.objects.get(id=row.id).canonical_smile
            pca_data.append(
                {
                    "x": row.x,
                    "y": row.y,
                    "id": row.id,
                    "family_name": row.family,
                    "smiles": smiles,
                }
            )
    else:
        pca_data = []
    # save correlation circle PNG
    my_string_io_bytes = io.BytesIO()
    plt.savefig(my_string_io_bytes, format="png", dpi=600, bbox_inches="tight")
    my_string_io_bytes.seek(0)
    # figdata_png is the correlation circle figure, base 64-encoded
    figdata_png = base64.b64encode(my_string_io_bytes.read())
    pca_data_cc = {
        "data": pca_data,
        "correlation_circle": figdata_png.decode("utf-8"),
    }
    pca_json = json.dumps(pca_data_cc, separators=(",", ":"))
    new = PcaBiplotData()
    new.pca_biplot_data = pca_json
    new.save()
    print("Successfully generated PCA biplot data")


@shared_task
def validate_compounds(compound_ids):
    """
    This task will perform all computations and validate the compound
    It also regenerates the LE-LLE and PCA plots
    """
    compute_compound_properties(compound_ids)
    update_compound_cached_properties(Compound.objects.filter(id__in=compound_ids))
    compute_drugbank_similarity(compound_ids)
    validate(compound_ids)
    generate_le_lle_plot()
    generate_pca_plot()
316
317


318
319
320
321
322
323
324
325
326
327
328
329
330
331
@task(base=IppidbTask, bind=True)
def launch_test_command_caching(self):
    import time
    import random

    self.update_job(std_out="Before first sleep, state={}".format(self.state))
    time.sleep(30)
    self.update_state(state=states.STARTED)
    self.update_job(std_out="After first sleep, state={}".format(self.state))
    num = random.random()
    if num > 0.5:
        raise Exception("ERROR: {} is greater than 0.5".format(num))


332
@shared_task
333
def launch_validate_contributions(contribution_ids):
334
335
336
337
338
339
340
341
342
343
    """
    This task will perform, for a given set of contributions,
    all computations on the compounds and validate the contributions
    It also regenerates the LE-LLE and PCA plots
    """
    for cont in Contribution.objects.filter(id__in=contribution_ids):
        try:
            for compound_action in cont.ppi.compoundaction_set.all():
                compound = compound_action.compound
                compute_compound_properties([compound.id])
344
345
346
                update_compound_cached_properties(
                    Compound.objects.filter(id__in=[compound.id])
                )
347
348
349
350
351
352
353
                compute_drugbank_similarity([compound.id])
                validate([compound.id])
        except Exception:
            print(compound.id)
    generate_le_lle_plot()
    generate_pca_plot()

354
355
356
357
358
359
360

@shared_task
def launch_compound_properties_caching():
    """
    This task will perform, for all already validated compounds,
    the caching of the properties.
    """
361
362
    validated_compounds = Compound.objects.validated()
    update_compound_cached_properties(validated_compounds)
363

Hervé  MENAGER's avatar
Hervé MENAGER committed
364

365
366
367
368
369
370
@shared_task
def launch_drugbank_similarity_computing():
    """
    This task will perform, for all already validated compounds,
    the computing of drugbank similarity.
    """
371
372
    validated_compounds = Compound.objects.validated()
    compute_drugbank_similarity(validated_compounds)
373

Hervé  MENAGER's avatar
Hervé MENAGER committed
374

375
376
377
378
379
380
381
@shared_task
def launch_plots_computing():
    """
    This task will perform the computing of LE-LLE and PCA plots.
    """
    generate_le_lle_plot()
    generate_pca_plot()