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