Initial port to python3
[htsworkflow.git] / htsworkflow / frontend / reports / models.py
1 from django.db import models
2 from django.db.models import Q
3 from django.core.exceptions import ObjectDoesNotExist
4 from datetime import datetime
5 from htsworkflow.frontend.samples.models import * 
6 from htsworkflow.frontend.analysis.models import *
7 from htsworkflow.frontend.experiments.models import *
8 from string import *
9 from htsworkflow.frontend.reports.utils import *
10 import re
11 ##from p1 import LibInfo
12 from .libinfopar import *
13
14 ## This is a table based REPORT generator. The goal is to display a Progress Report for all the ENCODE projects, based on Study Name (e.g. NRSF, FOXP2, Methy-Seq on .. etc).
15   
16 class ProgressReport(models.Model):
17   st_sbj = models.ForeignKey(Project,limit_choices_to = Q(project_name__startswith='ENCODE '),related_name='project',db_index=True,verbose_name="Studied Subject")
18   interactome_complete = models.BooleanField(default=False)
19
20   def Study(self):
21     str = self.st_sbj.__str__()
22     str += '<br/><br/>'
23     str += '<a title="open Project record" href="/admin/analys_track/project/'+self.st_sbj.id.__str__()+'/" target=_self style="font-size:85%">Edit Project</a>'
24     return str  
25   Study.allow_tags = True
26
27   def submit_to_DCC(self):
28     varText = ''
29     if self.note_about_DCC:
30       varText += '<br/><u>Note:</u><br/>'+self.note_about_DCC
31     return '%s<br/>%s' % (self.submitted_to_DCC,varText)
32   submit_to_DCC.allow_tags = True
33
34   def submit_to_NCBI(self):
35     varText = ''
36     if self.note_about_NCBI:
37       varText += '<br/><u>Note:</u><br/>'+self.note_about_NCBI 
38     return '%s<br/>%s' % (self.submitted_to_NCBI,varText)
39   submit_to_NCBI.allow_tags = True
40
41   ## -- Utility functions <-- This method was transfered to untils.py
42
43   ## --- LIBARAY PREPARATION SECTION 
44   def getLibIds(self):
45     ptasks = self.st_sbj.tasks.distinct()
46     arLibs = [] 
47     for t in ptasks:
48       if t.subject1 is not None:
49         arLibs.append(t.subject1.library_id)
50       if t.subject2 is not None:
51         arLibs.append(t.subject2.library_id)
52     arLibs = unique(arLibs)
53     return arLibs #.sort()
54
55   def getFCInfo(self,libid):   ## This is the haviest function 
56     arFCLanes = []
57     ##Test return arFCLanes
58     # can't get this to work: FC_L1 = FlowCell.objects.filter(lane_5_library__exact=libid)
59     allFCs = FlowCell.objects.all()
60     for f in allFCs:
61       entry = ''
62       lanes = []
63       #found = False
64 #      for i in range(1,9):
65 #        if eval('f.lane_'+i.__str__()+'_library.library_id==libid'):
66 #          lanes.append(i.__str__())
67 #          found = True
68
69 # maybe a bit faster this way:
70       if f.lane_1_library.library_id==libid:
71           lanes.append('1')
72           #found = True
73       if f.lane_2_library.library_id==libid:
74           lanes.append('2')
75           #found = True
76       if f.lane_3_library.library_id==libid:
77           lanes.append('3')
78           #found = True
79       if f.lane_4_library.library_id==libid:
80           lanes.append('4')
81           #found = True
82       if f.lane_5_library.library_id==libid:
83           lanes.append('5')
84           #found = True
85       if f.lane_6_library.library_id==libid:
86           lanes.append('6')
87           #found = True
88       if f.lane_7_library.library_id==libid:
89           lanes.append('7')
90           #found = True
91       if f.lane_8_library.library_id==libid:
92           lanes.append('8')
93           #found = True
94
95
96       #if found:
97       if len(lanes)>0:
98         rundate = re.sub(pattern="\s.*$",repl="",string=f.run_date.__str__())
99         entry = '<b>'+f.flowcell_id + '</b> Lanes No.: '+','.join(lanes)+' ('+rundate+')' 
100         arFCLanes.append(entry)    
101     if len(arFCLanes)==0:
102       arFCLanes.append('<font color=red>Flowcell not found.</font>')
103     return arFCLanes
104
105   def ab_batch(self):
106     ##  To have the Company's lot number, apearing on the (source) tube, we need to add new Field in Library. 
107     arlibs = self.getLibIds()
108     tstr = '<ul>' ##<u><b>Ab</b> from '+len(arlibs).__str__()+' libs</u>: '
109     arRows = []
110     for l in arlibs:
111       try:
112         rec = Library.objects.get(library_id=l,antibody__isnull=False)
113         arRows.append('<li>'+rec.antibody.antibodies+' for <b>'+rec.antibody.antigene+'</b> (src:'+rec.antibody.source+', cat:'+rec.antibody.catalog+')</li>')
114       except ObjectDoesNotExist:
115         tstr += ""
116     tstr += "".join(unique(arRows))+'</ul>'
117     return tstr
118   ab_batch.allow_tags = True
119
120   def cell_line(self):                                                                                           
121     arlibs = self.getLibIds()
122     tstr = '<ul>'
123     arRows = []                                                                                                                                     
124     for l in arlibs:
125       try:
126         rec = Library.objects.get(library_id=l)
127         arRows.append('<li><b>'+rec.cell_line.cellline_name+'</b> ('+rec.condition.condition_name+')</li>')
128       except ObjectDoesNotExist:
129         tstr += ""                                                                                                                               
130     tstr += "".join(unique(arRows))+'</ul>'
131     return tstr
132   cell_line.allow_tags = True
133
134   def cell_harvest_batch(self): # <- data now displayed in "cell_line"
135     ## name + date  
136     arlibs = self.getLibIds()
137     tstr = '<ul>'
138     arRows = []
139     for l in arlibs:
140       try:
141         rec = Library.objects.get(library_id=l)
142         arRows.append('<li><b>'+rec.condition.condition_name+'</b></li>')
143       except ObjectDoesNotExist:
144         tstr += ""
145     tstr += "".join(unique(arRows))+'</ul>'
146     return tstr
147   cell_harvest_batch.allow_tags = True
148
149   def ChIP_made(self):
150     ## person + date                                                                                                                                                                                                             
151     return '...'
152
153   def library(self):
154     ## Lib Id + Date + Person
155     tstr = '<script>'
156     tstr += 'function togit(eid){'
157     tstr += 'f=document.getElementById(eid);'
158     tstr += 'if(f.style.display==\'none\'){'
159     tstr += 'f.style.display=\'block\';'
160     tstr += '}else{'
161     tstr += 'f.style.display=\'none\';'
162     tstr += '}'
163     tstr += '}'
164     tstr += '</script>'
165     arlibs = self.getLibIds() ##.sort()
166     arlibs = arlibs
167     tstr +='<a href=# onClick="togit(\'libInfo'+self.st_sbj.project_name+'\')">view /hide</a>'
168     tstr += '<div id="libInfo'+self.st_sbj.project_name+'" style="display:block;border:solid #cccccc 1px;width:200px;height:300px;overflow:auto"><ul>'
169     arRows = []
170     for l in arlibs:
171       try:
172         rec = Library.objects.get(library_id=l)
173         arRows.append('<li><b>'+rec.library_id+'</b>: '+rec.library_name+'.<br/>Made By: '+rec.made_by+', On: '+ rec.creation_date.__str__()+'</li>')
174       except ObjectDoesNotExist:
175         tstr += ""
176     tstr += "".join(unique(arRows))+'</ul></div>'
177     return tstr
178   library.allow_tags = True
179
180
181   ## -- SEQUENCING SECTION 
182   def sequencing(self):
183     ## FCId + Lane + Date
184     arlibs = self.getLibIds()
185     tstr ='<a href=# onClick="togit(\'seqInfo'+self.st_sbj.project_name+'\')">view /hide</a>'
186     tstr += '<div id="seqInfo'+self.st_sbj.project_name+'" style="display:block;border:solid #cccccc 1px;width:200px;height:300px;overflow:auto"><ul>'    
187     for l in arlibs:
188       tstr += '<li><b>'+l+'</b>:<br/>'+(' / '.join(self.getFCInfo(l)))+'</li>'
189     tstr += '</ul></div>'
190     return tstr
191   sequencing.allow_tags = True
192   
193   def aligned_reads(self):
194     ## Mega reads/lane                                              
195     arlibs = self.getLibIds()
196     tstr = '<a href=# onClick="togit(\'readsInfo'+self.st_sbj.project_name+'\')">view /hide</a>'
197     tstr += '<div id="readsInfo'+self.st_sbj.project_name+'" style="display:block;border:solid #cccccc 1px;width:200px;height:300px;overflow:auto">'
198     tstr += '<table><tr><td>Library Id</td><td>Total Lanes</td><td>M Reads</td></tr>'
199     LanesCnt, ReadsCnt = 0, 0
200     for l in arlibs:      
201       res = getLibReads(l)
202       LanesCnt += res[0]
203       ReadsCnt += res[1]
204       rc = "%1.2f" % (res[1]/1000000.0)
205       tstr += '<tr><td><b>'+l+'</b></td><td>'+res[0].__str__()+'</td></td><td>'+rc+'</td></tr>'
206     tstr += '</table>'
207     #tstr += '<a target=_blank href="'+settings.TASKS_PROJS_SERVER+'/projects/'+self.st_sbj.id.__str__()+'">Project results page</a>'
208     tstr += '</div>'
209     myNum = (ReadsCnt/1000000.0)
210     myNum  = "%1.2f" % (myNum) 
211     tstr += '<div>Total: <b>'+LanesCnt.__str__()+'</b> lanes and <b>'+myNum+'</b> M Reads</div>'
212     tstr += '<a target=_blank href="'+settings.TASKS_PROJS_SERVER+'/projects/'+self.st_sbj.id.__str__()+'">Project results page</a>'
213     return tstr
214   aligned_reads.allow_tags = True
215
216   def peak_calling(self):
217     # date + what etc..
218     return 'coming up ..'
219
220   QPCR = models.CharField(max_length=500,blank=True,null=True)    
221   submitted_to_DCC = models.DateTimeField(blank=True,null=True)
222   submitted_to_NCBI = models.DateTimeField(blank=True,null=True)
223   note_about_DCC =  models.TextField(blank=True)
224   note_about_NCBI = models.TextField(blank=True)
225   
226   def __str__(self):
227       return '"%s" - %s' % (self.st_sbj,self.interactome_complete)
228
229   class Meta:
230     #verbose_name_plural = "Reports"
231     ordering = ["id"]
232
233   class Admin:
234     list_display = ('Study','ab_batch','cell_line','library','sequencing','aligned_reads','QPCR','submit_to_DCC','submit_to_NCBI','interactome_complete')
235     ## list_filter = ('interactome_complete')
236     
237
238 #############################################