b6561a624ed1b54c42a606a305cab1f081d05298
[htsworkflow.git] / htsworkflow / frontend / samples / views.py
1 # Create your views here.
2 from htsworkflow.frontend.experiments.models import FlowCell
3 from htsworkflow.frontend.samples.changelist import ChangeList
4 from htsworkflow.frontend.samples.models import Library
5 from htsworkflow.frontend.samples.results import get_flowcell_result_dict, parse_flowcell_id
6 from htsworkflow.pipelines.runfolder import load_pipeline_run_xml
7 from htsworkflow.pipelines import runfolder
8 from htsworkflow.frontend import settings
9 from htsworkflow.util import makebed
10 from htsworkflow.util import opener
11
12 from django.http import HttpResponse
13 from django.template import RequestContext
14 from django.template.loader import get_template
15
16 import StringIO
17 import logging
18 import os
19
20 LANE_LIST = [1,2,3,4,5,6,7,8]
21
22 def create_library_context(cl):
23     """
24     Create a list of libraries that includes how many lanes were run
25     """
26     records = []
27     #for lib in library_items.object_list:
28     for lib in cl.result_list:
29        summary = {}
30        summary['library_id'] = lib.library_id
31        summary['library_name'] = lib.library_name
32        summary['species_name' ] = lib.library_species.scientific_name
33        lanes_run = 0
34        for lane_id in LANE_LIST:
35            lane = getattr(lib, 'lane_%d_library' % (lane_id,))
36            lanes_run += len( lane.all() )
37        summary['lanes_run'] = lanes_run
38        records.append(summary)
39     cl.result_count = unicode(cl.paginator._count) + u" libraries"
40     return {'library_list': records }
41
42 def library(request):
43    # build changelist
44     fcl = ChangeList(request, Library,
45         list_filter=['library_species','affiliations'],
46         search_fields=['library_id', 'library_name'],
47         list_per_page=200,
48         queryset=Library.objects.filter(hidden__exact=0)
49     )
50
51     context = { 'cl': fcl, 'title': 'Library Index'}
52     context.update(create_library_context(fcl))
53     t = get_template('samples/library_index.html')
54     c = RequestContext(request, context)
55     return HttpResponse( t.render(c) )
56
57 def library_to_flowcells(request, lib_id):
58     """
59     Display information about all the flowcells a library has been run on.
60     """
61     t = get_template("samples/library_detail.html")
62     
63     try:
64       lib = Library.objects.get(library_id=lib_id)
65     except:
66       return HttpResponse("Library %s does not exist" % (lib_id))
67     
68     output = []
69     
70     output.append('<b>Library ID:</b> %s' % (lib.library_id))
71     output.append('<b>Name:</b> %s' % (lib.library_name))
72     output.append('<b>Species:</b> %s' % (lib.library_species.scientific_name))
73     output.append('')
74     
75     output.append('<b>FLOWCELL - LANE:</b>')
76     
77     output.extend([ '%s - Lane 1 %s' % (fc.flowcell_id, _files(fc.flowcell_id, 1)) for fc in lib.lane_1_library.all() ])
78     output.extend([ '%s - Lane 2 %s' % (fc.flowcell_id, _files(fc.flowcell_id, 2)) for fc in lib.lane_2_library.all() ])
79     output.extend([ '%s - Lane 3 %s' % (fc.flowcell_id, _files(fc.flowcell_id, 3)) for fc in lib.lane_3_library.all() ])
80     output.extend([ '%s - Lane 4 %s' % (fc.flowcell_id, _files(fc.flowcell_id, 4)) for fc in lib.lane_4_library.all() ])
81     output.extend([ '%s - Lane 5 %s' % (fc.flowcell_id, _files(fc.flowcell_id, 5)) for fc in lib.lane_5_library.all() ])
82     output.extend([ '%s - Lane 6 %s' % (fc.flowcell_id, _files(fc.flowcell_id, 6)) for fc in lib.lane_6_library.all() ])
83     output.extend([ '%s - Lane 7 %s' % (fc.flowcell_id, _files(fc.flowcell_id, 7)) for fc in lib.lane_7_library.all() ])
84     output.extend([ '%s - Lane 8 %s' % (fc.flowcell_id, _files(fc.flowcell_id, 8)) for fc in lib.lane_8_library.all() ])
85     
86     record_count = lib.lane_1_library.count() + \
87                     lib.lane_2_library.count() + \
88                     lib.lane_3_library.count() + \
89                     lib.lane_4_library.count() + \
90                     lib.lane_5_library.count() + \
91                     lib.lane_6_library.count() + \
92                     lib.lane_7_library.count() + \
93                     lib.lane_8_library.count()
94     
95     flowcell_list = []
96     flowcell_list.extend([ (fc.flowcell_id, 1) for fc in lib.lane_1_library.all() ])
97     flowcell_list.extend([ (fc.flowcell_id, 2) for fc in lib.lane_2_library.all() ])
98     flowcell_list.extend([ (fc.flowcell_id, 3) for fc in lib.lane_3_library.all() ])
99     flowcell_list.extend([ (fc.flowcell_id, 4) for fc in lib.lane_4_library.all() ])
100     flowcell_list.extend([ (fc.flowcell_id, 5) for fc in lib.lane_5_library.all() ])
101     flowcell_list.extend([ (fc.flowcell_id, 6) for fc in lib.lane_6_library.all() ])
102     flowcell_list.extend([ (fc.flowcell_id, 7) for fc in lib.lane_7_library.all() ])
103     flowcell_list.extend([ (fc.flowcell_id, 8) for fc in lib.lane_8_library.all() ])
104     flowcell_list.sort()
105     
106     lane_summary_list = []
107     for fc, lane in flowcell_list:
108         lane_summary, err_list = _summary_stats(fc, lane)
109         
110         lane_summary_list.extend(lane_summary)
111     
112         for err in err_list:    
113             output.append(err)
114    
115     output.append('<br />')
116     output.append(t.render(RequestContext(request, {'lane_summary_list': lane_summary_list})))
117     output.append('<br />')
118     
119     if record_count == 0:
120         output.append("None Found")
121     
122     return HttpResponse('<br />\n'.join(output))
123
124
125 def summaryhtm_fc_cnm(request, fc_id, cnm):
126     """
127     returns a Summary.htm file if it exists.
128     """
129     fc_id, status = parse_flowcell_id(fc_id)
130     d = get_flowcell_result_dict(fc_id)
131     
132     if d is None:
133         return HttpResponse('<b>Results for Flowcell %s not found.</b>' % (fc_id))
134     
135     if cnm not in d:
136         return HttpResponse('<b>Results for Flowcell %s; %s not found.</b>' % (fc_id, cnm))
137     
138     summary_filepath = d[cnm]['summary']
139     
140     if summary_filepath is None:
141         return HttpResponse('<b>Summary.htm for Flowcell %s; %s not found.</b>' % (fc_id, cnm))
142     
143     f = open(summary_filepath, 'r')
144     
145     return HttpResponse(f)
146
147
148 def result_fc_cnm_eland_lane(request, fc_id, cnm, lane):
149     """
150     returns an eland_file upon calling.
151     """
152     fc_id, status = parse_flowcell_id(fc_id)
153     d = get_flowcell_result_dict(fc_id)
154     
155     if d is None:
156         return HttpResponse('<b>Results for Flowcell %s not found.</b>' % (fc_id))
157     
158     if cnm not in d:
159         return HttpResponse('<b>Results for Flowcell %s; %s not found.</b>' % (fc_id, cnm))
160     
161     erd = d[cnm]['eland_results']
162     lane = int(lane)
163     
164     if lane not in erd:
165         return HttpResponse('<b>Results for Flowcell %s; %s; lane %s not found.</b>' % (fc_id, cnm, lane))
166     
167     filepath = erd[lane]
168     
169     f = opener.autoopen(filepath, 'r')
170     
171     return HttpResponse(f, mimetype="application/x-elandresult")
172
173
174 def bedfile_fc_cnm_eland_lane_ucsc(request, fc_id, cnm, lane):
175     """
176     returns a bed file for a given flowcell, CN-M (i.e. C1-33), and lane (ucsc compatible)
177     """
178     return bedfile_fc_cnm_eland_lane(request, fc_id, cnm, lane, ucsc_compatible=True)
179
180
181 def bedfile_fc_cnm_eland_lane(request, fc_id, cnm, lane, ucsc_compatible=False):
182     """
183     returns a bed file for a given flowcell, CN-M (i.e. C1-33), and lane
184     """
185     fc_id, status = parse_flowcell_id(fc_id)
186     d = get_flowcell_result_dict(fc_id)
187     
188     if d is None:
189         return HttpResponse('<b>Results for Flowcell %s not found.</b>' % (fc_id))
190     
191     if cnm not in d:
192         return HttpResponse('<b>Results for Flowcell %s; %s not found.</b>' % (fc_id, cnm))
193     
194     erd = d[cnm]['eland_results']
195     lane = int(lane)
196     
197     if lane not in erd:
198         return HttpResponse('<b>Results for Flowcell %s; %s; lane %s not found.</b>' % (fc_id, cnm, lane))
199     
200     filepath = erd[lane]
201     
202     # Eland result file
203     fi = opener.autoopen(filepath, 'r')
204     # output memory file
205     
206     name, description = makebed.make_description( fc_id, lane )
207     
208     bedgen = makebed.make_bed_from_eland_generator(fi, name, description)
209     
210     if ucsc_compatible:
211         return HttpResponse(bedgen)
212     else:
213         return HttpResponse(bedgen, mimetype="application/x-bedfile")
214
215
216 def _summary_stats(flowcell_id, lane_id):
217     """
218     Return the summary statistics for a given flowcell, lane, and end.
219     """
220     fc_id, status = parse_flowcell_id(flowcell_id)
221     fc_result_dict = get_flowcell_result_dict(fc_id)
222
223     summary_list = []
224     err_list = []
225     
226     if fc_result_dict is None:
227         err_list.append('Results for Flowcell %s not found.' % (fc_id))
228         return (summary_list, err_list)
229
230     for cycle_width in fc_result_dict:
231         xmlpath = fc_result_dict[cycle_width]['run_xml']
232         
233         if xmlpath is None:
234             err_list.append('Run xml for Flowcell %s(%s) not found.' % (fc_id, cycle_width))
235             continue
236         
237         try:
238             run = load_pipeline_run_xml(xmlpath)
239             gerald_summary = run.gerald.summary.lane_results
240             for end in range(len(gerald_summary)):
241                 eland_summary = run.gerald.eland_results.results[end][lane_id]
242                 # add information to lane_summary
243                 eland_summary.flowcell_id = flowcell_id
244                 eland_summary.clusters = gerald_summary[end][lane_id].cluster
245                 eland_summary.cycle_width = cycle_width
246                 eland_summary.summarized_reads = runfolder.summarize_mapped_reads(eland_summary.genome_map, eland_summary.mapped_reads)
247
248                 # grab some more information out of the flowcell db
249                 flowcell = FlowCell.objects.get(flowcell_id=fc_id)
250                 pm_field = 'lane_%d_pM' % (lane_id)
251                 eland_summary.successful_pm = getattr(flowcell, pm_field)
252
253                 summary_list.append(eland_summary)
254
255         except Exception, e:
256             summary_list.append("Summary report needs to be updated.")
257             logging.error("Exception: " + str(e))
258     
259     return (summary_list, err_list)
260
261 def _summary_stats_old(flowcell_id, lane):
262     """
263     return a dictionary of summary stats for a given flowcell_id & lane.
264     """
265     fc_id, status = parse_flowcell_id(flowcell_id)
266     fc_result_dict = get_flowcell_result_dict(fc_id)
267     
268     dict_list = []
269     err_list = []
270     summary_list = []
271     
272     if fc_result_dict is None:
273         err_list.append('Results for Flowcell %s not found.' % (fc_id))
274         return (dict_list, err_list, summary_list)
275     
276     for cnm in fc_result_dict:
277     
278         xmlpath = fc_result_dict[cnm]['run_xml']
279         
280         if xmlpath is None:
281             err_list.append('Run xml for Flowcell %s(%s) not found.' % (fc_id, cnm))
282             continue
283         
284         tree = ElementTree.parse(xmlpath).getroot()
285         results = runfolder.PipelineRun(pathname='', xml=tree)
286         try:
287             lane_report = runfolder.summarize_lane(results.gerald, lane)
288             summary_list.append(os.linesep.join(lane_report))
289         except Exception, e:
290             summary_list.append("Summary report needs to be updated.")
291             logging.error("Exception: " + str(e))
292        
293         print "----------------------------------"
294         print "-- DOES NOT SUPPORT PAIRED END ---"
295         print "----------------------------------"
296         lane_results = results.gerald.summary[0][lane]
297         lrs = lane_results
298         
299         d = {}
300         
301         d['average_alignment_score'] = lrs.average_alignment_score
302         d['average_first_cycle_intensity'] = lrs.average_first_cycle_intensity
303         d['cluster'] = lrs.cluster
304         d['lane'] = lrs.lane
305         d['flowcell'] = flowcell_id
306         d['cnm'] = cnm
307         d['percent_error_rate'] = lrs.percent_error_rate
308         d['percent_intensity_after_20_cycles'] = lrs.percent_intensity_after_20_cycles
309         d['percent_pass_filter_align'] = lrs.percent_pass_filter_align
310         d['percent_pass_filter_clusters'] = lrs.percent_pass_filter_clusters
311         
312         #FIXME: function finished, but need to take advantage of
313         #   may need to take in a list of lanes so we only have to
314         #   load the xml file once per flowcell rather than once
315         #   per lane.
316         dict_list.append(d)
317     
318     return (dict_list, err_list, summary_list)
319     
320     
321
322     
323 def _files(flowcell_id, lane):
324     """
325     Sets up available files for download
326     """
327     flowcell_id, id = parse_flowcell_id(flowcell_id)
328     d = get_flowcell_result_dict(flowcell_id)
329     
330     if d is None:
331         return ''
332     
333     output = []
334     
335     # c_name == 'CN-M' (i.e. C1-33)
336     for c_name in d:
337         
338         if d[c_name]['summary'] is not None:
339             output.append('<a href="/results/%s/%s/summary/">summary(%s)</a>' \
340                           % (flowcell_id, c_name, c_name))
341         
342         erd = d[c_name]['eland_results']
343         
344         if int(lane) in erd:
345             output.append('<a href="/results/%s/%s/eland_result/%s">eland_result(%s)</a>' % (flowcell_id, c_name, lane, c_name))
346             output.append('<a href="/results/%s/%s/bedfile/%s">bedfile(%s)</a>' % (flowcell_id, c_name, lane, c_name))
347     
348     if len(output) == 0:
349         return ''
350     
351     return '(' + '|'.join(output) + ')'
352