1 from __future__ import absolute_import, print_function, unicode_literals
3 # Create your views here.
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_to_response, 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
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
29 LANE_LIST = [1, 2, 3, 4, 5, 6, 7, 8]
30 SAMPLES_CONTEXT_DEFAULTS = {
31 'app_name': 'Flowcell/Library Tracker',
32 'bcmagic': BarcodeMagicForm()
35 LOGGER = logging.getLogger(__name__)
38 def library(request, todo_only=False):
39 filters = {'hidden__exact': 0}
41 filters['lane'] = None
43 fcl = HTSChangeList(request, Library,
44 list_filter=['affiliations', 'library_species'],
45 search_fields=['id', 'library_name', 'amplified_from_sample__id'],
47 model_admin=LibraryOptions(Library, admin_site),
51 'library_list': fcl.result_list,
52 'title': 'Library Index',
53 'todo_only': todo_only}
55 t = get_template('samples/library_index.html')
56 c = RequestContext(request, context)
57 return HttpResponse(t.render(c))
60 def library_not_run(request):
61 return library(request, todo_only=True)
64 def library_to_flowcells(request, lib_id):
66 Display information about all the flowcells a library has been run on.
69 lib = Library.objects.get(id=lib_id)
71 raise Http404('Library %s does not exist' % (lib_id,))
74 flowcell_run_results = {} # aka flowcells we're looking at
75 for lane in lib.lane_set.all():
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))
83 lane_summary_list = []
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)
89 eland_results.extend(_make_eland_results(fc, lane_number, flowcell_run_results))
92 'page_name': 'Library Details',
94 'eland_results': eland_results,
95 'lane_summary_list': lane_summary_list,
97 context.update(SAMPLES_CONTEXT_DEFAULTS)
99 return render_to_response(
100 'samples/library_detail.html',
102 context_instance=RequestContext(request))
105 def summaryhtm_fc_cnm(request, flowcell_id, cnm):
107 returns a Summary.htm file if it exists.
109 fc_id, status = parse_flowcell_id(flowcell_id)
110 d = get_flowcell_result_dict(fc_id)
113 return HttpResponse('<b>Results for Flowcell %s not found.</b>' % (fc_id))
116 return HttpResponse('<b>Results for Flowcell %s; %s not found.</b>' % (fc_id, cnm))
118 summary_filepath = d[cnm]['summary']
120 if summary_filepath is None:
121 return HttpResponse('<b>Summary.htm for Flowcell %s; %s not found.</b>' % (fc_id, cnm))
123 f = open(summary_filepath, 'r')
125 return HttpResponse(f)
128 def result_fc_cnm_eland_lane(request, flowcell_id, cnm, lane):
130 returns an eland_file upon calling.
132 fc_id, status = parse_flowcell_id(flowcell_id)
133 d = get_flowcell_result_dict(fc_id)
136 return HttpResponse('<b>Results for Flowcell %s not found.</b>' % (fc_id))
139 return HttpResponse('<b>Results for Flowcell %s; %s not found.</b>' % (fc_id, cnm))
141 erd = d[cnm]['eland_results']
145 return HttpResponse('<b>Results for Flowcell %s; %s; lane %s not found.</b>' % (fc_id, cnm, lane))
149 #f = opener.autoopen(filepath, 'r')
150 # return HttpResponse(f, content_type="application/x-elandresult")
152 f = open(filepath, 'r')
153 return HttpResponse(f, content_type='application/x-bzip2')
156 def bedfile_fc_cnm_eland_lane_ucsc(request, fc_id, cnm, lane):
158 returns a bed file for a given flowcell, CN-M (i.e. C1-33), and lane (ucsc compatible)
160 return bedfile_fc_cnm_eland_lane(request, fc_id, cnm, lane, ucsc_compatible=True)
163 def bedfile_fc_cnm_eland_lane(request, flowcell_id, cnm, lane, ucsc_compatible=False):
165 returns a bed file for a given flowcell, CN-M (i.e. C1-33), and lane
167 fc_id, status = parse_flowcell_id(flowcell_id)
168 d = get_flowcell_result_dict(fc_id)
171 return HttpResponse('<b>Results for Flowcell %s not found.</b>' % (fc_id))
174 return HttpResponse('<b>Results for Flowcell %s; %s not found.</b>' % (fc_id, cnm))
176 erd = d[cnm]['eland_results']
180 return HttpResponse('<b>Results for Flowcell %s; %s; lane %s not found.</b>' % (fc_id, cnm, lane))
185 fi = opener.autoopen(filepath, 'r')
188 name, description = makebed.make_description(fc_id, lane)
190 bedgen = makebed.make_bed_from_eland_generator(fi, name, description)
193 return HttpResponse(bedgen)
195 return HttpResponse(bedgen, content_type="application/x-bedfile")
198 def _summary_stats(flowcell_id, lane_id, library_id):
200 Return the summary statistics for a given flowcell, lane, and end.
202 fc_id, status = parse_flowcell_id(flowcell_id)
203 fc_result_dict = get_flowcell_result_dict(fc_id)
208 if fc_result_dict is None:
209 err_list.append('Results for Flowcell %s not found.' % (fc_id))
210 return (summary_list, err_list)
212 for cycle_width in fc_result_dict:
213 xmlpath = fc_result_dict[cycle_width]['run_xml']
216 err_list.append('Run xml for Flowcell %s(%s) not found.' % (fc_id, cycle_width))
219 run = runfolder.load_pipeline_run_xml(xmlpath)
220 # skip if we don't have available metadata.
221 if run.gerald is None or run.gerald.summary is None:
224 gerald_summary = run.gerald.summary.lane_results
225 key = SampleKey(lane=lane_id, sample='s')
226 eland_results = list(run.gerald.eland_results.find_keys(key))
227 key = SampleKey(lane=lane_id, sample=library_id)
228 eland_results.extend(run.gerald.eland_results.find_keys(key))
229 for key in eland_results:
230 eland_summary = run.gerald.eland_results.results[key]
231 # add information to lane_summary
232 eland_summary.flowcell_id = flowcell_id
234 read = key.read-1 if key.read is not None else 0
236 eland_summary.clusters = gerald_summary[read][key.lane].cluster
237 except (IndexError, KeyError) as e:
238 eland_summary.clustes = None
239 eland_summary.cycle_width = cycle_width
240 if hasattr(eland_summary, 'genome_map'):
241 eland_summary.summarized_reads = runfolder.summarize_mapped_reads(
242 eland_summary.genome_map,
243 eland_summary.mapped_reads)
245 # grab some more information out of the flowcell db
246 flowcell = FlowCell.objects.get(flowcell_id=flowcell_id)
247 #pm_field = 'lane_%d_pM' % (lane_id)
248 lanes = flowcell.lane_set.filter(lane_number=lane_id)
249 eland_summary.flowcell = flowcell
250 eland_summary.lanes = lanes
252 summary_list.append(eland_summary)
254 #except Exception as e:
255 # summary_list.append("Summary report needs to be updated.")
256 # LOGGER.error("Exception: " + str(e))
258 return (summary_list, err_list)
261 def get_eland_result_type(pathname):
263 Guess the eland result file type from the filename
265 path, filename = os.path.split(pathname)
266 if 'extended' in filename:
268 elif 'multi' in filename:
270 elif 'result' in filename:
276 def _make_eland_results(flowcell_id, lane_number, interesting_flowcells):
277 fc_id, status = parse_flowcell_id(flowcell_id)
278 cur_fc = interesting_flowcells.get(fc_id, None)
282 flowcell = FlowCell.objects.get(flowcell_id=flowcell_id)
283 lanes = flowcell.lane_set.filter(lane_number=lane_number)
284 # Loop throw storage devices if a result has been archived
286 if cur_fc is not None:
287 for lts in flowcell.longtermstorage_set.all():
288 for sd in lts.storage_devices.all():
289 # Use barcode_id if it exists
290 if sd.barcode_id is not None and sd.barcode_id != '':
291 storage_id_list.append(sd.barcode_id)
294 storage_id_list.append(sd.uuid)
296 # Formatting for template use
297 if len(storage_id_list) == 0:
300 storage_ids = ', '.join(['<a href="/inventory/%s/">%s</a>' % (s, s) for s in storage_id_list])
303 for cycle in cur_fc.keys():
304 result_path = cur_fc[cycle]['eland_results'].get(lanes[0], None)
305 result_link = make_result_link(fc_id, cycle, lanes[0], result_path)
306 results.append({'flowcell_id': fc_id,
307 'flowcell': flowcell,
308 'run_date': flowcell.run_date,
311 'summary_url': make_summary_url(flowcell_id, cycle),
312 'result_url': result_link[0],
313 'result_label': result_link[1],
314 'bed_url': result_link[2],
315 'storage_ids': storage_ids})
319 def make_summary_url(flowcell_id, cycle_name):
320 url = '/results/%s/%s/summary/' % (flowcell_id, cycle_name)
324 def make_result_link(flowcell_id, cycle_name, lane, eland_result_path):
325 if eland_result_path is None:
328 result_type = get_eland_result_type(eland_result_path)
329 result_url = '/results/%s/%s/eland_result/%s' % (flowcell_id, cycle_name, lane)
330 result_label = 'eland %s' % (result_type,)
332 if result_type == 'result':
333 bed_url_pattern = '/results/%s/%s/bedfile/%s'
334 bed_url = bed_url_pattern % (flowcell_id, cycle_name, lane)
336 return (result_url, result_label, bed_url)
339 def _files(flowcell_id, lane):
341 Sets up available files for download
345 flowcell_id, id = parse_flowcell_id(flowcell_id)
346 d = get_flowcell_result_dict(flowcell_id)
353 # c_name == 'CN-M' (i.e. C1-33)
356 if d[c_name]['summary'] is not None:
357 output.append('<a href="/results/%s/%s/summary/">summary(%s)</a>' %
358 (flowcell_id, c_name, c_name))
360 erd = d[c_name]['eland_results']
362 result_type = get_eland_result_type(erd[lane])
363 result_url_pattern = '<a href="/results/%s/%s/eland_result/%s">eland %s(%s)</a>'
364 output.append(result_url_pattern % (flowcell_id, c_name, lane, result_type, c_name))
365 if result_type == 'result':
366 bed_url_pattern = '<a href="/results/%s/%s/bedfile/%s">bedfile(%s)</a>'
367 output.append(bed_url_pattern % (flowcell_id, c_name, lane, c_name))
372 return '(' + '|'.join(output) + ')'
375 def library_id_to_admin_url(request, lib_id):
376 lib = Library.objects.get(id=lib_id)
377 return HttpResponseRedirect('/admin/samples/library/%s' % (lib.id,))
380 def library_dict(library_id):
382 Given a library id construct a dictionary containing important information
383 return None if nothing was found
386 lib = Library.objects.get(id=library_id)
387 except Library.DoesNotExist as e:
390 #lane_info = lane_information(lib.lane_set)
392 for lane in lib.lane_set.all():
393 lane_info.append({'flowcell': lane.flowcell.flowcell_id,
394 'lane_number': lane.lane_number,
396 'paired_end': lane.flowcell.paired_end,
397 'read_length': lane.flowcell.read_length,
398 'status_code': lane.status,
399 'status': LANE_STATUS_MAP[lane.status]})
403 # 'aligned_reads': lib.aligned_reads,
404 #'amplified_into_sample': lib.amplified_into_sample, # into is a colleciton...
405 #'amplified_from_sample_id': lib.amplified_from_sample,
406 #'antibody_name': lib.antibody_name(), # we have no antibodies.
407 'antibody_id': lib.antibody_id,
408 'cell_line_id': lib.cell_line_id,
409 'cell_line': str_or_none(lib.cell_line),
410 'experiment_type': lib.experiment_type.name,
411 'experiment_type_id': lib.experiment_type_id,
412 'gel_cut_size': lib.gel_cut_size,
413 'hidden': lib.hidden,
415 'insert_size': lib.insert_size,
416 'lane_set': lane_info,
417 'library_id': lib.id,
418 'library_name': lib.library_name,
419 'library_species': lib.library_species.scientific_name,
420 'library_species_id': lib.library_species_id,
421 #'library_type': lib.library_type.name,
422 'library_type_id': lib.library_type_id,
423 'made_for': lib.made_for,
424 'made_by': lib.made_by,
426 'replicate': lib.replicate,
427 'stopping_point': lib.stopping_point,
428 'successful_pM': str_or_none(lib.successful_pM),
429 'undiluted_concentration': str_or_none(lib.undiluted_concentration)
431 if lib.library_type_id is None:
432 info['library_type'] = None
434 info['library_type'] = lib.library_type.name
439 def library_json(request, library_id):
441 Return a json formatted library dictionary
443 require_api_key(request)
444 # what validation should we do on library_id?
446 lib = library_dict(library_id)
450 lib_json = json.dumps({'result': lib})
451 return HttpResponse(lib_json, content_type='application/json')
455 def species_json(request, species_id):
457 Return information about a species.
462 def species(request, species_id):
463 species = get_object_or_404(Species, id=species_id)
465 context = RequestContext(request,
466 {'species': species})
468 return render_to_response("samples/species_detail.html", context)
471 def antibodies(request):
472 context = RequestContext(request,
473 {'antibodies': Antibody.objects.order_by('antigene')})
474 return render_to_response("samples/antibody_index.html", context)
478 def user_profile(request):
480 Information about the user
483 'page_name': 'User Profile',
485 # 'bcmagic': BarcodeMagicForm(),
486 # 'select': 'settings',
488 context.update(SAMPLES_CONTEXT_DEFAULTS)
489 return render_to_response('registration/profile.html', context,
490 context_instance=RequestContext(request))