added checking on parser Status check: if !='OK' print err message and skip the count...
[htsworkflow.git] / htswfrontend / htswfrontend / fctracker / models.py
1 from django.db import models
2 from htswfrontend import settings
3 from htswfrontend.htsw_reports.libinfopar import *
4
5 class Primer(models.Model):
6   primer_name = models.CharField(max_length=100, db_index=True)
7   primer_seq = models.CharField(max_length=50, blank=True, null=True)
8   notes = models.TextField(blank=True)
9   def __str__(self):
10     return '%s' % (self.primer_name)
11   class Meta:
12     ordering = ["primer_name"]
13   class Admin:
14       list_display = ('primer_name','primer_seq','notes')
15       fields = (
16         (None, {
17             'fields': (('primer_name'),('primer_seq'),('notes'))
18         }),
19        )
20
21 class Antibody(models.Model):
22   antigene = models.CharField(max_length=500, db_index=True)
23   # New field Aug/20/08                                                                                                                                                            
24   # SQL to add column: alter table fctracker_antibody add column "nickname" varchar(20) NULL;
25   nickname = models.CharField(max_length=20,blank=True,null=True, db_index=True,verbose_name = 'Short Name')
26   catalog = models.CharField(max_length=50, unique=True, db_index=True)
27   antibodies = models.CharField(max_length=500, db_index=True)
28   source = models.CharField(max_length=500, blank=True, db_index=True)
29   biology = models.TextField(blank=True)
30   notes = models.TextField(blank=True)
31   def __str__(self):
32     return '%s - %s (%s)' % (self.antigene, self.antibodies, self.catalog)
33   class Meta:
34     verbose_name_plural = "antibodies"
35     ordering = ["antigene"]
36   class Admin:
37       list_display = ('antigene','nickname','antibodies','catalog','source','biology','notes')
38       list_filter = ('antibodies','source')
39       fields = (
40         (None, {
41             'fields': (('antigene','nickname','antibodies'),('catalog','source'),('biology'),('notes'))
42         }),
43        )
44
45 class Cellline(models.Model):
46   cellline_name = models.CharField(max_length=100, unique=True, db_index=True)
47   nickname = models.CharField(max_length=20,blank=True,null=True, db_index=True,verbose_name = 'Short Name')
48   notes = models.TextField(blank=True)
49   def __str__(self):
50     return '%s' % (self.cellline_name)
51
52   class Meta:
53     ordering = ["cellline_name"]
54
55   class Admin:
56       list_display = ('cellline_name','nickname','notes')
57       fields = (
58         (None, {
59             'fields': (('cellline_name','nickname'),('notes'),)
60         }),
61        )
62
63 class Condition(models.Model):
64   condition_name = models.CharField(max_length=2000, unique=True, db_index=True)
65   nickname = models.CharField(max_length=20,blank=True,null=True, db_index=True,verbose_name = 'Short Name')
66   notes = models.TextField(blank=True)
67   def __str__(self):
68     return '%s' % (self.condition_name)
69
70   class Meta:
71     ordering = ["condition_name"]
72
73   class Admin:
74       list_display = ('condition_name','nickname','notes')
75       fields = (
76         (None, {
77             'fields': (('condition_name','nickname'),('notes'),)
78         }),
79        )
80
81 class Species(models.Model):
82   scientific_name = models.CharField(max_length=256, unique=False, db_index=True, core=True)
83   common_name = models.CharField(max_length=256, blank=True)
84   use_genome_build = models.CharField(max_length=100, blank=False, null=False)
85
86   def __str__(self):
87     return '%s (%s)|%s' % (self.scientific_name, self.common_name, self.use_genome_build)
88   
89   class Meta:
90     verbose_name_plural = "species"
91     ordering = ["scientific_name"]
92   
93   class Admin:
94       fields = (
95         (None, {
96             'fields': (('scientific_name', 'common_name'), ('use_genome_build'))
97         }),
98       )
99
100 class Affiliation(models.Model):
101   name = models.CharField(max_length=256, db_index=True, core=True,verbose_name='Group Name')
102   contact = models.CharField(max_length=256, null=True, blank=True,verbose_name='Contact Name')  
103   email = models.EmailField(null=True,blank=True)
104   
105   def __str__(self):
106     str = self.name
107     if self.contact != '':
108       str += ' ('+self.contact+')' 
109     return str
110
111   class Meta:
112     ordering = ["name","contact"]
113     unique_together = (("name", "contact"),)
114
115   class Admin:
116       list_display = ('name','contact','email')
117       fields = (
118         (None, {
119             'fields': (('name','contact','email'))
120         }),
121       )
122
123 class Tag(models.Model):
124   tag_name = models.CharField(max_length=100, db_index=True,core=True,blank=False,null=False)
125   TAG_CONTEXT = (
126       #('Antibody','Antibody'),
127       #('Cellline', 'Cellline'),
128       #('Condition', 'Condition'),
129       ('Library', 'Library'),
130       ('ANY','ANY'),
131     )
132   context = models.CharField(max_length=50, choices=TAG_CONTEXT, default='Library')
133
134   def __str__(self):
135     return '%s' % (self.tag_name)
136
137   class Meta:
138     ordering = ["context","tag_name"]
139
140   class Admin:
141       list_display = ('tag_name','context')
142       fields = (
143         (None, {
144             'fields': ('tag_name','context')
145         }),
146       )
147
148 class Library(models.Model):
149   library_id = models.CharField(max_length=30, unique=True, db_index=True, core=True)
150   library_name = models.CharField(max_length=100, unique=True, core=True)
151   library_species = models.ForeignKey(Species, core=True)
152   cell_line = models.ForeignKey(Cellline,core=True)
153   condition = models.ForeignKey(Condition,core=True)
154   antibody = models.ForeignKey(Antibody,blank=True,null=True,core=True)
155   # New field Aug/25/08. SQL: alter table fctracker_library add column "lib_affiliation" varchar(256)  NULL;
156   affiliations = models.ManyToManyField(Affiliation,related_name='library_affiliations',null=True,filter_interface=models.HORIZONTAL)
157   # New field Nov/14/08
158   tags = models.ManyToManyField(Tag,related_name='library_tags',blank=True,null=True,filter_interface=models.HORIZONTAL)
159   # New field Aug/19/08
160   # SQL to add column: alter table fctracker_library add column "replicate" smallint unsigned NULL;
161   REPLICATE_NUM = ((1,1),(2,2),(3,3),(4,4))
162   replicate =  models.PositiveSmallIntegerField(choices=REPLICATE_NUM,default=1) 
163
164   EXPERIMENT_TYPES = (
165       ('INPUT_RXLCh','INPUT_RXLCh'),
166       ('ChIP-seq', 'ChIP-seq'),
167       ('Sheared', 'Sheared'),
168       ('RNA-seq', 'RNA-seq'),
169       ('Methyl-seq', 'Methyl-seq'),
170       ('DIP-seq', 'DIP-seq'),
171     ) 
172   experiment_type = models.CharField(max_length=50, choices=EXPERIMENT_TYPES, default='ChIP-seq')
173
174   creation_date = models.DateField(blank=True, null=True)
175   made_for = models.CharField(max_length=50, blank=True,verbose_name = 'ChIP/DNA/RNA Made By')
176   made_by = models.CharField(max_length=50, blank=True,verbose_name = 'Library Made By')
177   
178   PROTOCOL_END_POINTS = (
179       ('Completed','Completed'),
180       ('?', 'Unknown'),
181       ('Sample', 'Raw sample'),
182       ('Progress', 'In progress'),
183       ('1A', 'Ligation, then gel'),
184       ('PCR', 'Ligation, then PCR'),
185       ('1Ab', 'Ligation, PCR, then gel'),
186       ('1Aa', 'Ligation, gel, then PCR'),
187       ('2A', 'Ligation, PCR, gel, PCR'),
188     )
189   stopping_point = models.CharField(max_length=50, choices=PROTOCOL_END_POINTS, default='Completed')
190   amplified_from_sample = models.ForeignKey('self', blank=True, null=True)
191   
192   undiluted_concentration = models.DecimalField("Template concentr. (ng/ul)",max_digits=5, decimal_places=2, blank=True, null=True)
193   ten_nM_dilution = models.BooleanField()
194   successful_pM = models.DecimalField(max_digits=5, decimal_places=2,blank=True, null=True)
195   avg_lib_size = models.IntegerField(default=225, blank=True, null=True)
196   notes = models.TextField(blank=True)
197   
198   def __str__(self):
199     return '%s: %s' % (self.library_id, self.library_name)
200   
201   class Meta:
202     verbose_name_plural = "libraries"
203     ordering = ["-creation_date"] #["-library_id"]
204   
205   def antibody_name(self):
206     str ='<a target=_self href="/admin/fctracker/antibody/'+self.antibody.id.__str__()+'/" title="'+self.antibody.__str__()+'">'+self.antibody.nickname+'</a>'
207     return str
208   antibody_name.allow_tags = True
209
210   def org(self):
211     return self.library_species.common_name
212
213   def cond(self):
214     return self.condition.nickname
215
216   def affiliation(self):
217     affs = self.affiliations.all().order_by('name')
218     tstr = ''
219     ar = []
220     for t in affs:
221         ar.append(t.__str__())
222     return '%s' % (", ".join(ar))
223
224   def libtags(self):
225     affs = self.tags.all().order_by('tag_name')
226     tstr = ''
227     ar = []
228     for t in affs:
229         ar.append(t.__str__())
230     return '%s' % (", ".join(ar))
231
232   def DataRun(self):
233     str ='<a target=_self href="/admin/exp_track/datarun/?q='+self.library_id+'" title="Check All Data Runs for This Specific Library ..." ">DataRuns ..</a>'
234     return str
235   DataRun.allow_tags = True
236
237   def aligned_m_reads(self):
238     return getLibReads(self.library_id)
239
240   def aligned_reads(self):
241     res = getLibReads(self.library_id)
242
243     # Check data sanlty
244     if res[2] != 'OK':
245       return '<div style="border:solid red 2px">'+res[2]+'</div>'
246
247     rc = "%1.2f" % (res[1]/1000000.0)
248     # Color Scheme: green is more than 12M, blue is more than 5M, orange is more than 3M and red is less. For RNAseq, all those thresholds should be doubled
249     if res[0] > 0:
250       bgcolor = '#ff3300'  # Red, the color for minimum read count
251       rc_thr = [12000000,5000000,3000000]
252       if self.experiment_type == 'RNA-seq':
253         rc_thr = [20000000,10000000,6000000]
254
255       if res[1] > rc_thr[0]:
256         bgcolor = '#66ff66'  # Green
257       else:
258         if res[1] > rc_thr[1]:
259           bgcolor ='#00ccff'  # Blue
260         else:
261            if res[1] > rc_thr[2]: 
262              bgcolor ='#ffcc33'  # Orange
263       tstr = '<div style="background-color:'+bgcolor+';color:black">'
264       tstr += res[0].__str__()+' Lanes, '+rc+' M'
265       tstr += '</div>'
266     else: tstr = 'not processed yet' 
267     return tstr
268   aligned_reads.allow_tags = True
269
270   class Admin:
271     date_hierarchy = "creation_date"
272     save_as = True
273     save_on_top = True
274     ##search_fields = ['library_id','library_name','affiliations__name','affiliations__contact','made_by','made_for','antibody__antigene','antibody__catalog','antibody__antibodies','antibody__source','cell_line__cellline_name','library_species__scientific_name','library_species__common_name','library_species__use_genome_build']
275     search_fields = ['library_id','library_name','cell_line__cellline_name','library_species__scientific_name','library_species__common_name','library_species__use_genome_build']
276     list_display = ('affiliation','library_id','aligned_reads','DataRun','library_name','experiment_type','org','replicate','antibody_name','cell_line','cond','libtags','made_by','creation_date')
277     list_display_links = ('library_id', 'library_name')
278     list_filter = ('experiment_type','affiliations','library_species','tags','made_for', 'made_by','replicate','antibody','cell_line','condition')
279     fields = (
280         (None, {
281             'fields': (('replicate','library_id','library_name'),('library_species'),('experiment_type'),('cell_line','condition','antibody'),)
282         }),
283         ('Creation Information:', {
284             'fields' : (('made_for', 'made_by', 'creation_date'), ('stopping_point', 'amplified_from_sample'), ('avg_lib_size','undiluted_concentration', 'ten_nM_dilution', 'successful_pM'), 'notes',)
285         }),
286         ('Library/Project Affiliation:', {
287             'fields' : (('affiliations'),('tags'),)
288         }),
289         )