models.py 28.6 KB
Newer Older
1
2
3
4
"""
Models used in iPPI-DB
"""

Hervé  MENAGER's avatar
Hervé MENAGER committed
5
from __future__ import unicode_literals
6
import operator
Hervé  MENAGER's avatar
Hervé MENAGER committed
7
8

from django.db import models
9
from django.db.models import Max
10
from django.conf import settings
Hervé  MENAGER's avatar
Hervé MENAGER committed
11

12
from .utils import FingerPrinter, smi2inchi, smi2inchikey
13
from .ws import get_pubmed_info, get_google_patent_info, get_uniprot_info, get_taxonomy_info, get_go_info, get_pfam_info
14

Hervé  MENAGER's avatar
Hervé MENAGER committed
15

16
class AutoFillableModel(models.Model):
Hervé  MENAGER's avatar
Hervé MENAGER committed
17

18
19
20
21
22
23
24
25
26
27
28
29
30
    """
    AutoFillableModel makes it possible to automatically fill model fields from
    external sources in the autofill() method
    The save method allows to either include autofill or not. in autofill kwarg is
    set to True, save() will first call autofill(), otherwise it won't
    """

    class Meta:
        abstract = True

    def save(self, *args, **kwargs):
        if kwargs.get('autofill') is True:
            self.autofill()
31
32
        if 'autofill' in kwargs:
            del kwargs['autofill']
Hervé  MENAGER's avatar
Hervé MENAGER committed
33
        super(AutoFillableModel, self).save(*args, **kwargs)
34
35
36


class Bibliography(AutoFillableModel):
Hervé  MENAGER's avatar
Hervé MENAGER committed
37

Hervé  MENAGER's avatar
Hervé MENAGER committed
38
39
40
41
    """
    Bibliography data table
    """
    SOURCES = (
42
43
44
        ('PM', 'PubMed ID'),
        ('PT', 'Patent'),
        ('DO', 'DOI ID')
Hervé  MENAGER's avatar
Hervé MENAGER committed
45
    )
Hervé  MENAGER's avatar
Hervé MENAGER committed
46
47
    source = models.CharField(
        'Bibliographic type', max_length=2, choices=SOURCES, default='PM')
Hervé  MENAGER's avatar
Hervé MENAGER committed
48
49
    id_source = models.CharField('Bibliographic ID', max_length=25)
    title = models.CharField('Title', max_length=300)
50
    journal_name = models.CharField('Journal name', max_length=50, null=True, blank=True)
Hervé  MENAGER's avatar
Hervé MENAGER committed
51
52
    authors_list = models.CharField('Authors list', max_length=500)
    biblio_year = models.PositiveSmallIntegerField('Year')
53
    cytotox = models.BooleanField('Cytotoxicity data', default=False)
Rachel TORCHET's avatar
Rachel TORCHET committed
54
55
56
57
    in_silico = models.BooleanField('in silico study', default=False)
    in_vitro = models.BooleanField('in vitro study', default=False)
    in_vivo = models.BooleanField('in vivo study', default=False)
    in_cellulo = models.BooleanField('in cellulo study', default=False)
Hervé  MENAGER's avatar
Hervé MENAGER committed
58
59
    pharmacokinetic = models.BooleanField(
        'pharmacokinetic study', default=False)
Rachel TORCHET's avatar
Rachel TORCHET committed
60
    xray = models.BooleanField('X-Ray data', default=False)
Hervé  MENAGER's avatar
Hervé MENAGER committed
61

62
    def autofill(self):
63
64
65
        if self.source == 'PM':
            info = get_pubmed_info(self.id_source)
        else:
66
            info = get_google_patent_info(self.id_source)
67
68
69
70
        self.title = info['title']
        self.journal_name = info['journal_name']
        self.authors_list = info['authors_list']
        self.biblio_year = info['biblio_year']
Hervé  MENAGER's avatar
Hervé MENAGER committed
71

Hervé  MENAGER's avatar
Hervé MENAGER committed
72
73
74
    class Meta:
        verbose_name_plural = "bibliographies"

75
76
    def __str__(self):
        return '{}, {}'.format(self.source, self.id_source)
77

Hervé  MENAGER's avatar
Hervé MENAGER committed
78

79
class Taxonomy(AutoFillableModel):
Hervé  MENAGER's avatar
Hervé MENAGER committed
80
81
    taxonomy_id = models.DecimalField(
        'NCBI TaxID', unique=True, max_digits=9, decimal_places=0)
Hervé  MENAGER's avatar
Hervé MENAGER committed
82
    name = models.CharField('Organism name', max_length=200)
83

84
    def autofill(self):
85
86
87
        info = get_taxonomy_info(self.taxonomy_id)
        self.name = info['scientific_name']

88
89
90
    def __str__(self):
        return self.name

Hervé  MENAGER's avatar
Hervé MENAGER committed
91
92
    class Meta:
        verbose_name_plural = "taxonomies"
Hervé  MENAGER's avatar
Hervé MENAGER committed
93

Hervé  MENAGER's avatar
Hervé MENAGER committed
94

95
class MolecularFunction(AutoFillableModel):
Hervé  MENAGER's avatar
Hervé MENAGER committed
96
    go_id = models.CharField('Gene Ontology ID', unique=True, max_length=10)
Hervé  MENAGER's avatar
Hervé MENAGER committed
97
    # GO term id format: 'GO:0000000'
Hervé  MENAGER's avatar
Hervé MENAGER committed
98
99
    description = models.CharField('description', max_length=500)

100
    def autofill(self):
101
102
103
        info = get_go_info(self.go_id)
        self.description = info['label']

104
105
106
    def __str__(self):
        return self.description

Hervé  MENAGER's avatar
Hervé MENAGER committed
107

108
class Protein(AutoFillableModel):
Hervé  MENAGER's avatar
Hervé MENAGER committed
109
    uniprot_id = models.CharField('Uniprot ID', unique=True, max_length=10)
Hervé  MENAGER's avatar
Hervé MENAGER committed
110
111
    recommended_name_long = models.CharField(
        'Uniprot Recommended Name (long)', max_length=75)
Hervé  MENAGER's avatar
Hervé MENAGER committed
112
113
114
    short_name = models.CharField('Short name', max_length=50)
    gene_name = models.CharField('Gene name', unique=True, max_length=30)
    entry_name = models.CharField('Entry name', max_length=30)
115
    organism = models.ForeignKey('Taxonomy', models.CASCADE)
Hervé  MENAGER's avatar
Hervé MENAGER committed
116
117
    molecular_functions = models.ManyToManyField(MolecularFunction)

118
    def autofill(self):
119
        info = get_uniprot_info(self.uniprot_id)
120
        self.recommended_name_long = info['recommended_name']
121
122
        self.gene_name = info['gene']
        self.entry_name = info['entry_name']
123
        self.short_name = info['short_name']
124
125
126
127
128
        try:
            taxonomy = Taxonomy.objects.get(taxonomy_id=info['organism'])
        except Taxonomy.DoesNotExist:
            taxonomy = Taxonomy()
            taxonomy.taxonomy_id = info['organism']
129
            taxonomy.save(autofill=True)
130
        self.organism = taxonomy
131
        super(Protein, self).save()
132
133
134
135
136
137
        for go_id in info['molecular_functions']:
            try:
                mol_function = MolecularFunction.objects.get(go_id=go_id)
            except MolecularFunction.DoesNotExist:
                mol_function = MolecularFunction()
                mol_function.go_id = go_id
138
                mol_function.save(autofill=True)
139
            self.molecular_functions.add(mol_function)
140

141
142
143
    def __str__(self):
        return '{} ({})'.format(self.uniprot_id, self.recommended_name_long)

Hervé  MENAGER's avatar
Hervé MENAGER committed
144

145
class Domain(AutoFillableModel):
Hervé  MENAGER's avatar
Hervé MENAGER committed
146
147
    pfam_acc = models.CharField('Pfam Accession', max_length=10, unique=True)
    pfam_id = models.CharField('Pfam Family Identifier', max_length=20)
Hervé  MENAGER's avatar
Hervé MENAGER committed
148
    pfam_description = models.CharField('Pfam Description', max_length=100)
Hervé  MENAGER's avatar
Hervé MENAGER committed
149
    domain_family = models.CharField('Domain family', max_length=25)
Hervé  MENAGER's avatar
Hervé MENAGER committed
150
151
    # TODO: what is this field? check database
    # contents
152

153
    def autofill(self):
154
155
156
        info = get_pfam_info(self.pfam_acc)
        self.pfam_id = info['id']
        self.pfam_description = info['description']
Hervé  MENAGER's avatar
Hervé MENAGER committed
157

158
159
160
    def __str__(self):
        return '{} ({}-{})'.format(self.pfam_acc, self.pfam_id, self.pfam_description)

Hervé  MENAGER's avatar
Hervé MENAGER committed
161

162
class ProteinDomainComplex(models.Model):
163
164
    protein = models.ForeignKey('Protein', models.CASCADE)
    domain = models.ForeignKey('Domain', models.CASCADE)
Hervé  MENAGER's avatar
Hervé MENAGER committed
165
166
167
    ppc_copy_nb = models.IntegerField(
        'Number of copies of the protein in the complex')

Hervé  MENAGER's avatar
Hervé MENAGER committed
168
169
    class Meta:
        verbose_name_plural = "complexes"
170

171
172
173
    def __str__(self):
        return '{}-{}'.format(self.protein_id, self.domain_id)

174
175
    def name(self):
        return self.protein.short_name
Hervé  MENAGER's avatar
Hervé MENAGER committed
176

177

178
class ProteinDomainBoundComplex(ProteinDomainComplex):
Hervé  MENAGER's avatar
Hervé MENAGER committed
179
180
181
    ppp_copy_nb_per_p = models.IntegerField(
        'Number of copies of the protein in the pocket')

182
183
    class Meta:
        verbose_name_plural = "bound complexes"
Hervé  MENAGER's avatar
Hervé MENAGER committed
184
185


186
class ProteinDomainPartnerComplex(ProteinDomainComplex):
Hervé  MENAGER's avatar
Hervé MENAGER committed
187

188
189
    class Meta:
        verbose_name_plural = "partner complexes"
Hervé  MENAGER's avatar
Hervé MENAGER committed
190

Hervé  MENAGER's avatar
Hervé MENAGER committed
191

192
193
194
class Symmetry(models.Model):
    code = models.CharField('Symmetry code', max_length=2)
    description = models.CharField('Description', max_length=300)
Hervé  MENAGER's avatar
Hervé MENAGER committed
195

196
197
198
    class Meta:
        verbose_name_plural = "symmetries"

199
200
201
    def __str__(self):
        return '{} ({})'.format(self.code, self.description)

202
203

class Disease(models.Model):
Hervé  MENAGER's avatar
Hervé MENAGER committed
204
    name = models.CharField('Disease', max_length=30, unique=True)
Hervé  MENAGER's avatar
Hervé MENAGER committed
205
    # is there any database/nomenclature for diseases?
206
207
208
209

    def __str__(self):
        return self.name

Hervé  MENAGER's avatar
Hervé MENAGER committed
210

Hervé  MENAGER's avatar
Hervé MENAGER committed
211
212
213
class PpiFamily(models.Model):
    name = models.CharField('Name', max_length=30, unique=True)

214
215
216
    class Meta:
        verbose_name_plural = "PPI Families"

Hervé  MENAGER's avatar
Hervé MENAGER committed
217
218
    def __str__(self):
        return self.name
Hervé  MENAGER's avatar
Hervé MENAGER committed
219

Hervé  MENAGER's avatar
Hervé MENAGER committed
220

221
class Ppi(AutoFillableModel):
222
    pdb_id = models.CharField('PDB ID', max_length=4, null=True, blank=True)
Hervé  MENAGER's avatar
Hervé MENAGER committed
223
224
    pockets_nb = models.IntegerField(
        'Total number of pockets in the complex', default=1)
225
    symmetry = models.ForeignKey(Symmetry, models.CASCADE)
226
    diseases = models.ManyToManyField(Disease)
227
    family = models.ForeignKey(PpiFamily, models.CASCADE, null=True, blank=True)
228
    name = models.TextField('PPI name', null=True, blank=True)
Hervé  MENAGER's avatar
Hervé MENAGER committed
229

230
    def __str__(self):
231
        return 'PPI #{} on {}'.format(self.id, self.name)
232

233
234
235
    def autofill(self):
        # name is denormalized and stored in the database to reduce SQL queries in query mode
        self.name = self.compute_name_from_protein_names()
236
237
238
239
240

    def get_ppi_bound_complexes(self):
        """
        return bound ppi complexes belonging to this ppi
        """
Hervé  MENAGER's avatar
Hervé MENAGER committed
241
        # this is the less efficient query ever seen, FIXME
242
243
        return PpiComplex.objects.filter(ppi=self, complex__in=ProteinDomainBoundComplex.objects.all())

244
    def compute_name_from_protein_names(self):
Hervé  MENAGER's avatar
Hervé MENAGER committed
245
        all_protein_names = set(
246
            [ppi_complex.complex.protein.short_name for ppi_complex in self.ppicomplex_set.all()])
Hervé  MENAGER's avatar
Hervé MENAGER committed
247
248
        bound_protein_names = set(
            [ppi_complex.complex.protein.short_name for ppi_complex in self.get_ppi_bound_complexes()])
249
250
251
252
        partner_protein_names = all_protein_names - bound_protein_names
        bound_str = ','.join(bound_protein_names)
        partner_str = ','.join(partner_protein_names)
        name = bound_str
Hervé  MENAGER's avatar
Hervé MENAGER committed
253
        if partner_str != '':
254
255
            name += ' / ' + partner_str
        return name
256

Hervé  MENAGER's avatar
Hervé MENAGER committed
257

Hervé  MENAGER's avatar
Hervé MENAGER committed
258
class PpiComplex(models.Model):
259
260
    ppi = models.ForeignKey(Ppi, models.CASCADE)
    complex = models.ForeignKey(ProteinDomainComplex, models.CASCADE)
Hervé  MENAGER's avatar
Hervé MENAGER committed
261
262
    cc_nb = models.IntegerField(
        'Number of copies of the complex in the PPI', default=1)
Hervé  MENAGER's avatar
Hervé MENAGER committed
263
264
265
266

    class Meta:
        verbose_name_plural = "Ppi complexes"

267
268
269
    def __str__(self):
        return 'PPI {}, Complex {} ({})'.format(self.ppi, self.complex, self.cc_nb)

Hervé  MENAGER's avatar
Hervé MENAGER committed
270

271
class Compound(AutoFillableModel):
272
273
    canonical_smile = models.TextField(
        'Canonical Smile', unique=True)
Hervé  MENAGER's avatar
Hervé MENAGER committed
274
275
276
277
278
    is_macrocycle = models.BooleanField('Contains one or more macrocycles')
    aromatic_ratio = models.DecimalField(
        'Aromatic ratio', max_digits=3, decimal_places=2)
    balaban_index = models.DecimalField(
        'Balaban index', max_digits=3, decimal_places=2)
279
    fsp3 = models.DecimalField('Fsp3', max_digits=3, decimal_places=2)
Hervé  MENAGER's avatar
Hervé MENAGER committed
280
281
282
283
284
285
286
287
288
289
    gc_molar_refractivity = models.DecimalField(
        'GC Molar Refractivity', max_digits=5, decimal_places=2)
    log_d = models.DecimalField(
        'LogD (Partition coefficient octanol-1/water, with pKa information)', max_digits=4, decimal_places=2)
    a_log_p = models.DecimalField(
        'ALogP (Partition coefficient octanol-1/water)', max_digits=4, decimal_places=2)
    mean_atom_vol_vdw = models.DecimalField(
        'Mean atom volume computed with VdW radii', max_digits=4, decimal_places=2)
    molecular_weight = models.DecimalField(
        'Molecular weight', max_digits=6, decimal_places=2)
290
291
292
293
    nb_acceptor_h = models.IntegerField('Number of hydrogen bond acceptors')
    nb_aliphatic_amines = models.IntegerField('Number of aliphatics amines')
    nb_aromatic_bonds = models.IntegerField('Number of aromatic bonds')
    nb_aromatic_ether = models.IntegerField('Number of aromatic ethers')
Hervé  MENAGER's avatar
Hervé MENAGER committed
294
295
296
297
    nb_aromatic_sssr = models.IntegerField(
        'Number of aromatic Smallest Set of System Rings (SSSR)')
    nb_atom = models.IntegerField('Number of atoms')
    nb_atom_non_h = models.IntegerField('Number of non hydrogen atoms')
298
299
    nb_benzene_like_rings = models.IntegerField('Number of benzene-like rings')
    nb_bonds = models.IntegerField('Number of bonds')
Hervé  MENAGER's avatar
Hervé MENAGER committed
300
301
302
303
304
305
306
307
308
309
310
311
312
313
    nb_bonds_non_h = models.IntegerField(
        'Number of bonds not involving a hydrogen')
    nb_br = models.IntegerField('Number of Bromine atoms')
    nb_c = models.IntegerField('Number of Carbon atoms')
    nb_chiral_centers = models.IntegerField('Number of chiral centers')
    nb_circuits = models.IntegerField('Number of circuits')
    nb_cl = models.IntegerField('Number of Chlorine atoms')
    nb_csp2 = models.IntegerField('Number of sp2-hybridized carbon atoms')
    nb_csp3 = models.IntegerField('Number of sp3-hybridized carbon atoms')
    nb_donor_h = models.IntegerField('Number of hydrogen bond donors')
    nb_double_bonds = models.IntegerField('Number of double bonds')
    nb_f = models.IntegerField('Number of fluorine atoms')
    nb_i = models.IntegerField('Number of iodine atoms')
    nb_multiple_bonds = models.IntegerField('Number of multiple bonds')
314
    nb_n = models.IntegerField('Number of nitrogen atoms')
Hervé  MENAGER's avatar
Hervé MENAGER committed
315
316
317
    nb_o = models.IntegerField('Number of oxygen atoms')
    nb_rings = models.IntegerField('Number of rings')
    nb_rotatable_bonds = models.IntegerField('Number of rotatable bonds')
318
319
    inchi = models.TextField('InChi')
    inchikey = models.TextField('InChiKey')
Hervé  MENAGER's avatar
Hervé MENAGER committed
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
    randic_index = models.DecimalField(
        'Randic index', max_digits=4, decimal_places=2)
    rdf070m = models.DecimalField(
        'RDF070m, radial distribution function weighted by the atomic masses at 7Å', max_digits=5, decimal_places=2)
    rotatable_bond_fraction = models.DecimalField(
        'Fraction of rotatable bonds', max_digits=3, decimal_places=2)
    sum_atom_polar = models.DecimalField(
        'Sum of atomic polarizabilities', max_digits=5, decimal_places=2)
    sum_atom_vol_vdw = models.DecimalField(
        'Sum of atom volumes computed with VdW radii', max_digits=6, decimal_places=2)
    tpsa = models.DecimalField(
        'Topological Polar Surface Area (TPSA)', max_digits=5, decimal_places=2)
    ui = models.DecimalField(
        'Unsaturation index', max_digits=4, decimal_places=2)
    wiener_index = models.IntegerField('Wiener index')
    common_name = models.CharField(
        'Common name', unique=True, max_length=20, blank=True, null=True)
    pubchem_id = models.CharField(
        'Pubchem ID', max_length=10, blank=True, null=True)
    chemspider_id = models.CharField(
        'Chemspider ID', unique=True, max_length=10, blank=True, null=True)
    chembl_id = models.CharField(
        'Chembl ID', max_length=30, blank=True, null=True)
    iupac_name = models.CharField(
        'IUPAC name', max_length=255, blank=True, null=True)
345

346
347
348
    class Meta:
       ordering = ['id']

349
350
351
    def compute_drugbank_compound_similarity(self):
        """ compute Tanimoto similarity to existing DrugBank compounds """
        self.save()
352
        # fingerprints to compute drugbank similarities are in settings module, default FP2
353
        fingerprinter = FingerPrinter(getattr(settings, "DRUGBANK_FINGERPRINTS", "FP2"))
354
355
356
357
358
359
360
361
362
        #1. compute tanimoto for SMILES query vs all compounds
        smiles_dict = {c.id:c.canonical_smiles for c in DrugBankCompound.objects.all()}
        tanimoto_dict = fingerprinter.tanimoto_smiles(self.canonical_smile, smiles_dict)
        tanimoto_dict = dict(sorted(tanimoto_dict.items(), key=operator.itemgetter(1), reverse=True)[:15])
        dbcts = []
        for id_, tanimoto in tanimoto_dict.items():
            dbcts.append(DrugbankCompoundTanimoto(compound=self, drugbank_compound=DrugBankCompound.objects.get(id=id_), tanimoto=tanimoto))
        DrugbankCompoundTanimoto.objects.bulk_create(dbcts)

Hervé  MENAGER's avatar
Hervé MENAGER committed
363
364
365
    @property
    def biblio_refs(self):
        """
Hervé  MENAGER's avatar
Hervé MENAGER committed
366
        return all RefCompoundBiblio related to this compound
Hervé  MENAGER's avatar
Hervé MENAGER committed
367
368
        """
        return RefCompoundBiblio.objects.filter(compound=self)
369

370
371
372
373
374
375
376
377
378
379
380
381
382
    @property
    def pfam_ids(self):
        """
        return all PFAM ids for the domain of the proteins of the bound
        complexes in the PPIs this compound has an action on
        """
        pfam_ids = set()
        for ca in self.compoundaction_set.all():
            ca.get_complexes()
            for bound_complex in ca.ppi.get_ppi_bound_complexes():
                pfam_ids.add(bound_complex.complex.domain.pfam_id)
        return pfam_ids

383
    @property
Hervé  MENAGER's avatar
Hervé MENAGER committed
384
    def compound_action_ligand_ids(self):
385
386
387
        """
        return all PDB codes of the corresponding compound actions
        """
Hervé  MENAGER's avatar
Hervé MENAGER committed
388
        ligand_ids = set()
389
        for ca in self.compoundaction_set.all():
Hervé  MENAGER's avatar
Hervé MENAGER committed
390
391
            ligand_ids.add(ca.ligand_id)
        return ligand_ids
392

393
394
395
396
397
398
399
400
401
402
403
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
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
    @property
    def hba_hbd(self):
        return self.nb_acceptor_h + self.nb_donor_h

    @property
    def lipinsky_mw(self):
        return self.molecular_weight <= 500

    @property
    def lipinsky_hba(self):
        return self.nb_acceptor_h <= 10

    @property
    def lipinsky_hbd(self):
        return self.nb_donor_h <= 5

    @property
    def lipinsky_a_log_p(self):
        return self.a_log_p <= 5

    @property
    def lipinsky_global(self):
        return int(self.lipinsky_mw) + int(self.lipinsky_hba) + \
            int(self.lipinsky_hbd) + int(self.lipinsky_a_log_p) >= 3

    @property
    def veber_hba_hbd(self):
        return self.nb_acceptor_h + self.nb_donor_h <= 12

    @property
    def veber_tpsa(self):
        return self.tpsa <= 140

    @property
    def veber_rb(self):
        return self.nb_rotatable_bonds <= 10

    @property
    def veber_global(self):
        return self.veber_rb and (self.veber_hba_hbd or self.veber_tpsa)

    @property
    def pfizer_a_log_p(self):
        return self.a_log_p <= 3

    @property
    def pfizer_tpsa(self):
        return self.tpsa >= 75

    @property
    def pfizer_global(self):
        return self.pfizer_a_log_p and self.pfizer_tpsa

446
447
    @property
    def best_pXC50_activity(self):
448
        return self.compoundactivityresult_set.aggregate(Max('activity'))['activity__max']
449
450
451
452
453
454

    @property
    def best_pXC50_compound_activity_result(self):
        best_pXC50_activity = self.best_pXC50_activity
        if best_pXC50_activity is None:
            return None
455
        return self.compoundactivityresult_set.filter(activity=best_pXC50_activity)[0]
456

457
458
459
460
461
    @property
    def le(self):
        """
        LE: Ligand Efficiency
        """
462
463
464
465
        best_pXC50_activity = self.best_pXC50_activity
        if best_pXC50_activity is None:
            return None
        return (1.37 * float(best_pXC50_activity))/self.nb_atom_non_h
466
467
468
469
470
471

    @property
    def lle(self):
        """
        LLE: Lipophilic Efficiency
        """
472
473
474
        best_pXC50_activity = self.best_pXC50_activity
        if best_pXC50_activity is None:
            return None
Hervé  MENAGER's avatar
Hervé MENAGER committed
475
        return float(best_pXC50_activity - self.a_log_p)
476

477
    @property
478
    def best_pXC50_activity_ppi_name(self):
479
        """
480
        Name of the PPI corresponding to the best PXC50 activity
481
        """
482
483
484
        best_activity_car = self.best_pXC50_compound_activity_result
        if best_activity_car is None:
            return None
485
486
487
        ppi_name = best_activity_car.test_activity_description.ppi.name
        return ppi_name

488
489
490
491
492
493
494
495
496
497
498
    @property
    def best_pXC50_activity_ppi_family(self):
        """
        Family of the PPI corresponding to the best PXC50 activity
        """
        best_activity_car = self.best_pXC50_compound_activity_result
        if best_activity_car is None:
            return None
        ppi_family = best_activity_car.test_activity_description.ppi.family.name
        return ppi_family

499
500
501
502
503
504
505
506
507
508
509
510
511
512
    @property
    def bioch_tests_count(self):
        """
        return the number of associated biochemical tests
        """
        return self.compoundactivityresult_set.all().filter(test_activity_description__test_type='BIOCH').count()

    @property
    def cell_tests_count(self):
        """
        return the number of associated cell tests
        """
        return self.compoundactivityresult_set.all().filter(test_activity_description__test_type='CELL').count()

513
514
515
516
517
518
    @property
    def families(self):
        """
        return the all PPI families for PPIs involved in the compound activity of the compound
        """
        return list(set([ca.ppi.family for ca in self.compoundaction_set.all()]))
519
520
521
522
523
    
    @property
    def sorted_similar_drugbank_compounds(self):
        return self.drugbankcompoundtanimoto_set.order_by('-tanimoto')
        
524
525
526
    def autofill(self):
        # compute InChi and InChiKey
        self.inchi = smi2inchi(self.canonical_smile)
527
        self.inchikey = smi2inchikey(self.canonical_smile)
528
        self.compute_drugbank_compound_similarity()
529

530
531
532
    def __str__(self):
        return 'Compound #{}'.format(self.id)

533
534
535
class CompoundTanimoto(models.Model):
    canonical_smiles = models.TextField(
        'Canonical Smile')
536
    fingerprint = models.TextField('Fingerprint')
537
538
539
540
541
542
    compound = models.ForeignKey(Compound, models.CASCADE)
    tanimoto = models.DecimalField(
        'Tanimoto value', max_digits=5, decimal_places=4)

    class Meta:
        unique_together = (
543
            ('canonical_smiles', 'fingerprint', 'compound'))
544

545
def create_tanimoto(smiles_query, fingerprint):
546
    if CompoundTanimoto.objects.filter(canonical_smiles=smiles_query, fingerprint=fingerprint).count()==0:
547
        smiles_dict = {c.id:c.canonical_smile for c in Compound.objects.all()}
548
        fingerprinter = FingerPrinter(fingerprint)
549
550
551
552
553
        #1. compute tanimoto for SMILES query vs all compounds
        tanimoto_dict = fingerprinter.tanimoto_smiles(smiles_query, smiles_dict)
        #2. insert results in a table with three fields: SMILES query, compound id, tanimoto index
        cts = []
        for id_, smiles in smiles_dict.items():
554
            cts.append(CompoundTanimoto(canonical_smiles=smiles_query, fingerprint=fingerprint, compound=Compound.objects.get(id=id_), tanimoto=tanimoto_dict[id_]))
555
        CompoundTanimoto.objects.bulk_create(cts)
556

557
class PcaBiplotData(models.Model):
558
559
    pca_biplot_data = models.TextField(
        'PCA biplot JSON data', blank=True, null=True)
Hervé  MENAGER's avatar
Hervé MENAGER committed
560

561

562
class LeLleBiplotData(models.Model):
563
564
    le_lle_biplot_data = models.TextField(
        'LE-LLE biplot JSON data', blank=True, null=True)
Hervé  MENAGER's avatar
Hervé MENAGER committed
565

566

567
568
class CellLine(models.Model):
    name = models.CharField('Name', max_length=50, unique=True)
Hervé  MENAGER's avatar
Hervé MENAGER committed
569

570
571
572
    def __str__(self):
        return self.name

Hervé  MENAGER's avatar
Hervé MENAGER committed
573

574
575
576
577
578
579
580
581
582
583
class TestActivityDescription(models.Model):
    TEST_TYPES = (
        ('BIOCH', 'Biochemical assay'),
        ('CELL', 'Cellular assay')
    )
    TEST_MODULATION_TYPES = (
        ('B', 'Binding'),
        ('I', 'Inhibition'),
        ('S', 'Stabilization')
    )
584
585
586
587
    PROTEIN_BOUND_CONSTRUCTS = (
        ('F', 'Full length'),
        ('U', 'Unspecified')
    )
588
    biblio = models.ForeignKey(Bibliography, models.CASCADE)
Hervé  MENAGER's avatar
Hervé MENAGER committed
589
590
    protein_domain_bound_complex = models.ForeignKey(
        ProteinDomainBoundComplex, models.CASCADE)
591
    ppi = models.ForeignKey(Ppi, models.CASCADE, blank=True, null=True)
Hervé  MENAGER's avatar
Hervé MENAGER committed
592
    test_name = models.CharField('Test name', max_length=100)
593
    is_primary = models.BooleanField('Is primary')
Hervé  MENAGER's avatar
Hervé MENAGER committed
594
595
    protein_bound_construct = models.CharField(
        'Protein bound construct', max_length=5, choices=PROTEIN_BOUND_CONSTRUCTS, blank=True, null=True)
596
    test_type = models.CharField('Test type', max_length=5, choices=TEST_TYPES)
Hervé  MENAGER's avatar
Hervé MENAGER committed
597
598
599
600
    test_modulation_type = models.CharField(
        'Test modulation type', max_length=1, choices=TEST_MODULATION_TYPES)
    nb_active_compounds = models.IntegerField(
        'Total number of active compounds')
Hervé  MENAGER's avatar
Hervé MENAGER committed
601
602
    cell_line = models.ForeignKey(
        CellLine, models.CASCADE, blank=True, null=True)
603

Hervé  MENAGER's avatar
Hervé MENAGER committed
604
    def get_complexes(self):
605
606
607
608
        """
        get the complexes tested for this PPI
        depends on the modulation type
        """
Hervé  MENAGER's avatar
Hervé MENAGER committed
609
        if self.test_modulation_type == 'I':
610
            return self.ppi.ppicomplex_set.all()
611
612
        else:
            return self.ppi.get_ppi_bound_complexes()
613

614
615
616
    @property
    def protein_domain_partner_complex(self):
        for ppic in self.ppi.ppicomplex_set.all():
Hervé  MENAGER's avatar
Hervé MENAGER committed
617
            if hasattr(ppic.complex, 'proteindomainpartnercomplex'):
618
619
620
                return ppic.complex.proteindomainpartnercomplex
        return None

Hervé  MENAGER's avatar
Hervé MENAGER committed
621

622
class CompoundActivityResult(models.Model):
623
624
625
626
627
    MODULATION_TYPES = (
        ('B', 'Binding'),
        ('I', 'Inhibition'),
        ('S', 'Stabilization')
    )
Hervé  MENAGER's avatar
Hervé MENAGER committed
628
    ACTIVITY_TYPES = (
Hervé  MENAGER's avatar
Hervé MENAGER committed
629
630
631
632
        ('pIC50', 'pIC50 (half maximal inhibitory concentration, -log10)'),
        ('pEC50', 'pEC50 (half maximal effective concentration, -log10)'),
        ('pKd', 'pKd (dissociation constant, -log10)'),
        ('pKi', 'pKi (inhibition constant, -log10)'),
Hervé  MENAGER's avatar
Hervé MENAGER committed
633
    )
634
    compound = models.ForeignKey(Compound, models.CASCADE)
Hervé  MENAGER's avatar
Hervé MENAGER committed
635
636
    test_activity_description = models.ForeignKey(
        TestActivityDescription, models.CASCADE)
Hervé  MENAGER's avatar
Hervé MENAGER committed
637
638
639
640
    activity_type = models.CharField(
        'Activity type', max_length=5, choices=ACTIVITY_TYPES)
    activity = models.DecimalField(
        'Activity', max_digits=12, decimal_places=10)
641
    inhibition_percentage = models.DecimalField(
642
        'Inhibition percentage', max_digits=3, decimal_places=0, null=True, blank=True)
Hervé  MENAGER's avatar
Hervé MENAGER committed
643
644
    modulation_type = models.CharField(
        'Modulation type', max_length=1, choices=MODULATION_TYPES)
Hervé  MENAGER's avatar
Hervé MENAGER committed
645
646

    class Meta:
Hervé  MENAGER's avatar
Hervé MENAGER committed
647
648
649
        unique_together = (
            ('compound', 'test_activity_description', 'activity_type'),)

650
651
    def __str__(self):
        return 'Compound activity result for {} test {} on {}'.format(self.activity_type, self.test_activity_description.id, self.compound.id)
Hervé  MENAGER's avatar
Hervé MENAGER committed
652

653
654
655
    def is_best(self):
        return self.compound.best_pXC50_compound_activity_result.id == self.id

Hervé  MENAGER's avatar
Hervé MENAGER committed
656

657
class TestCytotoxDescription(models.Model):
658
    biblio = models.ForeignKey(Bibliography, models.CASCADE)
Hervé  MENAGER's avatar
Hervé MENAGER committed
659
    test_name = models.CharField('Cytotoxicity test name', max_length=100)
660
    cell_line = models.ForeignKey(CellLine, models.CASCADE)
Hervé  MENAGER's avatar
Hervé MENAGER committed
661
662
663
    compound_concentration = models.DecimalField(
        'Compound concentration in μM', max_digits=7, decimal_places=3, blank=True, null=True)

Hervé  MENAGER's avatar
Hervé MENAGER committed
664

665
class CompoundCytotoxicityResult(models.Model):
666
    compound = models.ForeignKey(Compound, models.CASCADE)
Hervé  MENAGER's avatar
Hervé MENAGER committed
667
668
    test_cytotoxicity_description = models.ForeignKey(
        TestCytotoxDescription, models.CASCADE)
669
    toxicity = models.BooleanField('Toxicity', default=False)
Hervé  MENAGER's avatar
Hervé MENAGER committed
670
671

    class Meta:
672
        unique_together = (('compound', 'test_cytotoxicity_description'),)
673

674
675
676
    def __str__(self):
        return 'Compound cytotoxicity result for test {} on {}'.format(self.test_cytotoxicity_description.id, self.compound.id)

Hervé  MENAGER's avatar
Hervé MENAGER committed
677

678
class TestPKDescription(models.Model):
679
680
681
682
683
684
    ADMINISTRATION_MODES = (
        ('IV', ''),
        ('PO', ''),
        ('IP', ''),
        ('SL', 'SL')
    )
685
    biblio = models.ForeignKey(Bibliography, models.CASCADE)
Hervé  MENAGER's avatar
Hervé MENAGER committed
686
    test_name = models.CharField('Pharmacokinetic test name', max_length=100)
687
    organism = models.ForeignKey(Taxonomy, models.CASCADE)
Hervé  MENAGER's avatar
Hervé MENAGER committed
688
689
    administration_mode = models.CharField(
        'Administration mode', max_length=2, choices=ADMINISTRATION_MODES, blank=True, null=True)
690
691
    concentration = models.DecimalField(
        'Concentration in mg/l', max_digits=7, decimal_places=3, blank=True, null=True)
Hervé  MENAGER's avatar
Hervé MENAGER committed
692
    dose = models.DecimalField(
693
        'Dose in mg/kg', max_digits=9, decimal_places=4, blank=True, null=True)
Hervé  MENAGER's avatar
Hervé MENAGER committed
694
695
696
    dose_interval = models.IntegerField(
        'Dose interval, in hours', blank=True, null=True)

697
698

class CompoundPKResult(models.Model):
699
700
    compound = models.ForeignKey(Compound, models.CASCADE)
    test_pk_description = models.ForeignKey(TestPKDescription, models.CASCADE)
701
    tolerated = models.NullBooleanField('Tolerated', null=True)
Hervé  MENAGER's avatar
Hervé MENAGER committed
702
703
704
705
    auc = models.IntegerField(
        'Area under curve (ng.mL-1.hr)', blank=True, null=True)
    clearance = models.DecimalField(
        'Clearance (mL/hr)', max_digits=7, decimal_places=3, blank=True, null=True)
706
    c_max = models.DecimalField(
Hervé  MENAGER's avatar
Hervé MENAGER committed
707
708
709
710
711
712
713
        'Maximal concentration (ng/mL)', max_digits=7, decimal_places=3, blank=True, null=True)
    oral_bioavailability = models.IntegerField(
        'Oral Bioavailability (%F)', blank=True, null=True)
    t_demi = models.IntegerField('t½', blank=True, null=True)
    t_max = models.IntegerField('tmax', blank=True, null=True)
    voldistribution = models.DecimalField(
        'Volume distribution (Vd)', max_digits=5, decimal_places=2, blank=True, null=True)
Hervé  MENAGER's avatar
Hervé MENAGER committed
714
715

    class Meta:
716
        unique_together = (('compound', 'test_pk_description'),)
Hervé  MENAGER's avatar
Hervé MENAGER committed
717

718
719
720
    def __str__(self):
        return 'Compound PK result for test {} on {}'.format(self.test_pk_description.id, self.compound.id)

Hervé  MENAGER's avatar
Hervé MENAGER committed
721

722
class CompoundAction(models.Model):
723
724
    ACTIVATION_MODES = (
        ('O', 'Orthosteric'),
725
726
        ('A', 'Allosteric'),
        ('U', 'Unspecified')
727
    )
728
    compound = models.ForeignKey(Compound, models.CASCADE)
Hervé  MENAGER's avatar
Hervé MENAGER committed
729
730
    activation_mode = models.CharField(
        'Activation mode', max_length=1, choices=ACTIVATION_MODES)
731
    ppi = models.ForeignKey(Ppi, models.CASCADE)
732
    ligand_id = models.CharField('PDB Ligand ID', max_length=3, blank=True, null=True)
Hervé  MENAGER's avatar
Hervé MENAGER committed
733
734
    nb_copy_compounds = models.IntegerField(
        'Number of copies for the compound')
Hervé  MENAGER's avatar
Hervé MENAGER committed
735
736

    class Meta:
737
        unique_together = (('ppi', 'compound', 'activation_mode', 'ligand_id'),)
Hervé  MENAGER's avatar
Hervé MENAGER committed
738
739

    def get_complexes(self):
740
741
742
743
        """
        get the complexes involved in the compound action
        which are always the bound complexes
        """
744
        return self.ppi.get_ppi_bound_complexes()
Hervé  MENAGER's avatar
Hervé MENAGER committed
745

746
747
    def __str__(self):
        return 'Action of {} on {}'.format(self.compound, self.ppi)
Hervé  MENAGER's avatar
Hervé MENAGER committed
748

749
class RefCompoundBiblio(models.Model):
750
751
    compound = models.ForeignKey(Compound, models.CASCADE)
    bibliography = models.ForeignKey(Bibliography, models.CASCADE)
Hervé  MENAGER's avatar
Hervé MENAGER committed
752
753
    compound_name = models.CharField(
        'Compound name in the publication', max_length=50)
Hervé  MENAGER's avatar
Hervé MENAGER committed
754
755

    class Meta:
756
        unique_together = (('compound', 'bibliography'),)
757

758
class DrugBankCompound(models.Model):
759
760
761
762
763
    id = models.TextField(
        'Drugbank ID', unique=True, primary_key=True)
    common_name = models.TextField('Common name')
    canonical_smiles = models.TextField(
        'Canonical SMILES')
764
765
766
767
768

class DrugbankCompoundTanimoto(models.Model):
    compound = models.ForeignKey(Compound, models.CASCADE)
    drugbank_compound = models.ForeignKey(DrugBankCompound, models.CASCADE)
    tanimoto = models.DecimalField(
769
        'Tanimoto value', max_digits=5, decimal_places=4)