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
28 LANE_LIST = [1, 2, 3, 4, 5, 6, 7, 8]
29 SAMPLES_CONTEXT_DEFAULTS = {
30 'app_name': 'Flowcell/Library Tracker',
31 'bcmagic': BarcodeMagicForm()
34 LOGGER = logging.getLogger(__name__)
37 def library(request, todo_only=False):
38 #filters = {'hidden__exact': 0}
40 filters['lane'] = None
42 fcl = HTSChangeList(request, Library,
43 list_filter=['affiliations', 'library_species'],
44 search_fields=['id', 'library_name', 'amplified_from_sample__id'],
46 model_admin=LibraryOptions(Library, None),
50 'library_list': fcl.result_list,
51 'title': 'Library Index',
52 'todo_only': todo_only}
54 t = get_template('samples/library_index.html')
55 c = RequestContext(request, context)
56 return HttpResponse(t.render(c))
59 def library_not_run(request):
60 return library(request, todo_only=True)
63 def library_to_flowcells(request, lib_id):
65 Display information about all the flowcells a library has been run on.
68 lib = Library.objects.get(id=lib_id)
70 raise Http404('Library %s does not exist' % (lib_id,))
73 flowcell_run_results = {} # aka flowcells we're looking at
74 for lane in lib.lane_set.all():
76 flowcell_id, id = parse_flowcell_id(fc.flowcell_id)
77 if flowcell_id not in flowcell_run_results:
78 flowcell_run_results[flowcell_id] = get_flowcell_result_dict(flowcell_id)
79 flowcell_list.append((fc.flowcell_id, lane.lane_number))
82 lane_summary_list = []
84 for fc, lane_number in flowcell_list:
85 lane_summary, err_list = _summary_stats(fc, lane_number, lib_id)
86 lane_summary_list.extend(lane_summary)
88 eland_results.extend(_make_eland_results(fc, lane_number, flowcell_run_results))
91 'page_name': 'Library Details',
93 'eland_results': eland_results,
94 'lane_summary_list': lane_summary_list,
96 context.update(SAMPLES_CONTEXT_DEFAULTS)
98 return render_to_response(
99 'samples/library_detail.html',
101 context_instance=RequestContext(request))
104 def summaryhtm_fc_cnm(request, flowcell_id, cnm):
106 returns a Summary.htm file if it exists.
108 fc_id, status = parse_flowcell_id(flowcell_id)
109 d = get_flowcell_result_dict(fc_id)
112 return HttpResponse('<b>Results for Flowcell %s not found.</b>' % (fc_id))
115 return HttpResponse('<b>Results for Flowcell %s; %s not found.</b>' % (fc_id, cnm))
117 summary_filepath = d[cnm]['summary']
119 if summary_filepath is None:
120 return HttpResponse('<b>Summary.htm for Flowcell %s; %s not found.</b>' % (fc_id, cnm))
122 f = open(summary_filepath, 'r')
124 return HttpResponse(f)
127 def result_fc_cnm_eland_lane(request, flowcell_id, cnm, lane):
129 returns an eland_file upon calling.
131 fc_id, status = parse_flowcell_id(flowcell_id)
132 d = get_flowcell_result_dict(fc_id)
135 return HttpResponse('<b>Results for Flowcell %s not found.</b>' % (fc_id))
138 return HttpResponse('<b>Results for Flowcell %s; %s not found.</b>' % (fc_id, cnm))
140 erd = d[cnm]['eland_results']
144 return HttpResponse('<b>Results for Flowcell %s; %s; lane %s not found.</b>' % (fc_id, cnm, lane))
148 #f = opener.autoopen(filepath, 'r')
149 # return HttpResponse(f, content_type="application/x-elandresult")
151 f = open(filepath, 'r')
152 return HttpResponse(f, content_type='application/x-bzip2')
155 def bedfile_fc_cnm_eland_lane_ucsc(request, fc_id, cnm, lane):
157 returns a bed file for a given flowcell, CN-M (i.e. C1-33), and lane (ucsc compatible)
159 return bedfile_fc_cnm_eland_lane(request, fc_id, cnm, lane, ucsc_compatible=True)
162 def bedfile_fc_cnm_eland_lane(request, flowcell_id, cnm, lane, ucsc_compatible=False):
164 returns a bed file for a given flowcell, CN-M (i.e. C1-33), and lane
166 fc_id, status = parse_flowcell_id(flowcell_id)
167 d = get_flowcell_result_dict(fc_id)
170 return HttpResponse('<b>Results for Flowcell %s not found.</b>' % (fc_id))
173 return HttpResponse('<b>Results for Flowcell %s; %s not found.</b>' % (fc_id, cnm))
175 erd = d[cnm]['eland_results']
179 return HttpResponse('<b>Results for Flowcell %s; %s; lane %s not found.</b>' % (fc_id, cnm, lane))
184 fi = opener.autoopen(filepath, 'r')
187 name, description = makebed.make_description(fc_id, lane)
189 bedgen = makebed.make_bed_from_eland_generator(fi, name, description)
192 return HttpResponse(bedgen)
194 return HttpResponse(bedgen, content_type="application/x-bedfile")
197 def _summary_stats(flowcell_id, lane_id, library_id):
199 Return the summary statistics for a given flowcell, lane, and end.
201 fc_id, status = parse_flowcell_id(flowcell_id)
202 fc_result_dict = get_flowcell_result_dict(fc_id)
207 if fc_result_dict is None:
208 err_list.append('Results for Flowcell %s not found.' % (fc_id))
209 return (summary_list, err_list)
211 for cycle_width in fc_result_dict:
212 xmlpath = fc_result_dict[cycle_width]['run_xml']
215 err_list.append('Run xml for Flowcell %s(%s) not found.' % (fc_id, cycle_width))
218 run = runfolder.load_pipeline_run_xml(xmlpath)
219 # skip if we don't have available metadata.
220 if run.gerald is None or run.gerald.summary is None:
223 gerald_summary = run.gerald.summary.lane_results
224 key = SampleKey(lane=lane_id, sample='s')
225 eland_results = list(run.gerald.eland_results.find_keys(key))
226 key = SampleKey(lane=lane_id, sample=library_id)
227 eland_results.extend(run.gerald.eland_results.find_keys(key))
228 for key in eland_results:
229 eland_summary = run.gerald.eland_results.results[key]
230 # add information to lane_summary
231 eland_summary.flowcell_id = flowcell_id
233 read = key.read-1 if key.read is not None else 0
235 eland_summary.clusters = gerald_summary[read][key.lane].cluster
236 except (IndexError, KeyError) as e:
237 eland_summary.clustes = None
238 eland_summary.cycle_width = cycle_width
239 if hasattr(eland_summary, 'genome_map'):
240 eland_summary.summarized_reads = runfolder.summarize_mapped_reads(
241 eland_summary.genome_map,
242 eland_summary.mapped_reads)
244 # grab some more information out of the flowcell db
245 flowcell = FlowCell.objects.get(flowcell_id=flowcell_id)
246 #pm_field = 'lane_%d_pM' % (lane_id)
247 lanes = flowcell.lane_set.filter(lane_number=lane_id)
248 eland_summary.flowcell = flowcell
249 eland_summary.lanes = lanes
251 summary_list.append(eland_summary)
253 #except Exception as e:
254 # summary_list.append("Summary report needs to be updated.")
255 # LOGGER.error("Exception: " + str(e))
257 return (summary_list, err_list)
260 def get_eland_result_type(pathname):
262 Guess the eland result file type from the filename
264 path, filename = os.path.split(pathname)
265 if 'extended' in filename:
267 elif 'multi' in filename:
269 elif 'result' in filename:
275 def _make_eland_results(flowcell_id, lane_number, interesting_flowcells):
276 fc_id, status = parse_flowcell_id(flowcell_id)
277 cur_fc = interesting_flowcells.get(fc_id, None)
281 flowcell = FlowCell.objects.get(flowcell_id=flowcell_id)
282 lanes = flowcell.lane_set.filter(lane_number=lane_number)
283 # Loop throw storage devices if a result has been archived
285 if cur_fc is not None:
286 for lts in flowcell.longtermstorage_set.all():
287 for sd in lts.storage_devices.all():
288 # Use barcode_id if it exists
289 if sd.barcode_id is not None and sd.barcode_id != '':
290 storage_id_list.append(sd.barcode_id)
293 storage_id_list.append(sd.uuid)
295 # Formatting for template use
296 if len(storage_id_list) == 0:
299 storage_ids = ', '.join(['<a href="/inventory/%s/">%s</a>' % (s, s) for s in storage_id_list])
302 for cycle in cur_fc.keys():
303 result_path = cur_fc[cycle]['eland_results'].get(lanes[0], None)
304 result_link = make_result_link(fc_id, cycle, lanes[0], result_path)
305 results.append({'flowcell_id': fc_id,
306 'flowcell': flowcell,
307 'run_date': flowcell.run_date,
310 'summary_url': make_summary_url(flowcell_id, cycle),
311 'result_url': result_link[0],
312 'result_label': result_link[1],
313 'bed_url': result_link[2],
314 'storage_ids': storage_ids})
318 def make_summary_url(flowcell_id, cycle_name):
319 url = '/results/%s/%s/summary/' % (flowcell_id, cycle_name)
323 def make_result_link(flowcell_id, cycle_name, lane, eland_result_path):
324 if eland_result_path is None:
327 result_type = get_eland_result_type(eland_result_path)
328 result_url = '/results/%s/%s/eland_result/%s' % (flowcell_id, cycle_name, lane)
329 result_label = 'eland %s' % (result_type,)
331 if result_type == 'result':
332 bed_url_pattern = '/results/%s/%s/bedfile/%s'
333 bed_url = bed_url_pattern % (flowcell_id, cycle_name, lane)
335 return (result_url, result_label, bed_url)
338 def _files(flowcell_id, lane):
340 Sets up available files for download
344 flowcell_id, id = parse_flowcell_id(flowcell_id)
345 d = get_flowcell_result_dict(flowcell_id)
352 # c_name == 'CN-M' (i.e. C1-33)
355 if d[c_name]['summary'] is not None:
356 output.append('<a href="/results/%s/%s/summary/">summary(%s)</a>' %
357 (flowcell_id, c_name, c_name))
359 erd = d[c_name]['eland_results']
361 result_type = get_eland_result_type(erd[lane])
362 result_url_pattern = '<a href="/results/%s/%s/eland_result/%s">eland %s(%s)</a>'
363 output.append(result_url_pattern % (flowcell_id, c_name, lane, result_type, c_name))
364 if result_type == 'result':
365 bed_url_pattern = '<a href="/results/%s/%s/bedfile/%s">bedfile(%s)</a>'
366 output.append(bed_url_pattern % (flowcell_id, c_name, lane, c_name))
371 return '(' + '|'.join(output) + ')'
374 def library_id_to_admin_url(request, lib_id):
375 lib = Library.objects.get(id=lib_id)
376 return HttpResponseRedirect('/admin/samples/library/%s' % (lib.id,))
379 def library_dict(library_id):
381 Given a library id construct a dictionary containing important information
382 return None if nothing was found
385 lib = Library.objects.get(id=library_id)
386 except Library.DoesNotExist as e:
389 #lane_info = lane_information(lib.lane_set)
391 for lane in lib.lane_set.all():
392 lane_info.append({'flowcell': lane.flowcell.flowcell_id,
393 'lane_number': lane.lane_number,
395 'paired_end': lane.flowcell.paired_end,
396 'read_length': lane.flowcell.read_length,
397 'status_code': lane.status,
398 'status': LANE_STATUS_MAP[lane.status]})
402 # 'aligned_reads': lib.aligned_reads,
403 #'amplified_into_sample': lib.amplified_into_sample, # into is a colleciton...
404 #'amplified_from_sample_id': lib.amplified_from_sample,
405 #'antibody_name': lib.antibody_name(), # we have no antibodies.
406 'antibody_id': lib.antibody_id,
407 'cell_line_id': lib.cell_line_id,
408 'cell_line': str_or_none(lib.cell_line),
409 'experiment_type': lib.experiment_type.name,
410 'experiment_type_id': lib.experiment_type_id,
411 'gel_cut_size': lib.gel_cut_size,
412 'hidden': lib.hidden,
414 'insert_size': lib.insert_size,
415 'lane_set': lane_info,
416 'library_id': lib.id,
417 'library_name': lib.library_name,
418 'library_species': lib.library_species.scientific_name,
419 'library_species_id': lib.library_species_id,
420 #'library_type': lib.library_type.name,
421 'library_type_id': lib.library_type_id,
422 'made_for': lib.made_for,
423 'made_by': lib.made_by,
425 'replicate': lib.replicate,
426 'stopping_point': lib.stopping_point,
427 'successful_pM': str_or_none(lib.successful_pM),
428 'undiluted_concentration': str_or_none(lib.undiluted_concentration)
430 if lib.library_type_id is None:
431 info['library_type'] = None
433 info['library_type'] = lib.library_type.name
438 def library_json(request, library_id):
440 Return a json formatted library dictionary
442 require_api_key(request)
443 # what validation should we do on library_id?
445 lib = library_dict(library_id)
449 lib_json = json.dumps({'result': lib})
450 return HttpResponse(lib_json, content_type='application/json')
454 def species_json(request, species_id):
456 Return information about a species.
461 def species(request, species_id):
462 species = get_object_or_404(Species, id=species_id)
464 context = RequestContext(request,
465 {'species': species})
467 return render_to_response("samples/species_detail.html", context)
470 def antibodies(request):
471 context = RequestContext(request,
472 {'antibodies': Antibody.objects.order_by('antigene')})
473 return render_to_response("samples/antibody_index.html", context)
477 def user_profile(request):
479 Information about the user
482 'page_name': 'User Profile',
484 # 'bcmagic': BarcodeMagicForm(),
485 # 'select': 'settings',
487 context.update(SAMPLES_CONTEXT_DEFAULTS)
488 return render_to_response('registration/profile.html', context,
489 context_instance=RequestContext(request))