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