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