478c547030e57a8a303ad9f2c0db4627b38aadc4
[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     
147     return HttpResponse(f, mimetype="application/x-elandresult")
148
149
150 def bedfile_fc_cnm_eland_lane_ucsc(request, fc_id, cnm, lane):
151     """
152     returns a bed file for a given flowcell, CN-M (i.e. C1-33), and lane (ucsc compatible)
153     """
154     return bedfile_fc_cnm_eland_lane(request, fc_id, cnm, lane, ucsc_compatible=True)
155
156
157 def bedfile_fc_cnm_eland_lane(request, fc_id, cnm, lane, ucsc_compatible=False):
158     """
159     returns a bed file for a given flowcell, CN-M (i.e. C1-33), and lane
160     """
161     fc_id, status = parse_flowcell_id(fc_id)
162     d = get_flowcell_result_dict(fc_id)
163     
164     if d is None:
165         return HttpResponse('<b>Results for Flowcell %s not found.</b>' % (fc_id))
166     
167     if cnm not in d:
168         return HttpResponse('<b>Results for Flowcell %s; %s not found.</b>' % (fc_id, cnm))
169     
170     erd = d[cnm]['eland_results']
171     lane = int(lane)
172     
173     if lane not in erd:
174         return HttpResponse('<b>Results for Flowcell %s; %s; lane %s not found.</b>' % (fc_id, cnm, lane))
175     
176     filepath = erd[lane]
177     
178     # Eland result file
179     fi = opener.autoopen(filepath, 'r')
180     # output memory file
181     
182     name, description = makebed.make_description( fc_id, lane )
183     
184     bedgen = makebed.make_bed_from_eland_generator(fi, name, description)
185     
186     if ucsc_compatible:
187         return HttpResponse(bedgen)
188     else:
189         return HttpResponse(bedgen, mimetype="application/x-bedfile")
190
191
192 def _summary_stats(flowcell_id, lane_id):
193     """
194     Return the summary statistics for a given flowcell, lane, and end.
195     """
196     fc_id, status = parse_flowcell_id(flowcell_id)
197     fc_result_dict = get_flowcell_result_dict(fc_id)
198
199     summary_list = []
200     err_list = []
201     
202     if fc_result_dict is None:
203         err_list.append('Results for Flowcell %s not found.' % (fc_id))
204         return (summary_list, err_list)
205
206     for cycle_width in fc_result_dict:
207         xmlpath = fc_result_dict[cycle_width]['run_xml']
208         
209         if xmlpath is None:
210             err_list.append('Run xml for Flowcell %s(%s) not found.' % (fc_id, cycle_width))
211             continue
212         
213         try:
214             run = load_pipeline_run_xml(xmlpath)
215             gerald_summary = run.gerald.summary.lane_results
216             for end in range(len(gerald_summary)):
217                 eland_summary = run.gerald.eland_results.results[end][lane_id]
218                 # add information to lane_summary
219                 eland_summary.flowcell_id = flowcell_id
220                 eland_summary.clusters = gerald_summary[end][lane_id].cluster
221                 eland_summary.cycle_width = cycle_width
222                 eland_summary.summarized_reads = runfolder.summarize_mapped_reads(eland_summary.genome_map, eland_summary.mapped_reads)
223
224                 # grab some more information out of the flowcell db
225                 flowcell = FlowCell.objects.get(flowcell_id=fc_id)
226                 pm_field = 'lane_%d_pM' % (lane_id)
227                 eland_summary.successful_pm = getattr(flowcell, pm_field)
228
229                 summary_list.append(eland_summary)
230
231         except Exception, e:
232             summary_list.append("Summary report needs to be updated.")
233             logging.error("Exception: " + str(e))
234     
235     return (summary_list, err_list)
236
237 def _summary_stats_old(flowcell_id, lane):
238     """
239     return a dictionary of summary stats for a given flowcell_id & lane.
240     """
241     fc_id, status = parse_flowcell_id(flowcell_id)
242     fc_result_dict = get_flowcell_result_dict(fc_id)
243     
244     dict_list = []
245     err_list = []
246     summary_list = []
247     
248     if fc_result_dict is None:
249         err_list.append('Results for Flowcell %s not found.' % (fc_id))
250         return (dict_list, err_list, summary_list)
251     
252     for cnm in fc_result_dict:
253     
254         xmlpath = fc_result_dict[cnm]['run_xml']
255         
256         if xmlpath is None:
257             err_list.append('Run xml for Flowcell %s(%s) not found.' % (fc_id, cnm))
258             continue
259         
260         tree = ElementTree.parse(xmlpath).getroot()
261         results = runfolder.PipelineRun(pathname='', xml=tree)
262         try:
263             lane_report = runfolder.summarize_lane(results.gerald, lane)
264             summary_list.append(os.linesep.join(lane_report))
265         except Exception, e:
266             summary_list.append("Summary report needs to be updated.")
267             logging.error("Exception: " + str(e))
268        
269         print "----------------------------------"
270         print "-- DOES NOT SUPPORT PAIRED END ---"
271         print "----------------------------------"
272         lane_results = results.gerald.summary[0][lane]
273         lrs = lane_results
274         
275         d = {}
276         
277         d['average_alignment_score'] = lrs.average_alignment_score
278         d['average_first_cycle_intensity'] = lrs.average_first_cycle_intensity
279         d['cluster'] = lrs.cluster
280         d['lane'] = lrs.lane
281         d['flowcell'] = flowcell_id
282         d['cnm'] = cnm
283         d['percent_error_rate'] = lrs.percent_error_rate
284         d['percent_intensity_after_20_cycles'] = lrs.percent_intensity_after_20_cycles
285         d['percent_pass_filter_align'] = lrs.percent_pass_filter_align
286         d['percent_pass_filter_clusters'] = lrs.percent_pass_filter_clusters
287         
288         #FIXME: function finished, but need to take advantage of
289         #   may need to take in a list of lanes so we only have to
290         #   load the xml file once per flowcell rather than once
291         #   per lane.
292         dict_list.append(d)
293     
294     return (dict_list, err_list, summary_list)
295     
296     
297 def get_eland_result_type(pathname):
298     """
299     Guess the eland result file type from the filename
300     """
301     path, filename = os.path.split(pathname)
302     if 'extended' in filename:
303         return 'extended'
304     elif 'multi' in filename:
305         return 'multi'
306     elif 'result' in filename:
307         return 'result'
308     else:
309         return 'unknown'
310
311 def _make_eland_results(flowcell_id, lane, interesting_flowcells):
312
313     cur_fc = interesting_flowcells.get(flowcell_id, None)
314     if cur_fc is None:
315       return []
316
317     results = []
318     for cycle in cur_fc.keys():
319         result_path = cur_fc[cycle]['eland_results'].get(lane, None)
320         result_link = make_result_link(flowcell_id, cycle, lane, result_path)
321         results.append({'flowcell_id': flowcell_id,
322                         'cycle': cycle, 
323                         'lane': lane, 
324                         'summary_url': make_summary_url(flowcell_id, cycle),
325                         'result_url': result_link[0],
326                         'result_label': result_link[1],
327                         'bed_url': result_link[2],
328         })
329     return results
330
331 def make_summary_url(flowcell_id, cycle_name):
332     url = '/results/%s/%s/summary/' % (flowcell_id, cycle_name)
333     return url
334
335 def make_result_link(flowcell_id, cycle_name, lane, eland_result_path):
336     if eland_result_path is None:
337         return ("", "", "")
338
339     result_type = get_eland_result_type(eland_result_path)
340     result_url = '/results/%s/%s/eland_result/%s' % (flowcell_id, cycle_name, lane)
341     result_label = 'eland %s' % (result_type,)
342     bed_url = None
343     if result_type == 'result':
344        bed_url_pattern = '/results/%s/%s/bedfile/%s'
345        bed_url = bed_url_pattern % (flowcell_id, cycle_name, lane)
346     
347     return (result_url, result_label, bed_url)
348
349 def _files(flowcell_id, lane):
350     """
351     Sets up available files for download
352     """
353     lane = int(lane)
354
355     flowcell_id, id = parse_flowcell_id(flowcell_id)
356     d = get_flowcell_result_dict(flowcell_id)
357     
358     if d is None:
359         return ''
360     
361     output = []
362     
363     # c_name == 'CN-M' (i.e. C1-33)
364     for c_name in d:
365         
366         if d[c_name]['summary'] is not None:
367             output.append('<a href="/results/%s/%s/summary/">summary(%s)</a>' \
368                           % (flowcell_id, c_name, c_name))
369         
370         erd = d[c_name]['eland_results']
371         if lane in erd:
372             result_type = get_eland_result_type(erd[lane])
373             result_url_pattern = '<a href="/results/%s/%s/eland_result/%s">eland %s(%s)</a>'
374             output.append(result_url_pattern % (flowcell_id, c_name, lane, result_type, c_name))
375             if result_type == 'result':
376                 bed_url_pattern = '<a href="/results/%s/%s/bedfile/%s">bedfile(%s)</a>'
377                 output.append(bed_url_pattern % (flowcell_id, c_name, lane, c_name))
378     
379     if len(output) == 0:
380         return ''
381     
382     return '(' + '|'.join(output) + ')'
383
384 def library_id_to_admin_url(request, lib_id):
385     lib = Library.objects.get(library_id=lib_id)
386     return HttpResponseRedirect('/admin/samples/library/%s' % (lib.id,))
387