4b6b3775f78c7546866d8121e5ac16224383a2c9
[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.core.exceptions import ObjectDoesNotExist
13 from django.http import HttpResponse, HttpResponseRedirect
14 from django.shortcuts import render_to_response
15 from django.template import RequestContext
16 from django.template.loader import get_template
17
18 import StringIO
19 import logging
20 import os
21
22 LANE_LIST = [1,2,3,4,5,6,7,8]
23
24 def create_library_context(cl):
25     """
26     Create a list of libraries that includes how many lanes were run
27     """
28     records = []
29     #for lib in library_items.object_list:
30     for lib in cl.result_list:
31        summary = {}
32        summary['library_id'] = lib.library_id
33        summary['library_name'] = lib.library_name
34        summary['species_name' ] = lib.library_species.scientific_name
35        if lib.amplified_from_sample is not None:
36            summary['amplified_from'] = lib.amplified_from_sample.library_id
37        else:
38            summary['amplified_from'] = ''
39        lanes_run = 0
40        for lane_id in LANE_LIST:
41            lane = getattr(lib, 'lane_%d_library' % (lane_id,))
42            lanes_run += len( lane.all() )
43        summary['lanes_run'] = lanes_run
44        records.append(summary)
45     cl.result_count = unicode(cl.paginator._count) + u" libraries"
46     return {'library_list': records }
47
48 def library(request):
49    # build changelist
50     fcl = ChangeList(request, Library,
51         list_filter=['affiliations', 'library_species'],
52         search_fields=['library_id', 'library_name', 'amplified_from_sample__library_id'],
53         list_per_page=200,
54         queryset=Library.objects.filter(hidden__exact=0)
55     )
56
57     context = { 'cl': fcl, 'title': 'Library Index'}
58     context.update(create_library_context(fcl))
59     t = get_template('samples/library_index.html')
60     c = RequestContext(request, context)
61     return HttpResponse( t.render(c) )
62
63 def library_to_flowcells(request, lib_id):
64     """
65     Display information about all the flowcells a library has been run on.
66     """
67     
68     try:
69       lib = Library.objects.get(library_id=lib_id)
70     except:
71       return HttpResponse("Library %s does not exist" % (lib_id))
72    
73     flowcell_list = []
74     interesting_flowcells = {} # aka flowcells we're looking at
75     for lane in LANE_LIST:
76         lane_library = getattr(lib, 'lane_%d_library' % (lane,))
77         for fc in lane_library.all():
78             flowcell_id, id = parse_flowcell_id(fc.flowcell_id)
79             if flowcell_id not in interesting_flowcells:
80                 interesting_flowcells[flowcell_id] = get_flowcell_result_dict(flowcell_id)
81             flowcell_list.append((fc.flowcell_id, lane))
82
83     flowcell_list.sort()
84     
85     lane_summary_list = []
86     eland_results = []
87     for fc, lane in flowcell_list:
88         lane_summary, err_list = _summary_stats(fc, lane)
89
90         eland_results.extend(_make_eland_results(fc, lane, interesting_flowcells))
91         lane_summary_list.extend(lane_summary)
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, flowcell_id, cnm):
102     """
103     returns a Summary.htm file if it exists.
104     """
105     fc_id, status = parse_flowcell_id(flowcell_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, flowcell_id, cnm, lane):
125     """
126     returns an eland_file upon calling.
127     """
128     fc_id, status = parse_flowcell_id(flowcell_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, flowcell_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(flowcell_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         run = load_pipeline_run_xml(xmlpath)
217         gerald_summary = run.gerald.summary.lane_results
218         for end in range(len(gerald_summary)):
219             eland_summary = run.gerald.eland_results.results[end][lane_id]
220             # add information to lane_summary
221             eland_summary.flowcell_id = flowcell_id
222             eland_summary.clusters = gerald_summary[end][lane_id].cluster
223             eland_summary.cycle_width = cycle_width
224             if hasattr(eland_summary, 'genome_map'):
225                 eland_summary.summarized_reads = runfolder.summarize_mapped_reads( 
226                                                    eland_summary.genome_map, 
227                                                    eland_summary.mapped_reads)
228
229             # grab some more information out of the flowcell db
230             flowcell = FlowCell.objects.get(flowcell_id=flowcell_id)
231             pm_field = 'lane_%d_pM' % (lane_id)
232             eland_summary.successful_pm = getattr(flowcell, pm_field)
233
234             summary_list.append(eland_summary)
235
236         #except Exception, e:
237         #    summary_list.append("Summary report needs to be updated.")
238         #    logging.error("Exception: " + str(e))
239     
240     return (summary_list, err_list)
241
242 def _summary_stats_old(flowcell_id, lane):
243     """
244     return a dictionary of summary stats for a given flowcell_id & lane.
245     """
246     fc_id, status = parse_flowcell_id(flowcell_id)
247     fc_result_dict = get_flowcell_result_dict(fc_id)
248     
249     dict_list = []
250     err_list = []
251     summary_list = []
252     
253     if fc_result_dict is None:
254         err_list.append('Results for Flowcell %s not found.' % (fc_id))
255         return (dict_list, err_list, summary_list)
256     
257     for cnm in fc_result_dict:
258     
259         xmlpath = fc_result_dict[cnm]['run_xml']
260         
261         if xmlpath is None:
262             err_list.append('Run xml for Flowcell %s(%s) not found.' % (fc_id, cnm))
263             continue
264         
265         tree = ElementTree.parse(xmlpath).getroot()
266         results = runfolder.PipelineRun(pathname='', xml=tree)
267         try:
268             lane_report = runfolder.summarize_lane(results.gerald, lane)
269             summary_list.append(os.linesep.join(lane_report))
270         except Exception, e:
271             summary_list.append("Summary report needs to be updated.")
272             logging.error("Exception: " + str(e))
273        
274         print "----------------------------------"
275         print "-- DOES NOT SUPPORT PAIRED END ---"
276         print "----------------------------------"
277         lane_results = results.gerald.summary[0][lane]
278         lrs = lane_results
279         
280         d = {}
281         
282         d['average_alignment_score'] = lrs.average_alignment_score
283         d['average_first_cycle_intensity'] = lrs.average_first_cycle_intensity
284         d['cluster'] = lrs.cluster
285         d['lane'] = lrs.lane
286         d['flowcell'] = flowcell_id
287         d['cnm'] = cnm
288         d['percent_error_rate'] = lrs.percent_error_rate
289         d['percent_intensity_after_20_cycles'] = lrs.percent_intensity_after_20_cycles
290         d['percent_pass_filter_align'] = lrs.percent_pass_filter_align
291         d['percent_pass_filter_clusters'] = lrs.percent_pass_filter_clusters
292         
293         #FIXME: function finished, but need to take advantage of
294         #   may need to take in a list of lanes so we only have to
295         #   load the xml file once per flowcell rather than once
296         #   per lane.
297         dict_list.append(d)
298     
299     return (dict_list, err_list, summary_list)
300     
301     
302 def get_eland_result_type(pathname):
303     """
304     Guess the eland result file type from the filename
305     """
306     path, filename = os.path.split(pathname)
307     if 'extended' in filename:
308         return 'extended'
309     elif 'multi' in filename:
310         return 'multi'
311     elif 'result' in filename:
312         return 'result'
313     else:
314         return 'unknown'
315
316 def _make_eland_results(flowcell_id, lane, interesting_flowcells):
317     fc_id, status = parse_flowcell_id(flowcell_id)
318     cur_fc = interesting_flowcells.get(fc_id, None)
319     if cur_fc is None:
320       return []
321
322     results = []
323     for cycle in cur_fc.keys():
324         result_path = cur_fc[cycle]['eland_results'].get(lane, None)
325         result_link = make_result_link(fc_id, cycle, lane, result_path)
326         results.append({'flowcell_id': fc_id,
327                         'cycle': cycle, 
328                         'lane': lane, 
329                         'summary_url': make_summary_url(flowcell_id, cycle),
330                         'result_url': result_link[0],
331                         'result_label': result_link[1],
332                         'bed_url': result_link[2],
333         })
334     return results
335
336 def make_summary_url(flowcell_id, cycle_name):
337     url = '/results/%s/%s/summary/' % (flowcell_id, cycle_name)
338     return url
339
340 def make_result_link(flowcell_id, cycle_name, lane, eland_result_path):
341     if eland_result_path is None:
342         return ("", "", "")
343
344     result_type = get_eland_result_type(eland_result_path)
345     result_url = '/results/%s/%s/eland_result/%s' % (flowcell_id, cycle_name, lane)
346     result_label = 'eland %s' % (result_type,)
347     bed_url = None
348     if result_type == 'result':
349        bed_url_pattern = '/results/%s/%s/bedfile/%s'
350        bed_url = bed_url_pattern % (flowcell_id, cycle_name, lane)
351     
352     return (result_url, result_label, bed_url)
353
354 def _files(flowcell_id, lane):
355     """
356     Sets up available files for download
357     """
358     lane = int(lane)
359
360     flowcell_id, id = parse_flowcell_id(flowcell_id)
361     d = get_flowcell_result_dict(flowcell_id)
362     
363     if d is None:
364         return ''
365     
366     output = []
367     
368     # c_name == 'CN-M' (i.e. C1-33)
369     for c_name in d:
370         
371         if d[c_name]['summary'] is not None:
372             output.append('<a href="/results/%s/%s/summary/">summary(%s)</a>' \
373                           % (flowcell_id, c_name, c_name))
374         
375         erd = d[c_name]['eland_results']
376         if lane in erd:
377             result_type = get_eland_result_type(erd[lane])
378             result_url_pattern = '<a href="/results/%s/%s/eland_result/%s">eland %s(%s)</a>'
379             output.append(result_url_pattern % (flowcell_id, c_name, lane, result_type, c_name))
380             if result_type == 'result':
381                 bed_url_pattern = '<a href="/results/%s/%s/bedfile/%s">bedfile(%s)</a>'
382                 output.append(bed_url_pattern % (flowcell_id, c_name, lane, c_name))
383     
384     if len(output) == 0:
385         return ''
386     
387     return '(' + '|'.join(output) + ')'
388
389 def library_id_to_admin_url(request, lib_id):
390     lib = Library.objects.get(library_id=lib_id)
391     return HttpResponseRedirect('/admin/samples/library/%s' % (lib.id,))
392