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