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