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