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