models.py 36.5 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

7
import operator
8
import re
Hervé  MENAGER's avatar
Hervé MENAGER committed
9

10
from django.conf import settings
11
12
13
14
from django.core.exceptions import ValidationError
from django.db import models
from django.db.models import FloatField, IntegerField, BooleanField
from django.db.models import Max, Count, F, Q, Case, When
15
from django.db.models.functions import Cast
16
from django.utils.translation import ugettext_lazy as _
Hervé  MENAGER's avatar
Hervé MENAGER committed
17

18
from .utils import FingerPrinter, smi2inchi, smi2inchikey
19
from .ws import get_pubmed_info, get_google_patent_info, get_uniprot_info, get_taxonomy_info, get_go_info, get_pfam_info
20

Hervé  MENAGER's avatar
Hervé MENAGER committed
21

22
23
24
25
26
27
28
29
30
31
32
33
34
35
class AutoFillableModel(models.Model):
    """
    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()
36
37
        if 'autofill' in kwargs:
            del kwargs['autofill']
Hervé  MENAGER's avatar
Hervé MENAGER committed
38
        super(AutoFillableModel, self).save(*args, **kwargs)
39
40
41


class Bibliography(AutoFillableModel):
Hervé  MENAGER's avatar
Hervé MENAGER committed
42
    """
Hervé  MENAGER's avatar
Hervé MENAGER committed
43
44
    Bibliography references
    (publications or patents)
Hervé  MENAGER's avatar
Hervé MENAGER committed
45
    """
46
47
    class Meta:
        unique_together = ('source', 'id_source',)
Hervé  MENAGER's avatar
Hervé MENAGER committed
48
    SOURCES = (
49
50
51
        ('PM', 'PubMed ID'),
        ('PT', 'Patent'),
        ('DO', 'DOI ID')
Hervé  MENAGER's avatar
Hervé MENAGER committed
52
    )
53
54
55
56
57
    id_source_validators = dict(
        PM=re.compile("^[0-9]+$"),
        PT=re.compile("^.*$"),
        DO=re.compile("^.*$"),
    )
Hervé  MENAGER's avatar
Hervé MENAGER committed
58
59
    source = models.CharField(
        'Bibliographic type', max_length=2, choices=SOURCES, default='PM')
Hervé  MENAGER's avatar
Hervé MENAGER committed
60
61
    id_source = models.CharField('Bibliographic ID', max_length=25)
    title = models.CharField('Title', max_length=300)
62
    journal_name = models.CharField('Journal name', max_length=50, null=True, blank=True)
Hervé  MENAGER's avatar
Hervé MENAGER committed
63
64
    authors_list = models.CharField('Authors list', max_length=500)
    biblio_year = models.PositiveSmallIntegerField('Year')
65
    cytotox = models.BooleanField('Cytotoxicity data', default=False)
Rachel TORCHET's avatar
Rachel TORCHET committed
66
67
68
69
    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
70
71
    pharmacokinetic = models.BooleanField(
        'pharmacokinetic study', default=False)
Rachel TORCHET's avatar
Rachel TORCHET committed
72
    xray = models.BooleanField('X-Ray data', default=False)
Hervé  MENAGER's avatar
Hervé MENAGER committed
73

74
    def autofill(self):
Hervé  MENAGER's avatar
Hervé MENAGER committed
75
76
77
78
        """
        fetch information from external services
        (Pubmed or Google patents)
        """
79
80
81
        if self.source == 'PM':
            info = get_pubmed_info(self.id_source)
        else:
82
            info = get_google_patent_info(self.id_source)
83
84
85
86
        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
87

88
89
    def clean(self):
        super().clean()
90
91
92
93
94
95
96
97
98
99
100
101
102
        Bibliography.validate_source_id(self.id_source, self.source)

    def has_external_url(self):
        return self.source == 'PM'

    def get_external_url(self):
        if self.source == 'PM':
            return "https://www.ncbi.nlm.nih.gov/pubmed/" + str(self.id_source)

    @staticmethod
    def validate_source_id(id_source, source):
        id_source_validator = Bibliography.id_source_validators[source]
        if not id_source_validator.match(id_source):
103
104
105
106
107
            raise ValidationError(
                dict(
                    id_source=_("Must match pattern %s for this selected source" % id_source_validator.pattern)
                )
            )
108
        return True
109

Hervé  MENAGER's avatar
Hervé MENAGER committed
110
111
112
    class Meta:
        verbose_name_plural = "bibliographies"

113
114
    def __str__(self):
        return '{}, {}'.format(self.source, self.id_source)
115

Hervé  MENAGER's avatar
Hervé MENAGER committed
116

117
class Taxonomy(AutoFillableModel):
Hervé  MENAGER's avatar
Hervé MENAGER committed
118
119
120
121
    """
    Taxonomy IDs (from NCBI Taxonomy) 
    and the corresponding human-readable name
    """
Hervé  MENAGER's avatar
Hervé MENAGER committed
122
123
    taxonomy_id = models.DecimalField(
        'NCBI TaxID', unique=True, max_digits=9, decimal_places=0)
Hervé  MENAGER's avatar
Hervé MENAGER committed
124
    name = models.CharField('Organism name', max_length=200)
125

126
    def autofill(self):
Hervé  MENAGER's avatar
Hervé MENAGER committed
127
128
129
130
        """
        fetch information from external services
        (NCBI Entrez)
        """
131
132
133
        info = get_taxonomy_info(self.taxonomy_id)
        self.name = info['scientific_name']

134
135
136
    def __str__(self):
        return self.name

Hervé  MENAGER's avatar
Hervé MENAGER committed
137
138
    class Meta:
        verbose_name_plural = "taxonomies"
Hervé  MENAGER's avatar
Hervé MENAGER committed
139

Hervé  MENAGER's avatar
Hervé MENAGER committed
140

141
class MolecularFunction(AutoFillableModel):
Hervé  MENAGER's avatar
Hervé MENAGER committed
142
143
144
145
    """
    Molecular functions (from Gene Ontology) 
    and the corresponding human-readable description
    """
Hervé  MENAGER's avatar
Hervé MENAGER committed
146
    go_id = models.CharField('Gene Ontology ID', unique=True, max_length=10)
Hervé  MENAGER's avatar
Hervé MENAGER committed
147
    # GO term id format: 'GO:0000000'
Hervé  MENAGER's avatar
Hervé MENAGER committed
148
149
    description = models.CharField('description', max_length=500)

150
    def autofill(self):
Hervé  MENAGER's avatar
Hervé MENAGER committed
151
152
153
154
        """
        fetch information from external services
        (EBI OLS)
        """
155
156
157
        info = get_go_info(self.go_id)
        self.description = info['label']

158
159
160
161
    @property
    def name(self):
        return self.go_id + ' ' + self.description

162
163
164
    def __str__(self):
        return self.description

Hervé  MENAGER's avatar
Hervé MENAGER committed
165

166
class Protein(AutoFillableModel):
Hervé  MENAGER's avatar
Hervé MENAGER committed
167
168
169
170
    """
    Protein information (from Uniprot) 
    and the corresponding human-readable name
    """
Hervé  MENAGER's avatar
Hervé MENAGER committed
171
    uniprot_id = models.CharField('Uniprot ID', unique=True, max_length=10)
Hervé  MENAGER's avatar
Hervé MENAGER committed
172
173
    recommended_name_long = models.CharField(
        'Uniprot Recommended Name (long)', max_length=75)
Hervé  MENAGER's avatar
Hervé MENAGER committed
174
175
176
    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)
177
    organism = models.ForeignKey('Taxonomy', models.CASCADE)
Hervé  MENAGER's avatar
Hervé MENAGER committed
178
179
    molecular_functions = models.ManyToManyField(MolecularFunction)

180
    def autofill(self):
Hervé  MENAGER's avatar
Hervé MENAGER committed
181
182
183
184
        """
        fetch information from external services
        (Uniprot) and create Taxonomy/Molecular Functions if needed
        """
185
        info = get_uniprot_info(self.uniprot_id)
186
        self.recommended_name_long = info['recommended_name']
187
188
        self.gene_name = info['gene']
        self.entry_name = info['entry_name']
189
        self.short_name = info['short_name']
190
191
192
193
194
        try:
            taxonomy = Taxonomy.objects.get(taxonomy_id=info['organism'])
        except Taxonomy.DoesNotExist:
            taxonomy = Taxonomy()
            taxonomy.taxonomy_id = info['organism']
195
            taxonomy.save(autofill=True)
196
        self.organism = taxonomy
197
        super(Protein, self).save()
198
199
200
201
202
203
        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
204
                mol_function.save(autofill=True)
205
            self.molecular_functions.add(mol_function)
206

207
208
209
    def __str__(self):
        return '{} ({})'.format(self.uniprot_id, self.recommended_name_long)

Hervé  MENAGER's avatar
Hervé MENAGER committed
210

211
class Domain(AutoFillableModel):
Hervé  MENAGER's avatar
Hervé MENAGER committed
212
213
214
    """
    Domain (i.e. Protein domain) information (from PFAM) 
    """
Hervé  MENAGER's avatar
Hervé MENAGER committed
215
216
    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
217
    pfam_description = models.CharField('Pfam Description', max_length=100)
Hervé  MENAGER's avatar
Hervé MENAGER committed
218
    domain_family = models.CharField('Domain family', max_length=25)
Bryan  BRANCOTTE's avatar
Bryan BRANCOTTE committed
219

Hervé  MENAGER's avatar
Hervé MENAGER committed
220
221
    # TODO: what is this field? check database
    # contents
222

223
    def autofill(self):
Hervé  MENAGER's avatar
Hervé MENAGER committed
224
225
226
227
        """
        fetch information from external services
        (PFAM)
        """
228
229
230
        info = get_pfam_info(self.pfam_acc)
        self.pfam_id = info['id']
        self.pfam_description = info['description']
Hervé  MENAGER's avatar
Hervé MENAGER committed
231

232
233
234
235
    @property
    def name(self):
        return self.pfam_id

236
237
238
    def __str__(self):
        return '{} ({}-{})'.format(self.pfam_acc, self.pfam_id, self.pfam_description)

Hervé  MENAGER's avatar
Hervé MENAGER committed
239

240
class ProteinDomainComplex(models.Model):
Hervé  MENAGER's avatar
Hervé MENAGER committed
241
    """
Bryan  BRANCOTTE's avatar
Bryan BRANCOTTE committed
242
    Protein-Domain association
Hervé  MENAGER's avatar
Hervé MENAGER committed
243
    """
244
245
    protein = models.ForeignKey('Protein', models.CASCADE)
    domain = models.ForeignKey('Domain', models.CASCADE)
Hervé  MENAGER's avatar
Hervé MENAGER committed
246
247
248
    ppc_copy_nb = models.IntegerField(
        'Number of copies of the protein in the complex')

Hervé  MENAGER's avatar
Hervé MENAGER committed
249
250
    class Meta:
        verbose_name_plural = "complexes"
251

252
253
254
    def __str__(self):
        return '{}-{}'.format(self.protein_id, self.domain_id)

255
256
    def name(self):
        return self.protein.short_name
Hervé  MENAGER's avatar
Hervé MENAGER committed
257

258

259
class ProteinDomainBoundComplex(ProteinDomainComplex):
Hervé  MENAGER's avatar
Hervé MENAGER committed
260
261
262
    """
    Protein-Domain association with a "bound complex" role
    """
Hervé  MENAGER's avatar
Hervé MENAGER committed
263
264
265
    ppp_copy_nb_per_p = models.IntegerField(
        'Number of copies of the protein in the pocket')

266
267
    class Meta:
        verbose_name_plural = "bound complexes"
Hervé  MENAGER's avatar
Hervé MENAGER committed
268
269


270
class ProteinDomainPartnerComplex(ProteinDomainComplex):
Hervé  MENAGER's avatar
Hervé MENAGER committed
271
272
273
    """
    Protein-Domain association with a "partner complex" role
    """
Hervé  MENAGER's avatar
Hervé MENAGER committed
274

275
276
    class Meta:
        verbose_name_plural = "partner complexes"
Hervé  MENAGER's avatar
Hervé MENAGER committed
277

Hervé  MENAGER's avatar
Hervé MENAGER committed
278

279
class Symmetry(models.Model):
Hervé  MENAGER's avatar
Hervé MENAGER committed
280
281
282
    """
    Symmetry of a PPI
    """
283
284
    code = models.CharField('Symmetry code', max_length=2)
    description = models.CharField('Description', max_length=300)
Hervé  MENAGER's avatar
Hervé MENAGER committed
285

286
287
288
    class Meta:
        verbose_name_plural = "symmetries"

289
290
291
    def __str__(self):
        return '{} ({})'.format(self.code, self.description)

292
293

class Disease(models.Model):
Hervé  MENAGER's avatar
Hervé MENAGER committed
294
    name = models.CharField('Disease', max_length=30, unique=True)
Bryan  BRANCOTTE's avatar
Bryan BRANCOTTE committed
295

Hervé  MENAGER's avatar
Hervé MENAGER committed
296
    # is there any database/nomenclature for diseases?
297
298
299
300

    def __str__(self):
        return self.name

Bryan  BRANCOTTE's avatar
Bryan BRANCOTTE committed
301

Hervé  MENAGER's avatar
Hervé MENAGER committed
302
class PpiFamily(models.Model):
Hervé  MENAGER's avatar
Hervé MENAGER committed
303
304
305
    """
    PPI Family
    """
Hervé  MENAGER's avatar
Hervé MENAGER committed
306
307
    name = models.CharField('Name', max_length=30, unique=True)

308
309
310
    class Meta:
        verbose_name_plural = "PPI Families"

Hervé  MENAGER's avatar
Hervé MENAGER committed
311
312
    def __str__(self):
        return self.name
Hervé  MENAGER's avatar
Hervé MENAGER committed
313

Hervé  MENAGER's avatar
Hervé MENAGER committed
314

315
class Ppi(AutoFillableModel):
Hervé  MENAGER's avatar
Hervé MENAGER committed
316
317
318
    """
    PPI
    """
319
    pdb_id = models.CharField('PDB ID', max_length=4, null=True, blank=True)
Hervé  MENAGER's avatar
Hervé MENAGER committed
320
321
    pockets_nb = models.IntegerField(
        'Total number of pockets in the complex', default=1)
322
    symmetry = models.ForeignKey(Symmetry, models.CASCADE)
323
    diseases = models.ManyToManyField(Disease)
324
    family = models.ForeignKey(PpiFamily, models.CASCADE, null=True, blank=True)
325
    name = models.TextField('PPI name', null=True, blank=True)
Hervé  MENAGER's avatar
Hervé MENAGER committed
326

327
    def __str__(self):
328
        return 'PPI #{} on {}'.format(self.id, self.name)
329

330
331
332
    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()
333
334
335
336
337

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

341
    def compute_name_from_protein_names(self):
Hervé  MENAGER's avatar
Hervé MENAGER committed
342
        all_protein_names = set(
343
            [ppi_complex.complex.protein.short_name for ppi_complex in self.ppicomplex_set.all()])
Hervé  MENAGER's avatar
Hervé MENAGER committed
344
345
        bound_protein_names = set(
            [ppi_complex.complex.protein.short_name for ppi_complex in self.get_ppi_bound_complexes()])
346
347
348
349
        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
350
        if partner_str != '':
351
352
            name += ' / ' + partner_str
        return name
353

Hervé  MENAGER's avatar
Hervé MENAGER committed
354

Hervé  MENAGER's avatar
Hervé MENAGER committed
355
class PpiComplex(models.Model):
Hervé  MENAGER's avatar
Hervé MENAGER committed
356
357
358
    """
    PPI Complex
    """
359
360
    ppi = models.ForeignKey(Ppi, models.CASCADE)
    complex = models.ForeignKey(ProteinDomainComplex, models.CASCADE)
Hervé  MENAGER's avatar
Hervé MENAGER committed
361
362
    cc_nb = models.IntegerField(
        'Number of copies of the complex in the PPI', default=1)
Hervé  MENAGER's avatar
Hervé MENAGER committed
363
364
365
366

    class Meta:
        verbose_name_plural = "Ppi complexes"

367
368
369
    def __str__(self):
        return 'PPI {}, Complex {} ({})'.format(self.ppi, self.complex, self.cc_nb)

Hervé  MENAGER's avatar
Hervé MENAGER committed
370

371
class CompoundManager(models.Manager):
Hervé  MENAGER's avatar
Hervé MENAGER committed
372
373
374
375
    """
    CompoundManager adds automatically a number of annotations to the results
    of the database query, used for filters and compound card
    """
376
377

    def get_queryset(self):
Bryan  BRANCOTTE's avatar
Bryan BRANCOTTE committed
378
        # @formatter:off
379
        qs = super().get_queryset()
380
        # with number of publications
381
        qs = qs.annotate(pubs=Count('refcompoundbiblio', distinct=True))
382
        # with best activity
Bryan  BRANCOTTE's avatar
Bryan BRANCOTTE committed
383
        qs = qs.annotate(best_activity=Max('compoundactivityresult__activity'))
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
        # with LE
        qs = qs.annotate(le=Cast(1.37 * Max('compoundactivityresult__activity') / F('nb_atom_non_h'), FloatField()))
        # with LLE
        qs = qs.annotate(lle=Cast(Max('compoundactivityresult__activity') - F('a_log_p'), FloatField()))
        # Lipinsky MW (<=500)
        qs = qs.annotate(lipinsky_mw=Case(When(molecular_weight__lte=500, then=True), default=False, output_field=BooleanField()))
        # Lipinsky hba (<=10)
        qs = qs.annotate(lipinsky_hba=Case(When(nb_acceptor_h__lte=10, then=True), default=False, output_field=BooleanField()))
        # Lipinsky hbd (<5)
        qs = qs.annotate(lipinsky_hbd=Case(When(nb_donor_h__lte=5, then=True), default=False, output_field=BooleanField()))
        # Lipinsky a_log_p (<5)
        qs = qs.annotate(lipinsky_a_log_p=Case(When(a_log_p__lte=5, then=True), default=False, output_field=BooleanField()))
        # Lipinsky global
        qs = qs.annotate(lipinsky_score=Cast(F('lipinsky_mw'), IntegerField())+Cast(F('lipinsky_hba'), IntegerField())+ \
            Cast(F('lipinsky_hbd'), IntegerField()) + Cast(F('lipinsky_a_log_p'), IntegerField()))
        qs = qs.annotate(lipinsky=Case(When(lipinsky_score__gte=3, then=True), default=False, output_field=BooleanField()))
        # Veber hba_hbd (<=12)
        qs = qs.annotate(hba_hbd=F('nb_acceptor_h')+F('nb_donor_h'))
        qs = qs.annotate(veber_hba_hbd=Case(When(hba_hbd__lte=12, then=True), default=False, output_field=BooleanField()))
        # Veber TPSA (<=140)
        qs = qs.annotate(veber_tpsa=Case(When(tpsa__lte=140, then=True), default=False, output_field=BooleanField()))
        # Veber Rotatable Bonds (<=10)
        qs = qs.annotate(veber_rb=Case(When(nb_rotatable_bonds__lte=10, then=True), default=False, output_field=BooleanField()))
        # Veber global (Rotatable bonds and (hba_hbd or tpsa))
408
409
        #qs = qs.annotate(veber=F('veber_rb').bitand(F('veber_hba_hbd').bitor(F('veber_tpsa'))))
        qs = qs.annotate(veber=Case(When(Q(Q(nb_rotatable_bonds__lte=10) & (Q(hba_hbd__lte=12) | Q(tpsa__lte=140))), then=True), default=False, output_field=BooleanField()))
410
411
412
413
414
        # Pfizer AlogP (<=3)
        qs = qs.annotate(pfizer_a_log_p=Case(When(a_log_p__lte=3, then=True), default=False, output_field=BooleanField()))
        # Pfizer TPSA (>=75)
        qs = qs.annotate(pfizer_tpsa=Case(When(tpsa__gte=75, then=True), default=False, output_field=BooleanField()))
        # Pfizer global (AlogP and TPSA)
415
416
        #qs = qs.annotate(pfizer=F('pfizer_a_log_p').bitand(F('pfizer_tpsa')))
        qs = qs.annotate(pfizer=Case(When(Q(Q(a_log_p__lte=3) & Q(tpsa__gte=75)), then=True), default=False, output_field=BooleanField()))
417
        # PDB ligand available
418
        qs = qs.annotate(pdb_ligand_av=Cast(Max(Case(When(compoundaction__ligand_id__isnull=False, then=1), default=0, output_field=IntegerField())), BooleanField()))
419
420
421
422
423
424
        # inhibition role
        qs = qs.annotate(inhibition_role=Case(When(compoundactivityresult__modulation_type='I', then=True), default=False, output_field=BooleanField()))
        # binding role
        qs = qs.annotate(binding_role=Case(When(compoundactivityresult__modulation_type='B', then=True), default=False, output_field=BooleanField()))
        # stabilisation role
        qs = qs.annotate(stabilisation_role=Case(When(compoundactivityresult__modulation_type='S', then=True), default=False, output_field=BooleanField()))
425
        # cellular tests performed
426
        qs = qs.annotate(celltest_av=Cast(Max(Case(When(compoundactivityresult__test_activity_description__test_type='CELL', then=1), default=0, output_field=IntegerField())), BooleanField()))
427
        # inhibition tests performed
428
        qs = qs.annotate(inhitest_av=Cast(Max(Case(When(compoundactivityresult__test_activity_description__test_modulation_type='I', then=1), default=0, output_field=IntegerField())), BooleanField()))
429
        # stabilisation tests performed
430
        qs = qs.annotate(stabtest_av=Cast(Max(Case(When(compoundactivityresult__test_activity_description__test_modulation_type='S', then=1), default=0, output_field=IntegerField())), BooleanField()))
431
        # binding tests performed
432
        qs = qs.annotate(bindtest_av=Cast(Max(Case(When(compoundactivityresult__test_activity_description__test_modulation_type='B', then=1), default=0, output_field=IntegerField())), BooleanField()))
433
        # pharmacokinetic tests performed
434
        qs = qs.annotate(pktest_av=Cast(Max(Case(When(refcompoundbiblio__bibliography__pharmacokinetic=True, then=1), default=0, output_field=IntegerField())), BooleanField()))
435
        # cytotoxicity tests performedudy
436
        qs = qs.annotate(cytoxtest_av=Cast(Max(Case(When(refcompoundbiblio__bibliography__cytotox=True, then=1), default=0, output_field=IntegerField())), BooleanField()))
437
        # in silico st performed
438
        qs = qs.annotate(insilico_av=Cast(Max(Case(When(refcompoundbiblio__bibliography__in_silico=True, then=1), default=0, output_field=IntegerField())), BooleanField()))
439
440
        # number of tests available
        qs = qs.annotate(tests_av=Count('compoundactivityresult', distinct=True))
Bryan  BRANCOTTE's avatar
Bryan BRANCOTTE committed
441
        #@formatter:on
442
443
        return qs

Bryan  BRANCOTTE's avatar
Bryan BRANCOTTE committed
444

445
class Compound(AutoFillableModel):
Hervé  MENAGER's avatar
Hervé MENAGER committed
446
447
448
    """
    Chemical compound
    """
Bryan  BRANCOTTE's avatar
Bryan BRANCOTTE committed
449
    objects = CompoundManager()
450
451
    canonical_smile = models.TextField(
        'Canonical Smile', unique=True)
Hervé  MENAGER's avatar
Hervé MENAGER committed
452
453
454
455
456
    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)
457
    fsp3 = models.DecimalField('Fsp3', max_digits=3, decimal_places=2)
Hervé  MENAGER's avatar
Hervé MENAGER committed
458
459
460
461
462
463
464
465
466
467
    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)
468
469
470
471
    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
472
473
474
475
    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')
476
477
    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
478
479
480
481
482
483
484
485
486
487
488
489
490
491
    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')
492
    nb_n = models.IntegerField('Number of nitrogen atoms')
Hervé  MENAGER's avatar
Hervé MENAGER committed
493
494
495
    nb_o = models.IntegerField('Number of oxygen atoms')
    nb_rings = models.IntegerField('Number of rings')
    nb_rotatable_bonds = models.IntegerField('Number of rotatable bonds')
496
497
    inchi = models.TextField('InChi')
    inchikey = models.TextField('InChiKey')
Hervé  MENAGER's avatar
Hervé MENAGER committed
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
    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)
523

524
    class Meta:
Bryan  BRANCOTTE's avatar
Bryan BRANCOTTE committed
525
        ordering = ['id']
526

527
528
529
    def compute_drugbank_compound_similarity(self):
        """ compute Tanimoto similarity to existing DrugBank compounds """
        self.save()
530
        # fingerprints to compute drugbank similarities are in settings module, default FP2
531
        fingerprinter = FingerPrinter(getattr(settings, "DRUGBANK_FINGERPRINTS", "FP2"))
Bryan  BRANCOTTE's avatar
Bryan BRANCOTTE committed
532
533
        # 1. compute tanimoto for SMILES query vs all compounds
        smiles_dict = {c.id: c.canonical_smiles for c in DrugBankCompound.objects.all()}
534
535
536
537
        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():
Bryan  BRANCOTTE's avatar
Bryan BRANCOTTE committed
538
539
540
541
542
            dbcts.append(DrugbankCompoundTanimoto(
                compound=self,
                drugbank_compound=DrugBankCompound.objects.get(id=id_),
                tanimoto=tanimoto,
            ))
543
544
        DrugbankCompoundTanimoto.objects.bulk_create(dbcts)

Hervé  MENAGER's avatar
Hervé MENAGER committed
545
546
547
    @property
    def biblio_refs(self):
        """
Hervé  MENAGER's avatar
Hervé MENAGER committed
548
        return all RefCompoundBiblio related to this compound
Hervé  MENAGER's avatar
Hervé MENAGER committed
549
550
        """
        return RefCompoundBiblio.objects.filter(compound=self)
551

552
553
554
555
556
557
558
559
560
561
562
563
564
    @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

565
    @property
Hervé  MENAGER's avatar
Hervé MENAGER committed
566
    def compound_action_ligand_ids(self):
567
568
569
        """
        return all PDB codes of the corresponding compound actions
        """
Hervé  MENAGER's avatar
Hervé MENAGER committed
570
        ligand_ids = set()
571
        for ca in self.compoundaction_set.all():
Hervé  MENAGER's avatar
Hervé MENAGER committed
572
573
            ligand_ids.add(ca.ligand_id)
        return ligand_ids
574

575
576
    @property
    def best_pXC50_activity(self):
577
        return self.compoundactivityresult_set.aggregate(Max('activity'))['activity__max']
578
579
580
581
582
583

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

586
    @property
587
    def best_pXC50_activity_ppi_name(self):
588
        """
589
        Name of the PPI corresponding to the best PXC50 activity
590
        """
591
592
593
        best_activity_car = self.best_pXC50_compound_activity_result
        if best_activity_car is None:
            return None
594
595
596
        ppi_name = best_activity_car.test_activity_description.ppi.name
        return ppi_name

597
598
599
600
601
602
603
604
605
606
607
    @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

608
609
610
611
612
613
614
615
616
617
618
619
620
621
    @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()

622
623
624
625
626
627
    @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()]))
Bryan  BRANCOTTE's avatar
Bryan BRANCOTTE committed
628

629
630
631
    @property
    def sorted_similar_drugbank_compounds(self):
        return self.drugbankcompoundtanimoto_set.order_by('-tanimoto')
Bryan  BRANCOTTE's avatar
Bryan BRANCOTTE committed
632

633
634
635
    def autofill(self):
        # compute InChi and InChiKey
        self.inchi = smi2inchi(self.canonical_smile)
636
        self.inchikey = smi2inchikey(self.canonical_smile)
637
        self.compute_drugbank_compound_similarity()
638

639
640
641
    def __str__(self):
        return 'Compound #{}'.format(self.id)

Bryan  BRANCOTTE's avatar
Bryan BRANCOTTE committed
642

643
644
645
class CompoundTanimoto(models.Model):
    canonical_smiles = models.TextField(
        'Canonical Smile')
646
    fingerprint = models.TextField('Fingerprint')
647
648
649
650
651
652
    compound = models.ForeignKey(Compound, models.CASCADE)
    tanimoto = models.DecimalField(
        'Tanimoto value', max_digits=5, decimal_places=4)

    class Meta:
        unique_together = (
653
            ('canonical_smiles', 'fingerprint', 'compound'))
654

Bryan  BRANCOTTE's avatar
Bryan BRANCOTTE committed
655

656
def create_tanimoto(smiles_query, fingerprint):
Hervé  MENAGER's avatar
Hervé MENAGER committed
657
658
659
660
    """
    Compute the Tanimoto similarity between a given SMILES and the compounds
    then insert the results in CompoundTanimoto
    """
Bryan  BRANCOTTE's avatar
Bryan BRANCOTTE committed
661
662
    if CompoundTanimoto.objects.filter(canonical_smiles=smiles_query, fingerprint=fingerprint).count() == 0:
        smiles_dict = {c.id: c.canonical_smile for c in Compound.objects.all()}
663
        fingerprinter = FingerPrinter(fingerprint)
Bryan  BRANCOTTE's avatar
Bryan BRANCOTTE committed
664
        # 1. compute tanimoto for SMILES query vs all compounds
665
        tanimoto_dict = fingerprinter.tanimoto_smiles(smiles_query, smiles_dict)
Bryan  BRANCOTTE's avatar
Bryan BRANCOTTE committed
666
        # 2. insert results in a table with three fields: SMILES query, compound id, tanimoto index
667
668
        cts = []
        for id_, smiles in smiles_dict.items():
Bryan  BRANCOTTE's avatar
Bryan BRANCOTTE committed
669
670
            cts.append(CompoundTanimoto(canonical_smiles=smiles_query, fingerprint=fingerprint,
                                        compound=Compound.objects.get(id=id_), tanimoto=tanimoto_dict[id_]))
671
        CompoundTanimoto.objects.bulk_create(cts)
672

Bryan  BRANCOTTE's avatar
Bryan BRANCOTTE committed
673

674
class PcaBiplotData(models.Model):
Hervé  MENAGER's avatar
Hervé MENAGER committed
675
676
677
678
    """
    PCA biplot data
    the table contains all the data as one JSON text in one row
    """
679
680
    pca_biplot_data = models.TextField(
        'PCA biplot JSON data', blank=True, null=True)
Hervé  MENAGER's avatar
Hervé MENAGER committed
681

682

683
class LeLleBiplotData(models.Model):
Hervé  MENAGER's avatar
Hervé MENAGER committed
684
685
686
687
    """
    LE-LLE biplot data
    the table contains all the data as one JSON text in one row
    """
688
689
    le_lle_biplot_data = models.TextField(
        'LE-LLE biplot JSON data', blank=True, null=True)
Hervé  MENAGER's avatar
Hervé MENAGER committed
690

691

692
class CellLine(models.Model):
Hervé  MENAGER's avatar
Hervé MENAGER committed
693
694
695
    """
    Cell lines
    """
696
    name = models.CharField('Name', max_length=50, unique=True)
Hervé  MENAGER's avatar
Hervé MENAGER committed
697

698
699
700
    def __str__(self):
        return self.name

Hervé  MENAGER's avatar
Hervé MENAGER committed
701

702
class TestActivityDescription(models.Model):
Hervé  MENAGER's avatar
Hervé MENAGER committed
703
704
705
    """
    Activity test descriptions
    """
706
707
708
709
710
711
712
713
714
    TEST_TYPES = (
        ('BIOCH', 'Biochemical assay'),
        ('CELL', 'Cellular assay')
    )
    TEST_MODULATION_TYPES = (
        ('B', 'Binding'),
        ('I', 'Inhibition'),
        ('S', 'Stabilization')
    )
715
716
717
718
    PROTEIN_BOUND_CONSTRUCTS = (
        ('F', 'Full length'),
        ('U', 'Unspecified')
    )
Bryan  BRANCOTTE's avatar
Bryan BRANCOTTE committed
719
720
721
722
    biblio = models.ForeignKey(
        Bibliography,
        on_delete=models.CASCADE,
    )
Hervé  MENAGER's avatar
Hervé MENAGER committed
723
    protein_domain_bound_complex = models.ForeignKey(
Bryan  BRANCOTTE's avatar
Bryan BRANCOTTE committed
724
725
726
        ProteinDomainBoundComplex,
        on_delete=models.CASCADE,
    )
727
    ppi = models.ForeignKey(Ppi, models.CASCADE, blank=True, null=True)
Bryan  BRANCOTTE's avatar
Bryan BRANCOTTE committed
728
729
730
731
732
733
734
    test_name = models.CharField(
        verbose_name='Test name',
        max_length=100,
    )
    is_primary = models.BooleanField(
        verbose_name='Is primary',
    )
Hervé  MENAGER's avatar
Hervé MENAGER committed
735
    protein_bound_construct = models.CharField(
Bryan  BRANCOTTE's avatar
Bryan BRANCOTTE committed
736
737
738
739
740
741
742
743
744
745
746
        verbose_name='Protein bound construct',
        max_length=5,
        choices=PROTEIN_BOUND_CONSTRUCTS,
        blank=True,
        null=True,
    )
    test_type = models.CharField(
        verbose_name='Test type',
        max_length=5,
        choices=TEST_TYPES,
    )
Hervé  MENAGER's avatar
Hervé MENAGER committed
747
    test_modulation_type = models.CharField(
Bryan  BRANCOTTE's avatar
Bryan BRANCOTTE committed
748
749
750
751
        verbose_name='Test modulation type',
        max_length=1,
        choices=TEST_MODULATION_TYPES,
    )
Hervé  MENAGER's avatar
Hervé MENAGER committed
752
    nb_active_compounds = models.IntegerField(
Bryan  BRANCOTTE's avatar
Bryan BRANCOTTE committed
753
754
        verbose_name='Total number of active compounds',
    )
Hervé  MENAGER's avatar
Hervé MENAGER committed
755
    cell_line = models.ForeignKey(
Bryan  BRANCOTTE's avatar
Bryan BRANCOTTE committed
756
757
758
759
760
        CellLine,
        on_delete=models.CASCADE,
        blank=True,
        null=True,
    )
761

Hervé  MENAGER's avatar
Hervé MENAGER committed
762
    def get_complexes(self):
763
764
765
766
        """
        get the complexes tested for this PPI
        depends on the modulation type
        """
Hervé  MENAGER's avatar
Hervé MENAGER committed
767
        if self.test_modulation_type == 'I':
768
            return self.ppi.ppicomplex_set.all()
769
770
        else:
            return self.ppi.get_ppi_bound_complexes()
771

772
773
774
    @property
    def protein_domain_partner_complex(self):
        for ppic in self.ppi.ppicomplex_set.all():
Hervé  MENAGER's avatar
Hervé MENAGER committed
775
            if hasattr(ppic.complex, 'proteindomainpartnercomplex'):
776
777
778
                return ppic.complex.proteindomainpartnercomplex
        return None

779
780
781
782
783
784
785
    @property
    def name(self):
        return self.test_name

    def __str__(self):
        return self.get_test_type_display()

Hervé  MENAGER's avatar
Hervé MENAGER committed
786

787
class CompoundActivityResult(models.Model):
Hervé  MENAGER's avatar
Hervé MENAGER committed
788
789
790
    """
    Activity test results on a compound
    """
791
792
793
794
    MODULATION_TYPES = (
        ('I', 'Inhibition'),
        ('S', 'Stabilization')
    )
Hervé  MENAGER's avatar
Hervé MENAGER committed
795
    ACTIVITY_TYPES = (
Hervé  MENAGER's avatar
Hervé MENAGER committed
796
797
798
799
        ('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
800
    )
801
    compound = models.ForeignKey(Compound, models.CASCADE)
Hervé  MENAGER's avatar
Hervé MENAGER committed
802
803
    test_activity_description = models.ForeignKey(
        TestActivityDescription, models.CASCADE)
Hervé  MENAGER's avatar
Hervé MENAGER committed
804
805
806
807
    activity_type = models.CharField(
        'Activity type', max_length=5, choices=ACTIVITY_TYPES)
    activity = models.DecimalField(
        'Activity', max_digits=12, decimal_places=10)
808
    inhibition_percentage = models.DecimalField(
809
        'Inhibition percentage', max_digits=3, decimal_places=0, null=True, blank=True)
Hervé  MENAGER's avatar
Hervé MENAGER committed
810
811
    modulation_type = models.CharField(
        'Modulation type', max_length=1, choices=MODULATION_TYPES)
Hervé  MENAGER's avatar
Hervé MENAGER committed
812
813

    class Meta:
Hervé  MENAGER's avatar
Hervé MENAGER committed
814
815
816
        unique_together = (
            ('compound', 'test_activity_description', 'activity_type'),)

817
    def __str__(self):
Bryan  BRANCOTTE's avatar
Bryan BRANCOTTE committed
818
819
820
821
822
        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
823

824
825
826
    def is_best(self):
        return self.compound.best_pXC50_compound_activity_result.id == self.id

Hervé  MENAGER's avatar
Hervé MENAGER committed
827

828
class TestCytotoxDescription(models.Model):
Hervé  MENAGER's avatar
Hervé MENAGER committed
829
830
831
    """
    Cytotoxicity test descriptions
    """
832
    biblio = models.ForeignKey(Bibliography, models.CASCADE)
Hervé  MENAGER's avatar
Hervé MENAGER committed
833
    test_name = models.CharField('Cytotoxicity test name', max_length=100)
834
    cell_line = models.ForeignKey(CellLine, models.CASCADE)
Hervé  MENAGER's avatar
Hervé MENAGER committed
835
836
837
    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
838

839
class CompoundCytotoxicityResult(models.Model):
Hervé  MENAGER's avatar
Hervé MENAGER committed
840
841
842
    """
    Cytotoxicity test results on a compound
    """
843
    compound = models.ForeignKey(Compound, models.CASCADE)
Hervé  MENAGER's avatar
Hervé MENAGER committed
844
845
    test_cytotoxicity_description = models.ForeignKey(
        TestCytotoxDescription, models.CASCADE)
846
    toxicity = models.BooleanField('Toxicity', default=False)
Hervé  MENAGER's avatar
Hervé MENAGER committed
847
848

    class Meta:
849
        unique_together = (('compound', 'test_cytotoxicity_description'),)
850

851
    def __str__(self):
Bryan  BRANCOTTE's avatar
Bryan BRANCOTTE committed
852
853
854
855
        return 'Compound cytotoxicity result for test {} on {}'.format(
            self.test_cytotoxicity_description.id,
            self.compound.id,
        )
856

Hervé  MENAGER's avatar
Hervé MENAGER committed
857

858
class TestPKDescription(models.Model):
Hervé  MENAGER's avatar
Hervé MENAGER committed
859
860
861
    """
    Pharmacokinetic test descriptions
    """
862
863
864
865
866
867
    ADMINISTRATION_MODES = (
        ('IV', ''),
        ('PO', ''),
        ('IP', ''),
        ('SL', 'SL')
    )
868
    biblio = models.ForeignKey(Bibliography, models.CASCADE)
Hervé  MENAGER's avatar
Hervé MENAGER committed
869
    test_name = models.CharField('Pharmacokinetic test name', max_length=100)
870
    organism = models.ForeignKey(Taxonomy, models.CASCADE)
Hervé  MENAGER's avatar
Hervé MENAGER committed
871
872
    administration_mode = models.CharField(
        'Administration mode', max_length=2, choices=ADMINISTRATION_MODES, blank=True, null=True)
873
874
    concentration = models.DecimalField(
        'Concentration in mg/l', max_digits=7, decimal_places=3, blank=True, null=True)
Hervé  MENAGER's avatar
Hervé MENAGER committed
875
    dose = models.DecimalField(
876
        'Dose in mg/kg', max_digits=9, decimal_places=4, blank=True, null=True)
Hervé  MENAGER's avatar
Hervé MENAGER committed
877
878
879
    dose_interval = models.IntegerField(
        'Dose interval, in hours', blank=True, null=True)

880
881

class CompoundPKResult(models.Model):
Hervé  MENAGER's avatar
Hervé MENAGER committed
882
883
884
    """
    Pharmacokinetic test results on a compound
    """
885
886
    compound = models.ForeignKey(Compound, models.CASCADE)
    test_pk_description = models.ForeignKey(TestPKDescription, models.CASCADE)
887
    tolerated = models.NullBooleanField('Tolerated', null=True)
Hervé  MENAGER's avatar
Hervé MENAGER committed
888
889
890
891
    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)
892
    c_max = models.DecimalField(
Hervé  MENAGER's avatar
Hervé MENAGER committed
893
894
895
896
897
898
899
        '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
900
901

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

904
905
906
    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
907

908
class CompoundAction(models.Model):
Hervé  MENAGER's avatar
Hervé MENAGER committed
909
910
911
    """
    Compound action
    """
912
913
    ACTIVATION_MODES = (
        ('O', 'Orthosteric'),
914
915
        ('A', 'Allosteric'),
        ('U', 'Unspecified')
916
    )
917
    compound = models.ForeignKey(Compound, models.CASCADE)
Hervé  MENAGER's avatar
Hervé MENAGER committed
918
919
    activation_mode = models.CharField(
        'Activation mode', max_length=1, choices=ACTIVATION_MODES)
920
    ppi = models.ForeignKey(Ppi, models.CASCADE)
921
    ligand_id = models.CharField('PDB Ligand ID', max_length=3, blank=True, null=True)
Hervé  MENAGER's avatar
Hervé MENAGER committed
922
923
    nb_copy_compounds = models.IntegerField(
        'Number of copies for the compound')
Hervé  MENAGER's avatar
Hervé MENAGER committed
924
925

    class Meta:
926
        unique_together = (('ppi', 'compound', 'activation_mode', 'ligand_id'),)
Hervé  MENAGER's avatar
Hervé MENAGER committed
927
928

    def get_complexes(self):
929
930
931
932
        """
        get the complexes involved in the compound action
        which are always the bound complexes
        """
933
        return self.ppi.get_ppi_bound_complexes()
Hervé  MENAGER's avatar
Hervé MENAGER committed
934

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

Bryan  BRANCOTTE's avatar
Bryan BRANCOTTE committed
938

939
class RefCompoundBiblio(models.Model):
Hervé  MENAGER's avatar
Hervé MENAGER committed
940
941
942
    """
    Compound-Bibliographic reference association
    """
943
944
    compound = models.ForeignKey(Compound, models.CASCADE)
    bibliography = models.ForeignKey(Bibliography, models.CASCADE)
Hervé  MENAGER's avatar
Hervé MENAGER committed
945
946
    compound_name = models.CharField(
        'Compound name in the publication', max_length=50)
Hervé  MENAGER's avatar
Hervé MENAGER committed
947
948

    class Meta:
949
        unique_together = (('compound', 'bibliography'),)
950

Bryan  BRANCOTTE's avatar
Bryan BRANCOTTE committed
951