1 from __future__ import absolute_import, print_function, unicode_literals
3 # Create your views here.
8 from django.views.decorators.csrf import csrf_exempt
9 from django.http import HttpResponse, HttpResponseRedirect, Http404
10 from django.shortcuts import render_to_response, get_object_or_404
11 from django.template import RequestContext
12 from django.template.loader import get_template
13 from django.contrib.auth.decorators import login_required
15 from htsworkflow.auth import require_api_key
16 from experiments.models import FlowCell, LANE_STATUS_MAP
17 from .changelist import HTSChangeList
18 from .models import Antibody, Library, Species
19 from .admin import LibraryOptions
20 from .results import get_flowcell_result_dict
21 from bcmagic.forms import BarcodeMagicForm
22 from htsworkflow.pipelines import runfolder
23 from htsworkflow.pipelines.samplekey import SampleKey
24 from htsworkflow.util.conversion import str_or_none, parse_flowcell_id
25 from htsworkflow.util import makebed
26 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 count_lanes(lane_set):
44 counts = [[0, 0, 0], [0, 0, 0]]
46 for lane in lane_set.all():
47 if lane.flowcell.paired_end:
51 if lane.flowcell.read_length < 40:
52 read_type = short_read
53 elif lane.flowcell.read_length < 100:
54 read_type = medium_read
57 counts[lane_type][read_type] += 1
62 def create_library_context(cl):
64 Create a list of libraries that includes how many lanes were run
67 #for lib in library_items.object_list:
68 for lib in cl.result_list:
70 summary['library'] = lib
71 summary['library_id'] = lib.id
72 summary['library_name'] = lib.library_name
73 summary['species_name'] = lib.library_species.scientific_name
74 if lib.amplified_from_sample is not None:
75 summary['amplified_from'] = lib.amplified_from_sample.id
77 summary['amplified_from'] = ''
78 lanes_run = count_lanes(lib.lane_set)
80 for row_index, row in enumerate(lanes_run):
81 for col_index, cell in enumerate(row):
82 if lanes_run[row_index][col_index] == 0:
83 lanes_run[row_index][col_index] = ''
84 summary['lanes_run'] = lanes_run
85 summary['is_archived'] = lib.is_archived()
86 records.append(summary)
87 cl.result_count = str(cl.paginator._count)
88 return {'library_list': records}
91 def library(request, todo_only=False):
92 queryset = Library.objects.filter(hidden__exact=0)
93 filters = {'hidden__exact': 0}
95 filters['lane'] = None
97 fcl = HTSChangeList(request, Library,
98 list_filter=['affiliations', 'library_species'],
99 search_fields=['id', 'library_name', 'amplified_from_sample__id'],
101 model_admin=LibraryOptions(Library, None),
102 extra_filters=filters
105 context = {'cl': fcl, 'title': 'Library Index', 'todo_only': todo_only}
106 context.update(create_library_context(fcl))
107 t = get_template('samples/library_index.html')
108 c = RequestContext(request, context)
109 return HttpResponse(t.render(c))
112 def library_not_run(request):
113 return library(request, todo_only=True)
116 def library_to_flowcells(request, lib_id):
118 Display information about all the flowcells a library has been run on.
121 lib = Library.objects.get(id=lib_id)
123 raise Http404('Library %s does not exist' % (lib_id,))
126 flowcell_run_results = {} # aka flowcells we're looking at
127 for lane in lib.lane_set.all():
129 flowcell_id, id = parse_flowcell_id(fc.flowcell_id)
130 if flowcell_id not in flowcell_run_results:
131 flowcell_run_results[flowcell_id] = get_flowcell_result_dict(flowcell_id)
132 flowcell_list.append((fc.flowcell_id, lane.lane_number))
135 lane_summary_list = []
137 for fc, lane_number in flowcell_list:
138 lane_summary, err_list = _summary_stats(fc, lane_number, lib_id)
139 lane_summary_list.extend(lane_summary)
141 eland_results.extend(_make_eland_results(fc, lane_number, flowcell_run_results))
144 'page_name': 'Library Details',
146 'eland_results': eland_results,
147 'lane_summary_list': lane_summary_list,
149 context.update(SAMPLES_CONTEXT_DEFAULTS)
151 return render_to_response(
152 'samples/library_detail.html',
154 context_instance=RequestContext(request))
157 def summaryhtm_fc_cnm(request, flowcell_id, cnm):
159 returns a Summary.htm file if it exists.
161 fc_id, status = parse_flowcell_id(flowcell_id)
162 d = get_flowcell_result_dict(fc_id)
165 return HttpResponse('<b>Results for Flowcell %s not found.</b>' % (fc_id))
168 return HttpResponse('<b>Results for Flowcell %s; %s not found.</b>' % (fc_id, cnm))
170 summary_filepath = d[cnm]['summary']
172 if summary_filepath is None:
173 return HttpResponse('<b>Summary.htm for Flowcell %s; %s not found.</b>' % (fc_id, cnm))
175 f = open(summary_filepath, 'r')
177 return HttpResponse(f)
180 def result_fc_cnm_eland_lane(request, flowcell_id, cnm, lane):
182 returns an eland_file upon calling.
184 fc_id, status = parse_flowcell_id(flowcell_id)
185 d = get_flowcell_result_dict(fc_id)
188 return HttpResponse('<b>Results for Flowcell %s not found.</b>' % (fc_id))
191 return HttpResponse('<b>Results for Flowcell %s; %s not found.</b>' % (fc_id, cnm))
193 erd = d[cnm]['eland_results']
197 return HttpResponse('<b>Results for Flowcell %s; %s; lane %s not found.</b>' % (fc_id, cnm, lane))
201 #f = opener.autoopen(filepath, 'r')
202 # return HttpResponse(f, content_type="application/x-elandresult")
204 f = open(filepath, 'r')
205 return HttpResponse(f, content_type='application/x-bzip2')
208 def bedfile_fc_cnm_eland_lane_ucsc(request, fc_id, cnm, lane):
210 returns a bed file for a given flowcell, CN-M (i.e. C1-33), and lane (ucsc compatible)
212 return bedfile_fc_cnm_eland_lane(request, fc_id, cnm, lane, ucsc_compatible=True)
215 def bedfile_fc_cnm_eland_lane(request, flowcell_id, cnm, lane, ucsc_compatible=False):
217 returns a bed file for a given flowcell, CN-M (i.e. C1-33), and lane
219 fc_id, status = parse_flowcell_id(flowcell_id)
220 d = get_flowcell_result_dict(fc_id)
223 return HttpResponse('<b>Results for Flowcell %s not found.</b>' % (fc_id))
226 return HttpResponse('<b>Results for Flowcell %s; %s not found.</b>' % (fc_id, cnm))
228 erd = d[cnm]['eland_results']
232 return HttpResponse('<b>Results for Flowcell %s; %s; lane %s not found.</b>' % (fc_id, cnm, lane))
237 fi = opener.autoopen(filepath, 'r')
240 name, description = makebed.make_description(fc_id, lane)
242 bedgen = makebed.make_bed_from_eland_generator(fi, name, description)
245 return HttpResponse(bedgen)
247 return HttpResponse(bedgen, content_type="application/x-bedfile")
250 def _summary_stats(flowcell_id, lane_id, library_id):
252 Return the summary statistics for a given flowcell, lane, and end.
254 fc_id, status = parse_flowcell_id(flowcell_id)
255 fc_result_dict = get_flowcell_result_dict(fc_id)
260 if fc_result_dict is None:
261 err_list.append('Results for Flowcell %s not found.' % (fc_id))
262 return (summary_list, err_list)
264 for cycle_width in fc_result_dict:
265 xmlpath = fc_result_dict[cycle_width]['run_xml']
268 err_list.append('Run xml for Flowcell %s(%s) not found.' % (fc_id, cycle_width))
271 run = runfolder.load_pipeline_run_xml(xmlpath)
272 # skip if we don't have available metadata.
273 if run.gerald is None or run.gerald.summary is None:
276 gerald_summary = run.gerald.summary.lane_results
277 key = SampleKey(lane=lane_id, sample='s')
278 eland_results = list(run.gerald.eland_results.find_keys(key))
279 key = SampleKey(lane=lane_id, sample=library_id)
280 eland_results.extend(run.gerald.eland_results.find_keys(key))
281 for key in eland_results:
282 eland_summary = run.gerald.eland_results.results[key]
283 # add information to lane_summary
284 eland_summary.flowcell_id = flowcell_id
286 read = key.read-1 if key.read is not None else 0
288 eland_summary.clusters = gerald_summary[read][key.lane].cluster
289 except (IndexError, KeyError) as e:
290 eland_summary.clustes = None
291 eland_summary.cycle_width = cycle_width
292 if hasattr(eland_summary, 'genome_map'):
293 eland_summary.summarized_reads = runfolder.summarize_mapped_reads(
294 eland_summary.genome_map,
295 eland_summary.mapped_reads)
297 # grab some more information out of the flowcell db
298 flowcell = FlowCell.objects.get(flowcell_id=flowcell_id)
299 #pm_field = 'lane_%d_pM' % (lane_id)
300 lanes = flowcell.lane_set.filter(lane_number=lane_id)
301 eland_summary.flowcell = flowcell
302 eland_summary.lanes = lanes
304 summary_list.append(eland_summary)
306 #except Exception as e:
307 # summary_list.append("Summary report needs to be updated.")
308 # LOGGER.error("Exception: " + str(e))
310 return (summary_list, err_list)
313 def get_eland_result_type(pathname):
315 Guess the eland result file type from the filename
317 path, filename = os.path.split(pathname)
318 if 'extended' in filename:
320 elif 'multi' in filename:
322 elif 'result' in filename:
328 def _make_eland_results(flowcell_id, lane_number, interesting_flowcells):
329 fc_id, status = parse_flowcell_id(flowcell_id)
330 cur_fc = interesting_flowcells.get(fc_id, None)
334 flowcell = FlowCell.objects.get(flowcell_id=flowcell_id)
335 lanes = flowcell.lane_set.filter(lane_number=lane_number)
336 # Loop throw storage devices if a result has been archived
338 if cur_fc is not None:
339 for lts in flowcell.longtermstorage_set.all():
340 for sd in lts.storage_devices.all():
341 # Use barcode_id if it exists
342 if sd.barcode_id is not None and sd.barcode_id != '':
343 storage_id_list.append(sd.barcode_id)
346 storage_id_list.append(sd.uuid)
348 # Formatting for template use
349 if len(storage_id_list) == 0:
352 storage_ids = ', '.join(['<a href="/inventory/%s/">%s</a>' % (s, s) for s in storage_id_list])
355 for cycle in cur_fc.keys():
356 result_path = cur_fc[cycle]['eland_results'].get(lanes[0], None)
357 result_link = make_result_link(fc_id, cycle, lanes[0], result_path)
358 results.append({'flowcell_id': fc_id,
359 'flowcell': flowcell,
360 'run_date': flowcell.run_date,
363 'summary_url': make_summary_url(flowcell_id, cycle),
364 'result_url': result_link[0],
365 'result_label': result_link[1],
366 'bed_url': result_link[2],
367 'storage_ids': storage_ids})
371 def make_summary_url(flowcell_id, cycle_name):
372 url = '/results/%s/%s/summary/' % (flowcell_id, cycle_name)
376 def make_result_link(flowcell_id, cycle_name, lane, eland_result_path):
377 if eland_result_path is None:
380 result_type = get_eland_result_type(eland_result_path)
381 result_url = '/results/%s/%s/eland_result/%s' % (flowcell_id, cycle_name, lane)
382 result_label = 'eland %s' % (result_type,)
384 if result_type == 'result':
385 bed_url_pattern = '/results/%s/%s/bedfile/%s'
386 bed_url = bed_url_pattern % (flowcell_id, cycle_name, lane)
388 return (result_url, result_label, bed_url)
391 def _files(flowcell_id, lane):
393 Sets up available files for download
397 flowcell_id, id = parse_flowcell_id(flowcell_id)
398 d = get_flowcell_result_dict(flowcell_id)
405 # c_name == 'CN-M' (i.e. C1-33)
408 if d[c_name]['summary'] is not None:
409 output.append('<a href="/results/%s/%s/summary/">summary(%s)</a>' %
410 (flowcell_id, c_name, c_name))
412 erd = d[c_name]['eland_results']
414 result_type = get_eland_result_type(erd[lane])
415 result_url_pattern = '<a href="/results/%s/%s/eland_result/%s">eland %s(%s)</a>'
416 output.append(result_url_pattern % (flowcell_id, c_name, lane, result_type, c_name))
417 if result_type == 'result':
418 bed_url_pattern = '<a href="/results/%s/%s/bedfile/%s">bedfile(%s)</a>'
419 output.append(bed_url_pattern % (flowcell_id, c_name, lane, c_name))
424 return '(' + '|'.join(output) + ')'
427 def library_id_to_admin_url(request, lib_id):
428 lib = Library.objects.get(id=lib_id)
429 return HttpResponseRedirect('/admin/samples/library/%s' % (lib.id,))
432 def library_dict(library_id):
434 Given a library id construct a dictionary containing important information
435 return None if nothing was found
438 lib = Library.objects.get(id=library_id)
439 except Library.DoesNotExist as e:
442 #lane_info = lane_information(lib.lane_set)
444 for lane in lib.lane_set.all():
445 lane_info.append({'flowcell': lane.flowcell.flowcell_id,
446 'lane_number': lane.lane_number,
448 'paired_end': lane.flowcell.paired_end,
449 'read_length': lane.flowcell.read_length,
450 'status_code': lane.status,
451 'status': LANE_STATUS_MAP[lane.status]})
455 # 'aligned_reads': lib.aligned_reads,
456 #'amplified_into_sample': lib.amplified_into_sample, # into is a colleciton...
457 #'amplified_from_sample_id': lib.amplified_from_sample,
458 #'antibody_name': lib.antibody_name(), # we have no antibodies.
459 'antibody_id': lib.antibody_id,
460 'cell_line_id': lib.cell_line_id,
461 'cell_line': str_or_none(lib.cell_line),
462 'experiment_type': lib.experiment_type.name,
463 'experiment_type_id': lib.experiment_type_id,
464 'gel_cut_size': lib.gel_cut_size,
465 'hidden': lib.hidden,
467 'insert_size': lib.insert_size,
468 'lane_set': lane_info,
469 'library_id': lib.id,
470 'library_name': lib.library_name,
471 'library_species': lib.library_species.scientific_name,
472 'library_species_id': lib.library_species_id,
473 #'library_type': lib.library_type.name,
474 'library_type_id': lib.library_type_id,
475 'made_for': lib.made_for,
476 'made_by': lib.made_by,
478 'replicate': lib.replicate,
479 'stopping_point': lib.stopping_point,
480 'successful_pM': str_or_none(lib.successful_pM),
481 'undiluted_concentration': str_or_none(lib.undiluted_concentration)
483 if lib.library_type_id is None:
484 info['library_type'] = None
486 info['library_type'] = lib.library_type.name
491 def library_json(request, library_id):
493 Return a json formatted library dictionary
495 require_api_key(request)
496 # what validation should we do on library_id?
498 lib = library_dict(library_id)
502 lib_json = json.dumps({'result': lib})
503 return HttpResponse(lib_json, content_type='application/json')
507 def species_json(request, species_id):
509 Return information about a species.
514 def species(request, species_id):
515 species = get_object_or_404(Species, id=species_id)
517 context = RequestContext(request,
518 {'species': species})
520 return render_to_response("samples/species_detail.html", context)
523 def antibodies(request):
524 context = RequestContext(request,
525 {'antibodies': Antibody.objects.order_by('antigene')})
526 return render_to_response("samples/antibody_index.html", context)
530 def user_profile(request):
532 Information about the user
535 'page_name': 'User Profile',
537 #'bcmagic': BarcodeMagicForm(),
538 #'select': 'settings',
540 context.update(SAMPLES_CONTEXT_DEFAULTS)
541 return render_to_response('registration/profile.html', context,
542 context_instance=RequestContext(request))