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