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