Initial port to python3
[htsworkflow.git] / htsworkflow / frontend / reports / reports.py
1 from htsworkflow.frontend.experiments.models import *
2 from django.http import HttpResponse
3 from django.core.exceptions import ObjectDoesNotExist
4 from django.shortcuts import render_to_response, get_object_or_404
5
6 def getBgColor(reads_cnt,exp_type):
7   # 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 are ~ double
8   bgcolor = '#ff3300'  # Red is the color for minimum read counts                                                                                                                            
9   rc_thr = [12000000,5000000,3000000] # Default for ChIP-Seq and Methyl-Seq
10   if exp_type == 'RNA-seq':
11     rc_thr = [20000000,10000000,6000000]
12
13   if reads_cnt > rc_thr[0]:
14     bgcolor = '#66ff66'  # Green                                                                                                                                                                                                                                               
15   else:
16     if reads_cnt > rc_thr[1]:
17       bgcolor ='#00ccff'  # Blue                                                                                                                                                                                                                                               
18     else:
19        if reads_cnt > rc_thr[2]:
20          bgcolor ='#ffcc33'  # Orange                                                                                                                                                                                                                                          
21   #tstr = '<div style="background-color:'+bgcolor+';color:black">'
22   #tstr += res[0].__str__()+' Lanes, '+rc+' M Reads'
23   #tstr += '</div>'
24
25   return bgcolor
26
27 def report1(request):
28   EXP = 'ChIP-seq'
29
30   if 'aflid' in request.GET:
31     AFL_Id = request.GET['aflid']
32     try:
33       AFL = Affiliation.objects.get(id=AFL_Id).name
34       AFL_CNT = Affiliation.objects.get(id=AFL_Id).contact
35     except ObjectDoesNotExist:
36       return HttpResponse("ERROR: Affiliation Record Not Found for: '"+AFL_ID+"'")
37   else:
38     AFL = 'ENCODE_Tier1'
39     AFL_CNT = ''
40     try:
41       AFL_Id = str(Affiliation.objects.get(name=AFL).id)
42     except ObjectDoesNotExist:
43       return HttpResponse("ERROR: Affiliation Record Not Found for: '"+AFL+"'")
44   
45   TFall = Library.objects.values('antibody').order_by('antibody').distinct()
46   CLLall = Library.objects.values('cell_line').order_by('cell_line').distinct()
47
48   TFs = TFall.filter(experiment_type=EXP,affiliations__name=AFL,affiliations__contact=AFL_CNT)
49   CLLs = CLLall.filter(experiment_type=EXP,affiliations__name=AFL,affiliations__contact=AFL_CNT)
50
51   # Check Replicate numbers
52   Reps = 1
53   RepRecs = Library.objects.filter(experiment_type=EXP,affiliations__name=AFL,affiliations__contact=AFL_CNT).order_by('-replicate')
54   if len(RepRecs) > 0: Reps = RepRecs[0].replicate
55   
56   ########
57   s = []
58   s += ['<span style="margin-right:20px"><a target=_self href="/admin" target=_self">Main Page</a></span>']
59   ##s += '<span style="margin-right:20px">Max Replicates: '+MaxRep.replicate.__str__()+'</span>'
60   s += ['<span>Select another <b>'+EXP+'</b> Report:</span>  <select>']
61   for af in Affiliation.objects.distinct():
62     option = []
63     option += ['<option value='+str(af.id)]
64     if AFL_Id == str(af.id):
65       option += [' selected']
66     option += [' onclick="window.location=\'/reports/report?aflid='+af.id.__str__()+'\'; return false;">'+str(af.name)+' '+str(af.contact)+'</option>']
67   s += option
68   s += ['</select>']
69
70   s += ['<span style="margin-left:20px;padding:1px;border:solid #cccccc 1px">color scheme: <span style="margin-left:5px;background-color:#66ff66"> > 12 M</span><span style="margin-left:5px;background-color:#00ccff"> >  5 M</span><span style="margin-left:5px;background-color:#ffcc33"> > 3 M</span><span style="margin-left:5px;background-color:#ff3300"> < 3 M</span></span>']
71
72   s += ['<span style="margin-left:20px">']
73   s += ['<u>Switch to:</u> '+AFL+' '+AFL_CNT+' <a target=_self href="/reports/report_RM?exp=RNA-seq&aflid='+AFL_Id+'"><b>RNA-Seq</b> Report</a>']
74   s += ['  | ']
75   s += ['<a target=_self href="/reports/report_RM?exp=Methyl-seq&aflid='+AFL_Id+'"><b>Methyl-Seq</b> Report</a>']
76
77   bgc = '#ffffff' 
78   pbgc = '#f7f7f7'
79   s += ['<br/><br/><table border=1 cellspacing="2">']
80   s += ['<tr><th style="text-align:right">PROJECT</th><th colspan='+str(Reps*len(CLLs))+' style="text-align:center">'+AFL+' '+AFL_CNT+' <span style="font-size:140%">'+EXP+'</span></th></tr>']
81   s += ['<tr><th style="text-align:right">CELL LINE</th>']
82   for H in CLLs: 
83     s += ['<th colspan='+Reps.__str__()+' style="text-align:center;background-color:'+bgc+'">'+Cellline.objects.get(id=H['cell_line']).cellline_name+'</th>']
84     tbgc = bgc
85     bgc = pbgc
86     pbgc = tbgc 
87   s += ['</tr><tr><th style="text-align:left">TF</th>']
88   bgc = '#ffffff'
89   pbgc = '#f7f7f7'
90   for H in CLLs:
91     for r in range(1,Reps+1):
92       s += ['<th style="text-align:center;background-color:'+bgc+'">Rep. '+r.__str__()+'</th>']
93     tbgc = bgc
94     bgc = pbgc
95     pbgc = tbgc
96   s += ['</tr>']
97   s += ['<tr><td align=right><a title="View Libraries Records" target=_self href=/admin/fctracker/library/?affiliations__id__exact='+AFL_Id+'&experiment_type__exact=INPUT_RXLCh>Total Chromatin</a></td>']
98   bgc = '#ffffff'
99   pbgc = '#f7f7f7'
100   for H in CLLs:
101     for r in range(1,Reps+1):
102       repReads = Library.objects.filter(experiment_type='INPUT_RXLCh',affiliations__name=AFL,affiliations__contact=AFL_CNT,cell_line=H['cell_line'].__str__(),replicate=r)
103       s += ["<td align=center style='background-color:"+bgc+"'>"]
104       if len(repReads) == 0:
105         s += ['No Libraries']
106       else:
107         cnt = 0
108         for R1 in repReads:
109           rres = R1.aligned_m_reads()
110           # Check data sanlty                                                                                                                                           
111           if rres[2] != 'OK':
112             s += ['<div style="border:solid red 2px">'+rres[2]]
113           else:
114             cnt = rres[1]
115             if cnt > 0:
116               s += ["<div style='background-color:"+getBgColor(cnt,EXP)+";font-size:140%'>"]
117               s += ["%1.2f" % (cnt/1000000.0)+" M"]
118             else:
119               s += ["<div style='background-color:#ff3300;width:100%;font-size:140%'>0 Reads"]
120           s += ["<div style='font-size:70%'>"+R1.library_id+", "+R1.condition.nickname+"</div>"]
121           s += ["</div>"]
122       s += ['</td>']
123     tbgc = bgc
124     bgc = pbgc
125     pbgc = tbgc
126   s += ['</tr>' ]
127
128   for T in TFs:
129     s += ['<tr>']
130     try:
131       if T['antibody']:
132         s += ['<td><a title="View Libraries Records" target=_self href=/admin/fctracker/library/?affiliations__id__exact='+AFL_Id+'&antibody__id__exact='+T['antibody'].__str__()+'>'+Antibody.objects.get(id=T['antibody']).nickname+'</a></td>']
133     except Antibody.DoesNotExist:
134       s += ['<td>n/a</td>']
135
136     bgc = '#ffffff'
137     pbgc = '#f7f7f7'
138     for H in CLLs:
139       for r in range(1,Reps+1):
140         repReads = Library.objects.filter(experiment_type=EXP,affiliations__name=AFL,affiliations__contact=AFL_CNT,cell_line=H['cell_line'].__str__(),antibody=T['antibody'].__str__(),replicate=r)
141         s += ["<td align=center style='background-color:"+bgc+"'>"]
142         if len(repReads) == 0: 
143           s += ['No Libraries']
144         else:
145           cnt = 0
146           for R1 in repReads:
147             rres = R1.aligned_m_reads()
148             # Check data sanlty
149             if rres[2] != 'OK':
150               s += ['<div style="border:solid red 2px">'+rres[2]]
151             else:
152               cnt = rres[1]
153               if cnt > 0:
154                 s += ["<div style='background-color:"+getBgColor(cnt,EXP)+";font-size:140%'>"]
155                 s += "%1.2f" % (cnt/1000000.0)+" M"
156               else:
157                 s += ["<div style='background-color:#ff3300;width:100%;font-size:140%'>0 Reads"]
158             s += ["<div style='font-size:70%'>"+R1.library_id+", "+R1.condition.nickname+"</div>"]
159             s += ["</div>"]
160         s += ['</td>']
161       tbgc = bgc
162       bgc = pbgc
163       pbgc = tbgc
164     s += ['</tr>']
165   s += ['</table>']
166
167   return render_to_response('reports/report.html',{'main': "\n".join(s)})
168
169
170 def report_RM(request): #for RNA-Seq and Methyl-Seq
171   EXP = 'RNA-seq'  
172
173   if 'exp' in request.GET:
174     EXP = request.GET['exp'] # Methyl-seq
175
176   if 'aflid' in request.GET:
177     AFL_Id = request.GET['aflid']
178     try:
179       AFL = Affiliation.objects.get(id=AFL_Id).name
180       AFL_CNT = Affiliation.objects.get(id=AFL_Id).contact
181     except ObjectDoesNotExist:
182       return HttpResponse("ERROR: Affiliation Record Not Found for: '"+AFL_ID+"'")
183   else:
184     AFL = 'ENCODE_Tier1'
185     AFL_CNT = ''
186     try:
187       AFL_Id = Affiliation.objects.get(name=AFL,contact=AFL_CNT).id.__str__()
188     except ObjectDoesNotExist:
189       return HttpResponse("ERROR: Affiliation Record Not Found for: '"+AFL+"'")
190
191   CLLall = Library.objects.values('cell_line').order_by('cell_line').distinct()
192   CLLs = CLLall.filter(experiment_type=EXP,affiliations__name=AFL,affiliations__contact=AFL_CNT)
193
194   ########
195   # Check Replicate numbers
196   Reps = 1
197   RepRecs = Library.objects.filter(experiment_type=EXP,affiliations__name=AFL,affiliations__contact=AFL_CNT).order_by('-replicate')
198   if len(RepRecs) > 0: Reps = RepRecs[0].replicate
199                                                                                                                                                                               
200   str = ''
201   str += '<span style="margin-right:20px"><a  target=_self href="/admin" target=_self">Main Page</a></span>'
202   str += '<span>Select another <b>'+EXP+'</b> Report:</span> <select>'
203   for af in Affiliation.objects.distinct():
204     str += '<option value='+af.id.__str__()
205     if AFL_Id == af.id.__str__():
206       str += ' selected'
207     str += ' onclick="window.location=\'/reports/report_RM?exp='+EXP+'&aflid='+af.id.__str__()+'\'; return false;">'+af.name+' '+af.contact+'</option>'
208   str += '</select>'
209
210   if EXP == 'RNA-seq':
211     str += '<span style="margin-left:20px;padding:1px;border:solid #cccccc 1px">color scheme: <span style="margin-left:5px;background-color:#66ff66"> > 20 M</span><span style="margin-left:5px;background-color:#00ccff"> >  10 M</span><span style="margin-left:5px;background-color:#ffcc33"> > 6 M</span><span style="margin-left:5px;background-color:#ff3300"> < 6 M</span></span>'
212     str += '<span style="margin-left:20px">'
213     str += '<u>Switch to:</u> '+AFL+' '+AFL_CNT+' <a target=_self href="/reports/report?exp=RNA-seq&aflid='+AFL_Id+'"><b>ChIP-Seq</b> Report</a>'
214     str += '  | '
215     str += '<a target=_self href="/reports/report_RM?exp=Methyl-seq&aflid='+AFL_Id+'"><b>Methyl-Seq</b> Report</a>'
216   else:
217     str += '<span style="margin-left:20px;padding:1px;border:solid #cccccc 1px">color scheme: <span style="margin-left:5px;background-color:#66ff66"> > 12 M</span><span style="margin-left:5px;background-color:#00ccff"> >  5 M</span><span style="margin-left:5px;background-color:#ffcc33"> > 3 M</span><span style="margin-left:5px;background-color:#ff3300"> < 3 M</span></span>'
218     str += '<span style="margin-left:20px">'
219     str += '<u>Switch to:</u> '+AFL+' '+AFL_CNT+' <a target=_self href="/reports/report?exp=RNA-seq&aflid='+AFL_Id+'"><b>ChIP-Seq</b> Report</a>'
220     str += '  | '
221     str += '<a target=_self href="/reports/report_RM?exp=RNA-seq&aflid='+AFL_Id+'"><b>RNA-Seq</b> Report</a>'
222
223   str += '<br/><br/><table border=1 cellspacing="2">'
224   str += '<tr><th colspan='+(Reps*len(CLLs)).__str__()+' style="text-align:center">'+AFL+' '+AFL_CNT+'  <span style="font-size:140%">'+EXP+'</span></th></tr>'
225   str += '<tr>'
226   bgc = '#ffffff'
227   pbgc = '#f7f7f7'
228   for H in CLLs:
229     str += '<th colspan='+Reps.__str__()+' style="text-align:center;background-color:'+bgc+'">'+Cellline.objects.get(id=H['cell_line']).cellline_name+'</th>'
230     tbgc = bgc
231     bgc = pbgc
232     pbgc = tbgc
233   str += '</tr><tr>'
234   bgc = '#ffffff'
235   pbgc = '#f7f7f7'
236   for H in CLLs:
237     for r in range(1,Reps+1):
238       str += '<th style="text-align:center;background-color:'+bgc+'">Rep. '+r.__str__()+'</th>'
239     tbgc = bgc
240     bgc = pbgc
241     pbgc = tbgc
242   str += '</tr>'
243
244   str += '<tr>' 
245   bgc = '#ffffff'
246   pbgc = '#f7f7f7'
247   for H in CLLs:
248     for r in range(1,Reps+1):
249       repReads = Library.objects.filter(experiment_type=EXP,affiliations__name=AFL,affiliations__contact=AFL_CNT,cell_line=H['cell_line'],replicate=r)                                                                                                                    
250       str += "<td align=center valign=top style='background-color:"+bgc+"'>"
251       if len(repReads) == 0:
252         str += 'No Libraries'
253       else:
254         cnt = 0
255         for R1 in repReads:
256           rres = R1.aligned_m_reads()
257           # Check data sanlty   
258           if rres[2] != 'OK':
259             str += '<div style="border:solid red 2px">'+rres[2]
260           else:
261             cnt = rres[1]
262             if cnt > 0:
263               str += "<div style='background-color:"+getBgColor(cnt,EXP)+";border:solid #cccccc 1px;font-size:140%'>"
264               str += "%1.2f" % (cnt/1000000.0)+" M"
265             else:  str += "<div style='background-color:#ff3300;border:solid #cccccc 1px;width:100%;font-size:140%'>0 Reads"
266           str += "<div style='font-size:80%'><a title='View Record' target=_self href=/admin/fctracker/library/?q="+R1.library_id+">"+R1.library_id+"</a>, "+R1.condition.nickname+", "+R1.library_species.common_name+"</div>"
267           str += "<div style='font-size:70%'>\""+R1.library_name+"\"</div"
268           str += "</div>"
269       str += '</td>'
270     tbgc = bgc
271     bgc = pbgc
272     pbgc = tbgc
273   str += '</tr>'
274   str += '</table>'
275
276   return render_to_response('reports/report.html',{'main': str})
277
278 def getNotRanFCs(request):
279   FCall = FlowCell.objects.order_by('-run_date').distinct()
280   str = '<table><tr><th>FlowCell</th><th>Lanes</th><th>Creation Date</th></tr>'
281   for f in FCall:
282     try:
283       t = DataRun.objects.get(fcid=f.id)
284     except ObjectDoesNotExist:
285       str += '<tr><td>'+f.flowcell_id+'</td><td>'+f.Lanes()+'</td><td>'+f.run_date.__str__()+'</td></tr>'
286   str += "</table>"
287   return render_to_response('reports/report.html',{'main':str})
288  
289 def test_Libs(request):
290   str = ''
291   str += '<table border=1><tr><th>Lib ID</th><th>Current Libaray Name (Free Text)</th><th>Auto-composed Libaray Name (antibody + celline + libid + species + [replicate])</th></tr>'
292   allLibs = Library.objects.all()
293   #allLibs = Library.objects.filter(antibody__isnull=False)
294   for L in allLibs:
295     str += '<tr>'
296     str += '<td>'+L.library_id+'</td><td>'+L.library_name+'</td>'   
297     str += '<td>'
298     str += L.experiment_type+'_'
299     if L.cell_line.cellline_name != 'Unknown':
300       str += L.cell_line.cellline_name+'_'
301
302     try:
303       if L.antibody is not None:
304         str += L.antibody.nickname + '_'
305     except Antibody.DoesNotExist:
306       pass
307   
308     str += 'Rep'+L.replicate.__str__()
309     str += '</td></tr>' 
310
311   str += '</table>'
312   return HttpResponse(str)