a6286d7313072c706ed2e8225e3fd398d28dd290
[htsworkflow.git] / htsworkflow / frontend / samples / views.py
1 # Create your views here.
2 import StringIO
3 import logging
4 import os
5 import sys
6
7 try:
8     import json
9 except ImportError, e:
10     import simplejson as json
11
12 from htsworkflow.frontend.auth import require_api_key
13 from htsworkflow.frontend.experiments.models import FlowCell, Lane, LANE_STATUS_MAP
14 from htsworkflow.frontend.samples.changelist import ChangeList
15 from htsworkflow.frontend.samples.models import Library, HTSUser
16 from htsworkflow.frontend.samples.results import get_flowcell_result_dict, parse_flowcell_id
17 from htsworkflow.frontend.bcmagic.forms import BarcodeMagicForm
18 from htsworkflow.pipelines.runfolder import load_pipeline_run_xml
19 from htsworkflow.pipelines import runfolder
20 from htsworkflow.pipelines.eland import ResultLane
21 from htsworkflow.frontend import settings
22 from htsworkflow.util.conversion import unicode_or_none
23 from htsworkflow.util import makebed
24 from htsworkflow.util import opener
25
26
27 from django.core.exceptions import ObjectDoesNotExist
28 from django.http import HttpResponse, HttpResponseRedirect, Http404
29 from django.shortcuts import render_to_response
30 from django.template import RequestContext
31 from django.template.loader import get_template
32 from django.contrib.auth.decorators import login_required
33
34 LANE_LIST = [1,2,3,4,5,6,7,8]
35 SAMPLES_CONTEXT_DEFAULTS = {
36     'app_name': 'Flowcell/Library Tracker',
37     'bcmagic': BarcodeMagicForm()
38 }
39
40 def count_lanes(lane_set):
41     single = 0
42     paired = 1
43     short_read = 0
44     medium_read = 1
45     long_read = 2
46     counts = [[0,0,0,],[0,0,0]]
47     
48     for lane in lane_set.all():
49         if lane.flowcell.paired_end:
50             lane_type = paired
51         else:
52             lane_type = single
53         if lane.flowcell.read_length < 40:
54             read_type = short_read
55         elif lane.flowcell.read_length < 100:
56             read_type = medium_read
57         else:
58             read_type = long_read
59         counts[lane_type][read_type] += 1
60         
61     return counts
62
63 def create_library_context(cl):
64     """
65      Create a list of libraries that includes how many lanes were run
66     """
67     records = []
68     #for lib in library_items.object_list:
69     for lib in cl.result_list:
70        summary = {}
71        summary['library_id'] = lib.id
72        summary['library_name'] = lib.library_name
73        summary['species_name' ] = lib.library_species.scientific_name
74        if lib.amplified_from_sample is not None:
75            summary['amplified_from'] = lib.amplified_from_sample.id
76        else:
77            summary['amplified_from'] = ''
78        lanes_run = count_lanes(lib.lane_set)
79        # suppress zeros
80        for row in xrange(len(lanes_run)):
81            for col in xrange(len(lanes_run[row])):
82                if lanes_run[row][col] == 0:
83                    lanes_run[row][col] = ''
84        summary['lanes_run'] = lanes_run
85        summary['is_archived'] = lib.is_archived()
86        records.append(summary)
87     cl.result_count = unicode(cl.paginator._count)
88     return {'library_list': records }
89
90 def library(request):
91     # build changelist
92     fcl = ChangeList(request, Library,
93         list_filter=['affiliations', 'library_species'],
94         search_fields=['id', 'library_name', 'amplified_from_sample__id'],
95         list_per_page=200,
96         queryset=Library.objects.filter(hidden__exact=0)
97     )
98
99     context = { 'cl': fcl, 'title': 'Library Index'}
100     context.update(create_library_context(fcl))
101     t = get_template('samples/library_index.html')
102     c = RequestContext(request, context)
103     return HttpResponse( t.render(c) )
104     
105
106 def library_to_flowcells(request, lib_id):
107     """
108     Display information about all the flowcells a library has been run on.
109     """
110     
111     try:
112       lib = Library.objects.get(id=lib_id)
113     except:
114       return HttpResponse("Library %s does not exist" % (lib_id))
115    
116     flowcell_list = []
117     flowcell_run_results = {} # aka flowcells we're looking at
118     for lane in lib.lane_set.all():
119         fc = lane.flowcell
120         flowcell_id, id = parse_flowcell_id(fc.flowcell_id)
121         if flowcell_id not in flowcell_run_results:
122             flowcell_run_results[flowcell_id] = get_flowcell_result_dict(flowcell_id)
123         flowcell_list.append((fc.flowcell_id, lane.lane_number))
124
125     flowcell_list.sort()
126     lane_summary_list = []
127     eland_results = []
128     for fc, lane_number in flowcell_list:
129         lane_summary, err_list = _summary_stats(fc, lane_number)
130
131         eland_results.extend(_make_eland_results(fc, lane_number, flowcell_run_results))
132         lane_summary_list.extend(lane_summary)
133
134     context = {
135         'page_name': 'Library Details',
136         'lib': lib,
137         'eland_results': eland_results,
138         'lane_summary_list': lane_summary_list,
139     }
140     context.update(SAMPLES_CONTEXT_DEFAULTS)
141
142     return render_to_response(
143         'samples/library_detail.html',
144         context,
145         context_instance = RequestContext(request))
146
147 def lanes_for(request, username=None):
148     """
149     Generate a report of recent activity for a user
150     """
151     query = {}
152     if username is not None:
153         user = HTSUser.objects.get(username=username)
154         query.update({'library__affiliations__users__id':user.id})
155     fcl = ChangeList(request, Lane,
156         list_filter=[],
157         search_fields=['flowcell__flowcell_id', 'library__id', 'library__library_name'],
158         list_per_page=200,
159         queryset=Lane.objects.filter(**query)
160     )
161
162     context = { 'lanes': fcl, 'title': 'Lane Index'}
163
164     return render_to_response(
165         'samples/lanes_for.html',
166         context,
167         context_instance = RequestContext(request)
168     )
169           
170     
171 def summaryhtm_fc_cnm(request, flowcell_id, cnm):
172     """
173     returns a Summary.htm file if it exists.
174     """
175     fc_id, status = parse_flowcell_id(flowcell_id)
176     d = get_flowcell_result_dict(fc_id)
177     
178     if d is None:
179         return HttpResponse('<b>Results for Flowcell %s not found.</b>' % (fc_id))
180     
181     if cnm not in d:
182         return HttpResponse('<b>Results for Flowcell %s; %s not found.</b>' % (fc_id, cnm))
183     
184     summary_filepath = d[cnm]['summary']
185     
186     if summary_filepath is None:
187         return HttpResponse('<b>Summary.htm for Flowcell %s; %s not found.</b>' % (fc_id, cnm))
188     
189     f = open(summary_filepath, 'r')
190     
191     return HttpResponse(f)
192
193
194 def result_fc_cnm_eland_lane(request, flowcell_id, cnm, lane):
195     """
196     returns an eland_file upon calling.
197     """
198     fc_id, status = parse_flowcell_id(flowcell_id)
199     d = get_flowcell_result_dict(fc_id)
200     
201     if d is None:
202         return HttpResponse('<b>Results for Flowcell %s not found.</b>' % (fc_id))
203     
204     if cnm not in d:
205         return HttpResponse('<b>Results for Flowcell %s; %s not found.</b>' % (fc_id, cnm))
206     
207     erd = d[cnm]['eland_results']
208     lane = int(lane)
209     
210     if lane not in erd:
211         return HttpResponse('<b>Results for Flowcell %s; %s; lane %s not found.</b>' % (fc_id, cnm, lane))
212     
213     filepath = erd[lane]
214     
215     #f = opener.autoopen(filepath, 'r')
216     # return HttpResponse(f, mimetype="application/x-elandresult")
217
218     f = open(filepath, 'r')
219     return HttpResponse(f, mimetype='application/x-bzip2')
220     
221
222
223 def bedfile_fc_cnm_eland_lane_ucsc(request, fc_id, cnm, lane):
224     """
225     returns a bed file for a given flowcell, CN-M (i.e. C1-33), and lane (ucsc compatible)
226     """
227     return bedfile_fc_cnm_eland_lane(request, fc_id, cnm, lane, ucsc_compatible=True)
228
229
230 def bedfile_fc_cnm_eland_lane(request, flowcell_id, cnm, lane, ucsc_compatible=False):
231     """
232     returns a bed file for a given flowcell, CN-M (i.e. C1-33), and lane
233     """
234     fc_id, status = parse_flowcell_id(flowcell_id)
235     d = get_flowcell_result_dict(fc_id)
236     
237     if d is None:
238         return HttpResponse('<b>Results for Flowcell %s not found.</b>' % (fc_id))
239     
240     if cnm not in d:
241         return HttpResponse('<b>Results for Flowcell %s; %s not found.</b>' % (fc_id, cnm))
242     
243     erd = d[cnm]['eland_results']
244     lane = int(lane)
245     
246     if lane not in erd:
247         return HttpResponse('<b>Results for Flowcell %s; %s; lane %s not found.</b>' % (fc_id, cnm, lane))
248     
249     filepath = erd[lane]
250     
251     # Eland result file
252     fi = opener.autoopen(filepath, 'r')
253     # output memory file
254     
255     name, description = makebed.make_description( fc_id, lane )
256     
257     bedgen = makebed.make_bed_from_eland_generator(fi, name, description)
258     
259     if ucsc_compatible:
260         return HttpResponse(bedgen)
261     else:
262         return HttpResponse(bedgen, mimetype="application/x-bedfile")
263
264
265 def _summary_stats(flowcell_id, lane_id):
266     """
267     Return the summary statistics for a given flowcell, lane, and end.
268     """
269     fc_id, status = parse_flowcell_id(flowcell_id)
270     fc_result_dict = get_flowcell_result_dict(fc_id)
271
272     summary_list = []
273     err_list = []
274     
275     if fc_result_dict is None:
276         err_list.append('Results for Flowcell %s not found.' % (fc_id))
277         return (summary_list, err_list)
278
279     for cycle_width in fc_result_dict:
280         xmlpath = fc_result_dict[cycle_width]['run_xml']
281         
282         if xmlpath is None:
283             err_list.append('Run xml for Flowcell %s(%s) not found.' % (fc_id, cycle_width))
284             continue
285         
286         run = load_pipeline_run_xml(xmlpath)
287         gerald_summary = run.gerald.summary.lane_results
288         for end in range(len(gerald_summary)):
289             end_summary = run.gerald.eland_results.results[end]
290             if end_summary.has_key(lane_id):
291                 eland_summary = run.gerald.eland_results.results[end][lane_id]
292             else:
293                 eland_summary = ResultLane(lane_id=lane_id, end=end)
294             # add information to lane_summary
295             eland_summary.flowcell_id = flowcell_id
296             if len(gerald_summary) > end and gerald_summary[end].has_key(lane_id):
297                 eland_summary.clusters = gerald_summary[end][lane_id].cluster
298             else:
299                 eland_summary.clusters = None
300             eland_summary.cycle_width = cycle_width
301             if hasattr(eland_summary, 'genome_map'):
302                 eland_summary.summarized_reads = runfolder.summarize_mapped_reads( 
303                                                    eland_summary.genome_map, 
304                                                    eland_summary.mapped_reads)
305
306             # grab some more information out of the flowcell db
307             flowcell = FlowCell.objects.get(flowcell_id=flowcell_id)
308             #pm_field = 'lane_%d_pM' % (lane_id)
309             lane_obj = flowcell.lane_set.get(lane_number=lane_id)
310             eland_summary.successful_pm = lane_obj.pM
311
312             summary_list.append(eland_summary)
313
314         #except Exception, e:
315         #    summary_list.append("Summary report needs to be updated.")
316         #    logging.error("Exception: " + str(e))
317     
318     return (summary_list, err_list)
319
320 def _summary_stats_old(flowcell_id, lane):
321     """
322     return a dictionary of summary stats for a given flowcell_id & lane.
323     """
324     fc_id, status = parse_flowcell_id(flowcell_id)
325     fc_result_dict = get_flowcell_result_dict(fc_id)
326     
327     dict_list = []
328     err_list = []
329     summary_list = []
330     
331     if fc_result_dict is None:
332         err_list.append('Results for Flowcell %s not found.' % (fc_id))
333         return (dict_list, err_list, summary_list)
334     
335     for cnm in fc_result_dict:
336     
337         xmlpath = fc_result_dict[cnm]['run_xml']
338         
339         if xmlpath is None:
340             err_list.append('Run xml for Flowcell %s(%s) not found.' % (fc_id, cnm))
341             continue
342         
343         tree = ElementTree.parse(xmlpath).getroot()
344         results = runfolder.PipelineRun(pathname='', xml=tree)
345         try:
346             lane_report = runfolder.summarize_lane(results.gerald, lane)
347             summary_list.append(os.linesep.join(lane_report))
348         except Exception, e:
349             summary_list.append("Summary report needs to be updated.")
350             logging.error("Exception: " + str(e))
351        
352         print >>sys.stderr, "----------------------------------"
353         print >>sys.stderr, "-- DOES NOT SUPPORT PAIRED END ---"
354         print >>sys.stderr, "----------------------------------"
355         lane_results = results.gerald.summary[0][lane]
356         lrs = lane_results
357         
358         d = {}
359         
360         d['average_alignment_score'] = lrs.average_alignment_score
361         d['average_first_cycle_intensity'] = lrs.average_first_cycle_intensity
362         d['cluster'] = lrs.cluster
363         d['lane'] = lrs.lane
364         d['flowcell'] = flowcell_id
365         d['cnm'] = cnm
366         d['percent_error_rate'] = lrs.percent_error_rate
367         d['percent_intensity_after_20_cycles'] = lrs.percent_intensity_after_20_cycles
368         d['percent_pass_filter_align'] = lrs.percent_pass_filter_align
369         d['percent_pass_filter_clusters'] = lrs.percent_pass_filter_clusters
370         
371         #FIXME: function finished, but need to take advantage of
372         #   may need to take in a list of lanes so we only have to
373         #   load the xml file once per flowcell rather than once
374         #   per lane.
375         dict_list.append(d)
376     
377     return (dict_list, err_list, summary_list)
378     
379     
380 def get_eland_result_type(pathname):
381     """
382     Guess the eland result file type from the filename
383     """
384     path, filename = os.path.split(pathname)
385     if 'extended' in filename:
386         return 'extended'
387     elif 'multi' in filename:
388         return 'multi'
389     elif 'result' in filename:
390         return 'result'
391     else:
392         return 'unknown'
393
394 def _make_eland_results(flowcell_id, lane, interesting_flowcells):
395     fc_id, status = parse_flowcell_id(flowcell_id)
396     cur_fc = interesting_flowcells.get(fc_id, None)
397     if cur_fc is None:
398       return []
399
400     flowcell = FlowCell.objects.get(flowcell_id=flowcell_id)
401     # Loop throw storage devices if a result has been archived
402     storage_id_list = []
403     if cur_fc is not None:
404         for lts in flowcell.longtermstorage_set.all():
405             for sd in lts.storage_devices.all():
406                 # Use barcode_id if it exists
407                 if sd.barcode_id is not None and sd.barcode_id != '':
408                     storage_id_list.append(sd.barcode_id)
409                 # Otherwise use UUID
410                 else:
411                     storage_id_list.append(sd.uuid)
412         
413     # Formatting for template use
414     if len(storage_id_list) == 0:
415         storage_ids = None
416     else:
417         storage_ids = ', '.join([ '<a href="/inventory/%s/">%s</a>' % (s,s) for s in storage_id_list ])
418
419     results = []
420     for cycle in cur_fc.keys():
421         result_path = cur_fc[cycle]['eland_results'].get(lane, None)
422         result_link = make_result_link(fc_id, cycle, lane, result_path)
423         results.append({'flowcell_id': fc_id,
424                         'run_date': flowcell.run_date,
425                         'cycle': cycle, 
426                         'lane': lane, 
427                         'summary_url': make_summary_url(flowcell_id, cycle),
428                         'result_url': result_link[0],
429                         'result_label': result_link[1],
430                         'bed_url': result_link[2],
431                         'storage_ids': storage_ids
432         })
433     return results
434
435 def make_summary_url(flowcell_id, cycle_name):
436     url = '/results/%s/%s/summary/' % (flowcell_id, cycle_name)
437     return url
438
439 def make_result_link(flowcell_id, cycle_name, lane, eland_result_path):
440     if eland_result_path is None:
441         return ("", "", "")
442
443     result_type = get_eland_result_type(eland_result_path)
444     result_url = '/results/%s/%s/eland_result/%s' % (flowcell_id, cycle_name, lane)
445     result_label = 'eland %s' % (result_type,)
446     bed_url = None
447     if result_type == 'result':
448        bed_url_pattern = '/results/%s/%s/bedfile/%s'
449        bed_url = bed_url_pattern % (flowcell_id, cycle_name, lane)
450     
451     return (result_url, result_label, bed_url)
452
453 def _files(flowcell_id, lane):
454     """
455     Sets up available files for download
456     """
457     lane = int(lane)
458
459     flowcell_id, id = parse_flowcell_id(flowcell_id)
460     d = get_flowcell_result_dict(flowcell_id)
461     
462     if d is None:
463         return ''
464     
465     output = []
466     
467     # c_name == 'CN-M' (i.e. C1-33)
468     for c_name in d:
469         
470         if d[c_name]['summary'] is not None:
471             output.append('<a href="/results/%s/%s/summary/">summary(%s)</a>' \
472                           % (flowcell_id, c_name, c_name))
473         
474         erd = d[c_name]['eland_results']
475         if lane in erd:
476             result_type = get_eland_result_type(erd[lane])
477             result_url_pattern = '<a href="/results/%s/%s/eland_result/%s">eland %s(%s)</a>'
478             output.append(result_url_pattern % (flowcell_id, c_name, lane, result_type, c_name))
479             if result_type == 'result':
480                 bed_url_pattern = '<a href="/results/%s/%s/bedfile/%s">bedfile(%s)</a>'
481                 output.append(bed_url_pattern % (flowcell_id, c_name, lane, c_name))
482     
483     if len(output) == 0:
484         return ''
485     
486     return '(' + '|'.join(output) + ')'
487
488 def library_id_to_admin_url(request, lib_id):
489     lib = Library.objects.get(id=lib_id)
490     return HttpResponseRedirect('/admin/samples/library/%s' % (lib.id,))
491
492 def library_dict(library_id):
493     """
494     Given a library id construct a dictionary containing important information
495     return None if nothing was found
496     """
497     try:
498         lib = Library.objects.get(id = library_id)
499     except Library.DoesNotExist, e:
500         return None
501
502     #lane_info = lane_information(lib.lane_set)
503     lane_info = []
504     for lane in lib.lane_set.all():
505         lane_info.append( {'flowcell':lane.flowcell.flowcell_id,
506                            'lane_number': lane.lane_number,
507                            'paired_end': lane.flowcell.paired_end,
508                            'read_length': lane.flowcell.read_length,
509                            'status_code': lane.status,
510                            'status': LANE_STATUS_MAP[lane.status]} )
511         
512     info = {
513         # 'affiliations'?
514         # 'aligned_reads': lib.aligned_reads,
515         #'amplified_into_sample': lib.amplified_into_sample, # into is a colleciton...
516         #'amplified_from_sample_id': lib.amplified_from_sample, 
517         #'antibody_name': lib.antibody_name(), # we have no antibodies.
518         'antibody_id': lib.antibody_id,
519         'cell_line_id': lib.cell_line_id,
520         'cell_line': unicode_or_none(lib.cell_line),
521         'experiment_type': lib.experiment_type.name,
522         'experiment_type_id': lib.experiment_type_id,
523         'gel_cut_size': lib.gel_cut_size,
524         'hidden': lib.hidden,
525         'id': lib.id,
526         'insert_size': lib.insert_size,
527         'lane_set': lane_info,
528         'library_id': lib.id,
529         'library_name': lib.library_name,
530         'library_species': lib.library_species.scientific_name,
531         'library_species_id': lib.library_species_id,
532         #'library_type': lib.library_type.name,
533         'library_type_id': lib.library_type_id,
534         'made_for': lib.made_for,
535         'made_by': lib.made_by,
536         'notes': lib.notes,
537         'replicate': lib.replicate,
538         'stopping_point': lib.stopping_point,
539         'successful_pM': unicode_or_none(lib.successful_pM),
540         'undiluted_concentration': unicode_or_none(lib.undiluted_concentration)
541         }
542     if lib.library_type_id is None:
543         info['library_type'] = None
544     else:
545         info['library_type'] = lib.library_type.name
546     return info
547
548 def library_json(request, library_id):
549     """
550     Return a json formatted library dictionary
551     """
552     require_api_key(request)
553     # what validation should we do on library_id?
554     
555     lib = library_dict(library_id)
556     if lib is None:
557         raise Http404
558
559     lib_json = json.dumps(lib)
560     return HttpResponse(lib_json, mimetype='application/json')
561
562 def species_json(request, species_id):
563     """
564     Return information about a species.
565     """
566     raise Http404
567
568 @login_required
569 def user_profile(request):
570     """
571     Information about the user
572     """
573     context = {
574                 'page_name': 'User Profile',
575                 'media': '',
576                 #'bcmagic': BarcodeMagicForm(),
577                 #'select': 'settings',
578             }
579     context.update(SAMPLES_CONTEXT_DEFAULTS)
580     return render_to_response('registration/profile.html', context,
581                               context_instance=RequestContext(request))
582