1 # Create your views here.
10 import simplejson as json
12 from htsworkflow.frontend.auth import require_api_key
13 from htsworkflow.frontend.experiments.models import FlowCell
14 from htsworkflow.frontend.samples.changelist import ChangeList
15 from htsworkflow.frontend.samples.models import Library
16 from htsworkflow.frontend.samples.results import get_flowcell_result_dict, parse_flowcell_id
17 from htsworkflow.frontend.bcmagic.forms import BarcodeMagicForm
18 from htsworkflow.pipelines.runfolder import load_pipeline_run_xml
19 from htsworkflow.pipelines import runfolder
20 from htsworkflow.pipelines.eland import ResultLane
21 from htsworkflow.frontend import settings
22 from htsworkflow.util.conversion import unicode_or_none
23 from htsworkflow.util import makebed
24 from htsworkflow.util import opener
27 from django.core.exceptions import ObjectDoesNotExist
28 from django.http import HttpResponse, HttpResponseRedirect, Http404
29 from django.shortcuts import render_to_response
30 from django.template import RequestContext
31 from django.template.loader import get_template
32 from django.contrib.auth.decorators import login_required
34 LANE_LIST = [1,2,3,4,5,6,7,8]
35 SAMPLES_CONTEXT_DEFAULTS = {
36 'app_name': 'Flowcell/Library Tracker',
37 'bcmagic': BarcodeMagicForm()
40 def create_library_context(cl):
42 Create a list of libraries that includes how many lanes were run
45 #for lib in library_items.object_list:
46 for lib in cl.result_list:
48 summary['library_id'] = lib.id
49 summary['library_name'] = lib.library_name
50 summary['species_name' ] = lib.library_species.scientific_name
51 if lib.amplified_from_sample is not None:
52 summary['amplified_from'] = lib.amplified_from_sample.id
54 summary['amplified_from'] = ''
56 #for lane_id in LANE_LIST:
57 # lane = getattr(lib, 'lane_%d_library' % (lane_id,))
58 # lanes_run += len( lane.all() )
59 lanes_run = lib.lane_set.count()
60 summary['lanes_run'] = lanes_run
61 summary['is_archived'] = lib.is_archived()
62 records.append(summary)
63 cl.result_count = unicode(cl.paginator._count) + u" libraries"
64 return {'library_list': records }
68 fcl = ChangeList(request, Library,
69 list_filter=['affiliations', 'library_species'],
70 search_fields=['id', 'library_name', 'amplified_from_sample__id'],
72 queryset=Library.objects.filter(hidden__exact=0)
75 context = { 'cl': fcl, 'title': 'Library Index'}
76 context.update(create_library_context(fcl))
77 t = get_template('samples/library_index.html')
78 c = RequestContext(request, context)
81 'page_name': 'Library Index',
82 'east_region_config_div': 'changelist-filter',
85 app_context.update(SAMPLES_CONTEXT_DEFAULTS)
87 app_t = get_template('flowcell_libraries_app.html')
88 app_c = RequestContext(request, app_context)
89 return HttpResponse( app_t.render(app_c) )
91 def library_to_flowcells(request, lib_id):
93 Display information about all the flowcells a library has been run on.
97 lib = Library.objects.get(id=lib_id)
99 return HttpResponse("Library %s does not exist" % (lib_id))
102 flowcell_run_results = {} # aka flowcells we're looking at
103 for lane in lib.lane_set.all():
105 flowcell_id, id = parse_flowcell_id(fc.flowcell_id)
106 if flowcell_id not in flowcell_run_results:
107 flowcell_run_results[flowcell_id] = get_flowcell_result_dict(flowcell_id)
108 flowcell_list.append((fc.flowcell_id, lane.lane_number))
111 lane_summary_list = []
113 for fc, lane_number in flowcell_list:
114 lane_summary, err_list = _summary_stats(fc, lane_number)
116 eland_results.extend(_make_eland_results(fc, lane_number, flowcell_run_results))
117 lane_summary_list.extend(lane_summary)
120 'page_name': 'Library Details',
122 'eland_results': eland_results,
123 'lane_summary_list': lane_summary_list,
125 context.update(SAMPLES_CONTEXT_DEFAULTS)
127 return render_to_response(
128 'samples/library_detail.html',
130 context_instance = RequestContext(request))
132 def summaryhtm_fc_cnm(request, flowcell_id, cnm):
134 returns a Summary.htm file if it exists.
136 fc_id, status = parse_flowcell_id(flowcell_id)
137 d = get_flowcell_result_dict(fc_id)
140 return HttpResponse('<b>Results for Flowcell %s not found.</b>' % (fc_id))
143 return HttpResponse('<b>Results for Flowcell %s; %s not found.</b>' % (fc_id, cnm))
145 summary_filepath = d[cnm]['summary']
147 if summary_filepath is None:
148 return HttpResponse('<b>Summary.htm for Flowcell %s; %s not found.</b>' % (fc_id, cnm))
150 f = open(summary_filepath, 'r')
152 return HttpResponse(f)
155 def result_fc_cnm_eland_lane(request, flowcell_id, cnm, lane):
157 returns an eland_file upon calling.
159 fc_id, status = parse_flowcell_id(flowcell_id)
160 d = get_flowcell_result_dict(fc_id)
163 return HttpResponse('<b>Results for Flowcell %s not found.</b>' % (fc_id))
166 return HttpResponse('<b>Results for Flowcell %s; %s not found.</b>' % (fc_id, cnm))
168 erd = d[cnm]['eland_results']
172 return HttpResponse('<b>Results for Flowcell %s; %s; lane %s not found.</b>' % (fc_id, cnm, lane))
176 #f = opener.autoopen(filepath, 'r')
177 # return HttpResponse(f, mimetype="application/x-elandresult")
179 f = open(filepath, 'r')
180 return HttpResponse(f, mimetype='application/x-bzip2')
184 def bedfile_fc_cnm_eland_lane_ucsc(request, fc_id, cnm, lane):
186 returns a bed file for a given flowcell, CN-M (i.e. C1-33), and lane (ucsc compatible)
188 return bedfile_fc_cnm_eland_lane(request, fc_id, cnm, lane, ucsc_compatible=True)
191 def bedfile_fc_cnm_eland_lane(request, flowcell_id, cnm, lane, ucsc_compatible=False):
193 returns a bed file for a given flowcell, CN-M (i.e. C1-33), and lane
195 fc_id, status = parse_flowcell_id(flowcell_id)
196 d = get_flowcell_result_dict(fc_id)
199 return HttpResponse('<b>Results for Flowcell %s not found.</b>' % (fc_id))
202 return HttpResponse('<b>Results for Flowcell %s; %s not found.</b>' % (fc_id, cnm))
204 erd = d[cnm]['eland_results']
208 return HttpResponse('<b>Results for Flowcell %s; %s; lane %s not found.</b>' % (fc_id, cnm, lane))
213 fi = opener.autoopen(filepath, 'r')
216 name, description = makebed.make_description( fc_id, lane )
218 bedgen = makebed.make_bed_from_eland_generator(fi, name, description)
221 return HttpResponse(bedgen)
223 return HttpResponse(bedgen, mimetype="application/x-bedfile")
226 def _summary_stats(flowcell_id, lane_id):
228 Return the summary statistics for a given flowcell, lane, and end.
230 fc_id, status = parse_flowcell_id(flowcell_id)
231 fc_result_dict = get_flowcell_result_dict(fc_id)
236 if fc_result_dict is None:
237 err_list.append('Results for Flowcell %s not found.' % (fc_id))
238 return (summary_list, err_list)
240 for cycle_width in fc_result_dict:
241 xmlpath = fc_result_dict[cycle_width]['run_xml']
244 err_list.append('Run xml for Flowcell %s(%s) not found.' % (fc_id, cycle_width))
247 run = load_pipeline_run_xml(xmlpath)
248 gerald_summary = run.gerald.summary.lane_results
249 for end in range(len(gerald_summary)):
250 end_summary = run.gerald.eland_results.results[end]
251 if end_summary.has_key(lane_id):
252 eland_summary = run.gerald.eland_results.results[end][lane_id]
254 eland_summary = ResultLane(lane_id=lane_id, end=end)
255 # add information to lane_summary
256 eland_summary.flowcell_id = flowcell_id
257 if len(gerald_summary) > end and gerald_summary[end].has_key(lane_id):
258 eland_summary.clusters = gerald_summary[end][lane_id].cluster
260 eland_summary.clusters = None
261 eland_summary.cycle_width = cycle_width
262 if hasattr(eland_summary, 'genome_map'):
263 eland_summary.summarized_reads = runfolder.summarize_mapped_reads(
264 eland_summary.genome_map,
265 eland_summary.mapped_reads)
267 # grab some more information out of the flowcell db
268 flowcell = FlowCell.objects.get(flowcell_id=flowcell_id)
269 #pm_field = 'lane_%d_pM' % (lane_id)
270 lane_obj = flowcell.lane_set.get(lane_number=lane_id)
271 eland_summary.successful_pm = lane_obj.pM
273 summary_list.append(eland_summary)
275 #except Exception, e:
276 # summary_list.append("Summary report needs to be updated.")
277 # logging.error("Exception: " + str(e))
279 return (summary_list, err_list)
281 def _summary_stats_old(flowcell_id, lane):
283 return a dictionary of summary stats for a given flowcell_id & lane.
285 fc_id, status = parse_flowcell_id(flowcell_id)
286 fc_result_dict = get_flowcell_result_dict(fc_id)
292 if fc_result_dict is None:
293 err_list.append('Results for Flowcell %s not found.' % (fc_id))
294 return (dict_list, err_list, summary_list)
296 for cnm in fc_result_dict:
298 xmlpath = fc_result_dict[cnm]['run_xml']
301 err_list.append('Run xml for Flowcell %s(%s) not found.' % (fc_id, cnm))
304 tree = ElementTree.parse(xmlpath).getroot()
305 results = runfolder.PipelineRun(pathname='', xml=tree)
307 lane_report = runfolder.summarize_lane(results.gerald, lane)
308 summary_list.append(os.linesep.join(lane_report))
310 summary_list.append("Summary report needs to be updated.")
311 logging.error("Exception: " + str(e))
313 print >>sys.stderr, "----------------------------------"
314 print >>sys.stderr, "-- DOES NOT SUPPORT PAIRED END ---"
315 print >>sys.stderr, "----------------------------------"
316 lane_results = results.gerald.summary[0][lane]
321 d['average_alignment_score'] = lrs.average_alignment_score
322 d['average_first_cycle_intensity'] = lrs.average_first_cycle_intensity
323 d['cluster'] = lrs.cluster
325 d['flowcell'] = flowcell_id
327 d['percent_error_rate'] = lrs.percent_error_rate
328 d['percent_intensity_after_20_cycles'] = lrs.percent_intensity_after_20_cycles
329 d['percent_pass_filter_align'] = lrs.percent_pass_filter_align
330 d['percent_pass_filter_clusters'] = lrs.percent_pass_filter_clusters
332 #FIXME: function finished, but need to take advantage of
333 # may need to take in a list of lanes so we only have to
334 # load the xml file once per flowcell rather than once
338 return (dict_list, err_list, summary_list)
341 def get_eland_result_type(pathname):
343 Guess the eland result file type from the filename
345 path, filename = os.path.split(pathname)
346 if 'extended' in filename:
348 elif 'multi' in filename:
350 elif 'result' in filename:
355 def _make_eland_results(flowcell_id, lane, interesting_flowcells):
356 fc_id, status = parse_flowcell_id(flowcell_id)
357 cur_fc = interesting_flowcells.get(fc_id, None)
361 flowcell = FlowCell.objects.get(flowcell_id=flowcell_id)
362 # Loop throw storage devices if a result has been archived
364 if cur_fc is not None:
365 for lts in flowcell.longtermstorage_set.all():
366 for sd in lts.storage_devices.all():
367 # Use barcode_id if it exists
368 if sd.barcode_id is not None and sd.barcode_id != '':
369 storage_id_list.append(sd.barcode_id)
372 storage_id_list.append(sd.uuid)
374 # Formatting for template use
375 if len(storage_id_list) == 0:
378 storage_ids = ', '.join([ '<a href="/inventory/%s/">%s</a>' % (s,s) for s in storage_id_list ])
381 for cycle in cur_fc.keys():
382 result_path = cur_fc[cycle]['eland_results'].get(lane, None)
383 result_link = make_result_link(fc_id, cycle, lane, result_path)
384 results.append({'flowcell_id': fc_id,
385 'run_date': flowcell.run_date,
388 'summary_url': make_summary_url(flowcell_id, cycle),
389 'result_url': result_link[0],
390 'result_label': result_link[1],
391 'bed_url': result_link[2],
392 'storage_ids': storage_ids
396 def make_summary_url(flowcell_id, cycle_name):
397 url = '/results/%s/%s/summary/' % (flowcell_id, cycle_name)
400 def make_result_link(flowcell_id, cycle_name, lane, eland_result_path):
401 if eland_result_path is None:
404 result_type = get_eland_result_type(eland_result_path)
405 result_url = '/results/%s/%s/eland_result/%s' % (flowcell_id, cycle_name, lane)
406 result_label = 'eland %s' % (result_type,)
408 if result_type == 'result':
409 bed_url_pattern = '/results/%s/%s/bedfile/%s'
410 bed_url = bed_url_pattern % (flowcell_id, cycle_name, lane)
412 return (result_url, result_label, bed_url)
414 def _files(flowcell_id, lane):
416 Sets up available files for download
420 flowcell_id, id = parse_flowcell_id(flowcell_id)
421 d = get_flowcell_result_dict(flowcell_id)
428 # c_name == 'CN-M' (i.e. C1-33)
431 if d[c_name]['summary'] is not None:
432 output.append('<a href="/results/%s/%s/summary/">summary(%s)</a>' \
433 % (flowcell_id, c_name, c_name))
435 erd = d[c_name]['eland_results']
437 result_type = get_eland_result_type(erd[lane])
438 result_url_pattern = '<a href="/results/%s/%s/eland_result/%s">eland %s(%s)</a>'
439 output.append(result_url_pattern % (flowcell_id, c_name, lane, result_type, c_name))
440 if result_type == 'result':
441 bed_url_pattern = '<a href="/results/%s/%s/bedfile/%s">bedfile(%s)</a>'
442 output.append(bed_url_pattern % (flowcell_id, c_name, lane, c_name))
447 return '(' + '|'.join(output) + ')'
449 def library_id_to_admin_url(request, lib_id):
450 lib = Library.objects.get(id=lib_id)
451 return HttpResponseRedirect('/admin/samples/library/%s' % (lib.id,))
453 def library_dict(library_id):
455 Given a library id construct a dictionary containing important information
456 return None if nothing was found
459 lib = Library.objects.get(id = library_id)
460 except Library.DoesNotExist, e:
463 #lane_info = lane_information(lib.lane_set)
465 for lane in lib.lane_set.all():
466 lane_info.append( {'flowcell':lane.flowcell.flowcell_id,
467 'lane_number': lane.lane_number} )
471 # 'aligned_reads': lib.aligned_reads,
472 #'amplified_into_sample': lib.amplified_into_sample, # into is a colleciton...
473 #'amplified_from_sample_id': lib.amplified_from_sample,
474 #'antibody_name': lib.antibody_name(), # we have no antibodies.
475 'antibody_id': lib.antibody_id,
476 'avg_lib_size': lib.avg_lib_size,
477 'cell_line_id': lib.cell_line_id,
478 'cell_line': unicode_or_none(lib.cell_line),
479 'experiment_type': lib.experiment_type.name,
480 'experiment_type_id': lib.experiment_type_id,
482 'lane_set': lane_info,
483 'library_id': lib.id,
484 'library_name': lib.library_name,
485 'library_species': lib.library_species.scientific_name,
486 'library_species_id': lib.library_species_id,
487 #'library_type': lib.library_type.name,
488 'library_type_id': lib.library_type_id,
489 'made_for': lib.made_for,
490 'made_by': lib.made_by,
492 'replicate': lib.replicate,
493 'stopping_point': lib.stopping_point,
494 'successful_pM': unicode_or_none(lib.successful_pM),
495 'undiluted_concentration': unicode_or_none(lib.undiluted_concentration)
497 if lib.library_type_id is None:
498 info['library_type'] = None
500 info['library_type'] = lib.library_type.name
503 def library_json(request, library_id):
505 Return a json formatted library dictionary
507 require_api_key(request)
508 # what validation should we do on library_id?
510 lib = library_dict(library_id)
514 lib_json = json.dumps(lib)
515 return HttpResponse(lib_json, mimetype='application/json')
517 def species_json(request, species_id):
519 Return information about a species.
524 def user_profile(request):
526 Information about the user
529 'page_name': 'User Profile',
531 #'bcmagic': BarcodeMagicForm(),
532 #'select': 'settings',
534 context.update(SAMPLES_CONTEXT_DEFAULTS)
535 return render_to_response('registration/profile.html', context,
536 context_instance=RequestContext(request))