models.py 10.2 KB
Newer Older
1 2 3 4 5 6 7 8 9
## Copyright 2013 Mathieu Courcelles
## Mike Tyers's lab / IRIC / Universite de Montreal 

"""
This is the data model module for the CLMSpipeline_app.
"""


# Import standard librariesdjang
10
#import os.path
11 12

# Import Django related libraries
13 14
from django.contrib.contenttypes.models import ContentType
from django.core.urlresolvers import reverse
15
from django.db import models
16
from django.db.models.signals import post_save, pre_save, pre_delete
17
from django.dispatch import receiver
18 19

# Import project libraries
20

21 22 23 24 25 26 27



## File upload

def upload_path_handler(instance, filename):
        
28
    return "dataset/{id}-{filename}".format(id=instance.pk, filename=filename)
29 30 31



32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48
class AdminURLMixin(object):
    """
    Generate admin url for objet in this model
    Code from: http://timmyomahony.com/blog/2012/12/12/reversing-admin-urls-and-creating-admin-links-you-models/
    """
    
    
    def get_admin_url(self):
        content_type = ContentType \
            .objects \
            .get_for_model(self.__class__)
        return reverse("admin:%s_%s_change" % (
            content_type.app_label,
            content_type.model),
            args=(self.id,))


49 50

# Create your models here.
51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66

class CrossLinker(models.Model):
    """
    This class holds the name of all the cross-linkers.
    """
    
    name = models.CharField(max_length=100, unique=True)

    def __unicode__(self):
        return self.name

    class Meta:
        ordering = ['name']



67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89
class FastaDB(models.Model):
    """
    This class holds the name of all the FASTA database.
    """
    
    name = models.CharField(max_length=200, unique=True)

    def __unicode__(self):
        return self.name

    class Meta:
        ordering = ['name']



class Instrument(models.Model):
    """
    This class holds the name of all the MS instruments.
    """
    
    name = models.CharField(max_length=100, unique=True)

    def __unicode__(self):
90
        return self.name
91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109

    class Meta:
        ordering = ['name']


class searchAlgorithm(models.Model):
    """
    This class holds the name of all the search algorithms.
    """
    
    name = models.CharField(max_length=100, unique=True)

    def __unicode__(self):
        return str(self.name)

    class Meta:
        ordering = ['name']


110 111

class Dataset(models.Model, AdminURLMixin):
112 113 114 115 116 117
    """
    This class holds dataset information of cross-linked peptides.
    """
    
    creation_date = models.DateTimeField(auto_now_add=True)
    
118 119
    name = models.CharField(max_length=100)
    
120 121 122 123 124 125 126 127
    prefix = models.CharField(max_length=25, 
                              help_text='Short name that will be appeded in comparison.')
    
    file = models.FileField(upload_to=upload_path_handler,
                            help_text='pLink note: Merge the files ending with xlink_qry.proteins.txt from 1.sample\\search folder.')
    
    extra_file = models.FileField(upload_to=upload_path_handler, blank=True,
                            help_text='pLink only: select pLink_combine.spectra.xls from 2.report\\sample1 folder. This file is used to filter FDR filtered hits.')
128
    
129
    cross_linker = models.ForeignKey(CrossLinker)
130 131 132 133 134
    
    instrument_name = models.ForeignKey(Instrument)
    
    fasta_db = models.ForeignKey(FastaDB)
    
135
    search_algorithm = models.ForeignKey(searchAlgorithm)
136 137 138

    description = models.TextField('Detailed description', blank=True)
    
139 140
    parsing_status = models.BooleanField(default=False)
    
141
    parsing_log = models.CharField(max_length=1000, blank=True, null=True)
142
    
143 144 145
    
    def formated_url(self):
        return '<a href="%s">%s</a>' % (self.get_admin_url(), self.pk)
146 147 148 149
    
    def __unicode__(self):
        return str(self.pk)
    
150
  
151 152

    class Meta:
153
        ordering = ['-creation_date']
154 155
        
        
156 157 158 159 160
        
        
# Code for dataset file upload
# Code from http://stackoverflow.com/questions/9968532/django-admin-file-upload-with-current-model-id
_UNSAVED_FILEFIELD = 'unsaved_filefield'
161
_UNSAVED_FILEFIELD_EXTRA = 'unsaved_filefield_extra'
162 163 164 165 166 167

@receiver(pre_save, sender=Dataset)
def skip_saving_file(sender, instance, **kwargs):
    if not instance.pk and not hasattr(instance, _UNSAVED_FILEFIELD):
        setattr(instance, _UNSAVED_FILEFIELD, instance.file)
        instance.file = None
168 169 170 171
    
    if not instance.pk and not hasattr(instance, _UNSAVED_FILEFIELD_EXTRA) and instance.extra_file:
        setattr(instance, _UNSAVED_FILEFIELD_EXTRA, instance.extra_file)
        instance.extra_file = None
172 173 174
        
    
    
175 176 177

@receiver(post_save, sender=Dataset)
def save_file(sender, instance, created, **kwargs):
178
    
179 180
    if created and hasattr(instance, _UNSAVED_FILEFIELD):
        instance.file = getattr(instance, _UNSAVED_FILEFIELD)
181 182
        if created and hasattr(instance, _UNSAVED_FILEFIELD_EXTRA):
            instance.extra_file = getattr(instance, _UNSAVED_FILEFIELD_EXTRA)
183 184
        instance.save()
        
185
        
186 187 188 189 190
                
        # delete it if you feel uncomfortable...
        # instance.__dict__.pop(_UNSAVED_FILEFIELD)


191 192 193 194 195 196 197 198 199 200
@receiver(pre_delete, sender=Dataset)
def remove_CLPeptide(sender, instance, **kwargs):
    
    # Remove CLpeptides not linked to any dataset after deletion
    for clpep in instance.clpeptide_set.all():
        if clpep.dataset.count() == 1:
            clpep.delete()
                    
            

201 202 203 204

        
        
class CLPeptide(models.Model):
205 206 207 208 209 210 211 212
    """
    This class holds details of cross-linked peptides.
    """
    
    dataset = models.ManyToManyField(Dataset)
    
    run_name = models.CharField(max_length=1000)
    
213
    scan_number = models.IntegerField('Scan #')
214 215 216
    
    precursor_mz = models.FloatField()
    
217
    precursor_charge = models.CharField('z', max_length=5)
218 219 220 221 222 223 224 225 226
    
    precursor_intensity = models.FloatField()
    
    rank = models.IntegerField()
    
    match_score = models.FloatField()
    
    spectrum_intensity_coverage = models.FloatField()
    
227
    total_fragment_matches = models.IntegerField('# Fragments')
228 229 230 231 232 233 234
    
    delta = models.FloatField()
    
    error = models.FloatField()
    
    peptide1 = models.CharField(max_length=100)
    
235
    peptide_wo_mod1 = models.CharField(max_length=150)
236 237 238
    
    display_protein1 = models.CharField(max_length=250)
    
239
    peptide_position1 = models.IntegerField('Pep. Pos. 1')
240
    
241
    pep1_link_pos = models.IntegerField()
242 243 244
    
    peptide2 = models.CharField(max_length=100)
    
245
    peptide_wo_mod2 = models.CharField(max_length=150)
246 247 248
    
    display_protein2 = models.CharField(max_length=250)
    
249
    peptide_position2 = models.IntegerField('Pep. Pos. 2')
250
    
251
    pep2_link_pos = models.IntegerField()
252 253 254 255 256 257 258 259 260
    
    autovalidated = models.BooleanField()
    
    validated = models.CharField(max_length=50)
    
    rejected = models.BooleanField()
    
    notes = models.CharField(max_length=100)
    
261 262 263 264
    LINK_TYPE_CHOICES = (
                            (1, 'Inter-protein'),
                            (2, 'Intra-protein'),
                            (3, 'Intra-peptide'),
265
                            (4, 'Dead-end'),
266
                         )
267
    
268
    link_type = models.IntegerField(choices=LINK_TYPE_CHOICES)
269
    
270 271
    cross_link = models.BooleanField()
    
272 273 274 275 276 277 278
    not_decoy = models.BooleanField()
    
    
    
    class Meta:
        ordering = ['-match_score']
    
279
    
280 281 282 283 284
    def fixAutovalidated(self):
        if self.autovalidated == 'true':
            self.autovalidated = True
        else:
            self.autovalidated = False
285 286 287 288 289 290 291 292
    
    
    def guessLinkType(self):
        """
        This method guess the type of peptide cross-link since Xi is not
        providing this information.
        """
        
293
        self.link_type = 1
294
        self.cross_link = False
295 296 297
        
        if self.peptide_wo_mod1 == self.peptide_wo_mod2:
            self.link_type = 1
298
            self.cross_link = True
299 300 301
            
        elif self.display_protein1 == self.display_protein2:
            self.link_type = 2
302
            self.cross_link = True
303 304 305 306 307 308
        
        else:
        
            if self.pep2_link_pos == -1:
                self.link_type = 4
                
309
            elif self.pep2_link_pos > -1 and self.peptide_wo_mod2 == '-':
310
                self.link_type = 3
311

312 313 314 315 316 317 318 319 320 321 322
                
                
    def isDecoy(self):
        
        if self.display_protein1 == 'DECOY' or self.display_protein2 == 'DECOY':
            self.not_decoy = False
        else:
            self.not_decoy = True
            
            
    
Mathieu Courcelles's avatar
.  
Mathieu Courcelles committed
323 324 325 326 327 328 329 330 331 332
class CLPeptideFilter(models.Model):
    """
    This class holds pre-defined filters for cross-linked peptides.
    """
    
    creation_date = models.DateTimeField(auto_now_add=True)
    
    name = models.CharField(max_length=100)
    
    description = models.TextField('Detailed description', blank=True)
333 334


Mathieu Courcelles's avatar
.  
Mathieu Courcelles committed
335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372

class CLPeptideFilterParam(models.Model):
    
    clpeptidefilter = models.ForeignKey(CLPeptideFilter)
    
    METHOD_CHOICES = (
                            ('Exclude', 'Exclude'),
                            ('Filter', 'Filter'),
                        
                         )
    
    method = models.CharField(max_length = 20, choices = METHOD_CHOICES)
    
    field = models.CharField(max_length = 100, choices = [(field.name, field.name) for field in CLPeptide._meta.fields])
    
    LOOKUP_CHOICES = (
                            ('Exact match', 'exact'),
                            ('Exact match case insentive', 'iexact'),
                            ('Contains', 'contains'),
                            ('Contains case insentive', 'contains'),
                            ('Greater than', 'gt'),
                            ('Greater than or equal to', 'gte'),
                            ('Less than', 'lt'),
                            ('Less than or equal to', 'lte'),
                            ('Starts-with', 'startswith'),
                            ('Starts-with case insensitive', 'istartswith'),
                            ('Ends-with', 'endswith'),
                            ('Ends-with case insensitive', 'iendswith'),
                            ('Is null', 'isnull'),
                            ('Regular expression match', 'regex'),
                            ('Regular expression match case insensitive', 'iregex'),
                            
                         )
    
    field_lookup = models.CharField(max_length=50, choices=LOOKUP_CHOICES)
    
    value = models.CharField(max_length = 50)