100f3a972bc826858fd84134f683a82f5b2d41d8
[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        summary['is_archived'] = lib.is_archived()
45        records.append(summary)
46     cl.result_count = unicode(cl.paginator._count) + u" libraries"
47     return {'library_list': records }
48
49 def library(request):
50    # build changelist
51     fcl = ChangeList(request, Library,
52         list_filter=['affiliations', 'library_species'],
53         search_fields=['library_id', 'library_name', 'amplified_from_sample__library_id'],
54         list_per_page=200,
55         queryset=Library.objects.filter(hidden__exact=0)
56     )
57
58     context = { 'cl': fcl, 'title': 'Library Index'}
59     context.update(create_library_context(fcl))
60     t = get_template('samples/library_index.html')
61     c = RequestContext(request, context)
62     return HttpResponse( t.render(c) )
63
64 def library_to_flowcells(request, lib_id):
65     """
66     Display information about all the flowcells a library has been run on.
67     """
68     
69     try:
70       lib = Library.objects.get(library_id=lib_id)
71     except:
72       return HttpResponse("Library %s does not exist" % (lib_id))
73    
74     flowcell_list = []
75     interesting_flowcells = {} # aka flowcells we're looking at
76     for lane in LANE_LIST:
77         lane_library = getattr(lib, 'lane_%d_library' % (lane,))
78         for fc in lane_library.all():
79             flowcell_id, id = parse_flowcell_id(fc.flowcell_id)
80             if flowcell_id not in interesting_flowcells:
81                 interesting_flowcells[flowcell_id] = get_flowcell_result_dict(flowcell_id)
82             flowcell_list.append((fc.flowcell_id, lane))
83
84     flowcell_list.sort()
85     
86     lane_summary_list = []
87     eland_results = []
88     for fc, lane in flowcell_list:
89         lane_summary, err_list = _summary_stats(fc, lane)
90
91         eland_results.extend(_make_eland_results(fc, lane, interesting_flowcells))
92         lane_summary_list.extend(lane_summary)
93
94     return render_to_response(
95         'samples/library_detail.html',
96         {'lib': lib,
97          'eland_results': eland_results,
98          'lane_summary_list': lane_summary_list,
99         },
100         context_instance = RequestContext(request))
101
102 def summaryhtm_fc_cnm(request, flowcell_id, cnm):
103     """
104     returns a Summary.htm file if it exists.
105     """
106     fc_id, status = parse_flowcell_id(flowcell_id)
107     d = get_flowcell_result_dict(fc_id)
108     
109     if d is None:
110         return HttpResponse('<b>Results for Flowcell %s not found.</b>' % (fc_id))
111     
112     if cnm not in d:
113         return HttpResponse('<b>Results for Flowcell %s; %s not found.</b>' % (fc_id, cnm))
114     
115     summary_filepath = d[cnm]['summary']
116     
117     if summary_filepath is None:
118         return HttpResponse('<b>Summary.htm for Flowcell %s; %s not found.</b>' % (fc_id, cnm))
119     
120     f = open(summary_filepath, 'r')
121     
122     return HttpResponse(f)
123
124
125 def result_fc_cnm_eland_lane(request, flowcell_id, cnm, lane):
126     """
127     returns an eland_file upon calling.
128     """
129     fc_id, status = parse_flowcell_id(flowcell_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     erd = d[cnm]['eland_results']
139     lane = int(lane)
140     
141     if lane not in erd:
142         return HttpResponse('<b>Results for Flowcell %s; %s; lane %s not found.</b>' % (fc_id, cnm, lane))
143     
144     filepath = erd[lane]
145     
146     #f = opener.autoopen(filepath, 'r')
147     # return HttpResponse(f, mimetype="application/x-elandresult")
148
149     f = open(filepath, 'r')
150     return HttpResponse(f, mimetype='application/x-bzip2')
151     
152
153
154 def bedfile_fc_cnm_eland_lane_ucsc(request, fc_id, cnm, lane):
155     """
156     returns a bed file for a given flowcell, CN-M (i.e. C1-33), and lane (ucsc compatible)
157     """
158     return bedfile_fc_cnm_eland_lane(request, fc_id, cnm, lane, ucsc_compatible=True)
159
160
161 def bedfile_fc_cnm_eland_lane(request, flowcell_id, cnm, lane, ucsc_compatible=False):
162     """
163     returns a bed file for a given flowcell, CN-M (i.e. C1-33), and lane
164     """
165     fc_id, status = parse_flowcell_id(flowcell_id)
166     d = get_flowcell_result_dict(fc_id)
167     
168     if d is None:
169         return HttpResponse('<b>Results for Flowcell %s not found.</b>' % (fc_id))
170     
171     if cnm not in d:
172         return HttpResponse('<b>Results for Flowcell %s; %s not found.</b>' % (fc_id, cnm))
173     
174     erd = d[cnm]['eland_results']
175     lane = int(lane)
176     
177     if lane not in erd:
178         return HttpResponse('<b>Results for Flowcell %s; %s; lane %s not found.</b>' % (fc_id, cnm, lane))
179     
180     filepath = erd[lane]
181     
182     # Eland result file
183     fi = opener.autoopen(filepath, 'r')
184     # output memory file
185     
186     name, description = makebed.make_description( fc_id, lane )
187     
188     bedgen = makebed.make_bed_from_eland_generator(fi, name, description)
189     
190     if ucsc_compatible:
191         return HttpResponse(bedgen)
192     else:
193         return HttpResponse(bedgen, mimetype="application/x-bedfile")
194
195
196 def _summary_stats(flowcell_id, lane_id):
197     """
198     Return the summary statistics for a given flowcell, lane, and end.
199     """
200     fc_id, status = parse_flowcell_id(flowcell_id)
201     fc_result_dict = get_flowcell_result_dict(fc_id)
202
203     summary_list = []
204     err_list = []
205     
206     if fc_result_dict is None:
207         err_list.append('Results for Flowcell %s not found.' % (fc_id))
208         return (summary_list, err_list)
209
210     for cycle_width in fc_result_dict:
211         xmlpath = fc_result_dict[cycle_width]['run_xml']
212         
213         if xmlpath is None:
214             err_list.append('Run xml for Flowcell %s(%s) not found.' % (fc_id, cycle_width))
215             continue
216         
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=flowcell_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     fc_id, status = parse_flowcell_id(flowcell_id)
319     cur_fc = interesting_flowcells.get(fc_id, None)
320     if cur_fc is None:
321       return []
322
323     flowcell = Flowcell.objects.get(flowcell_id=flowcell_id)
324     # Loop throw storage devices if a result has been archived
325     storage_id_list = []
326     if cur_fc is not None:
327         for lts in flowcell.longtermstorage_set.all():
328             for sd in lts.storage_devices.all():
329                 # Use barcode_id if it exists
330                 if sd.barcode_id is not None and sd.barcode_id != '':
331                     storage_id_list.append(sd.barcode_id)
332                 # Otherwise use UUID
333                 else:
334                     storage_id_list.append(sd.uuid)
335         
336     # Formatting for template use
337     if len(storage_id_list) == 0:
338         storage_ids = None
339     else:
340         storage_ids = ', '.join(storage_id_list)
341
342     results = []
343     for cycle in cur_fc.keys():
344         result_path = cur_fc[cycle]['eland_results'].get(lane, None)
345         result_link = make_result_link(fc_id, cycle, lane, result_path)
346         results.append({'flowcell_id': fc_id,
347                         'cycle': cycle, 
348                         'lane': lane, 
349                         'summary_url': make_summary_url(flowcell_id, cycle),
350                         'result_url': result_link[0],
351                         'result_label': result_link[1],
352                         'bed_url': result_link[2],
353                         'storage_ids': storage_ids
354         })
355     return results
356
357 def make_summary_url(flowcell_id, cycle_name):
358     url = '/results/%s/%s/summary/' % (flowcell_id, cycle_name)
359     return url
360
361 def make_result_link(flowcell_id, cycle_name, lane, eland_result_path):
362     if eland_result_path is None:
363         return ("", "", "")
364
365     result_type = get_eland_result_type(eland_result_path)
366     result_url = '/results/%s/%s/eland_result/%s' % (flowcell_id, cycle_name, lane)
367     result_label = 'eland %s' % (result_type,)
368     bed_url = None
369     if result_type == 'result':
370        bed_url_pattern = '/results/%s/%s/bedfile/%s'
371        bed_url = bed_url_pattern % (flowcell_id, cycle_name, lane)
372     
373     return (result_url, result_label, bed_url)
374
375 def _files(flowcell_id, lane):
376     """
377     Sets up available files for download
378     """
379     lane = int(lane)
380
381     flowcell_id, id = parse_flowcell_id(flowcell_id)
382     d = get_flowcell_result_dict(flowcell_id)
383     
384     if d is None:
385         return ''
386     
387     output = []
388     
389     # c_name == 'CN-M' (i.e. C1-33)
390     for c_name in d:
391         
392         if d[c_name]['summary'] is not None:
393             output.append('<a href="/results/%s/%s/summary/">summary(%s)</a>' \
394                           % (flowcell_id, c_name, c_name))
395         
396         erd = d[c_name]['eland_results']
397         if lane in erd:
398             result_type = get_eland_result_type(erd[lane])
399             result_url_pattern = '<a href="/results/%s/%s/eland_result/%s">eland %s(%s)</a>'
400             output.append(result_url_pattern % (flowcell_id, c_name, lane, result_type, c_name))
401             if result_type == 'result':
402                 bed_url_pattern = '<a href="/results/%s/%s/bedfile/%s">bedfile(%s)</a>'
403                 output.append(bed_url_pattern % (flowcell_id, c_name, lane, c_name))
404     
405     if len(output) == 0:
406         return ''
407     
408     return '(' + '|'.join(output) + ')'
409
410 def library_id_to_admin_url(request, lib_id):
411     lib = Library.objects.get(library_id=lib_id)
412     return HttpResponseRedirect('/admin/samples/library/%s' % (lib.id,))
413