1 # Create your views here.
2 from htsworkflow.frontend.experiments.models import FlowCell
3 from htsworkflow.frontend.samples.changelist import ChangeList
4 from htsworkflow.frontend.samples.models import Library
5 from htsworkflow.frontend.samples.results import get_flowcell_result_dict, parse_flowcell_id
6 from htsworkflow.pipelines.runfolder import load_pipeline_run_xml
7 from htsworkflow.pipelines import runfolder
8 from htsworkflow.frontend import settings
9 from htsworkflow.util import makebed
10 from htsworkflow.util import opener
12 from django.core.exceptions import ObjectDoesNotExist
13 from django.http import HttpResponse, HttpResponseRedirect
14 from django.shortcuts import render_to_response
15 from django.template import RequestContext
16 from django.template.loader import get_template
17 from django.contrib.auth.decorators import login_required
23 LANE_LIST = [1,2,3,4,5,6,7,8]
24 SAMPLES_CONTEXT_DEFAULTS = {
25 'app_name': 'Flowcell/Library Tracker'
28 def create_library_context(cl):
30 Create a list of libraries that includes how many lanes were run
33 #for lib in library_items.object_list:
34 for lib in cl.result_list:
36 summary['library_id'] = lib.library_id
37 summary['library_name'] = lib.library_name
38 summary['species_name' ] = lib.library_species.scientific_name
39 if lib.amplified_from_sample is not None:
40 summary['amplified_from'] = lib.amplified_from_sample.library_id
42 summary['amplified_from'] = ''
44 for lane_id in LANE_LIST:
45 lane = getattr(lib, 'lane_%d_library' % (lane_id,))
46 lanes_run += len( lane.all() )
47 summary['lanes_run'] = lanes_run
48 summary['is_archived'] = lib.is_archived()
49 records.append(summary)
50 cl.result_count = unicode(cl.paginator._count) + u" libraries"
51 return {'library_list': records }
55 fcl = ChangeList(request, Library,
56 list_filter=['affiliations', 'library_species'],
57 search_fields=['library_id', 'library_name', 'amplified_from_sample__library_id'],
59 queryset=Library.objects.filter(hidden__exact=0)
62 context = { 'cl': fcl, 'title': 'Library Index'}
63 context.update(create_library_context(fcl))
64 t = get_template('samples/library_index.html')
65 c = RequestContext(request, context)
68 'page_name': 'Library Index',
69 'east_region_config_div': 'changelist-filter',
72 app_context.update(SAMPLES_CONTEXT_DEFAULTS)
74 app_t = get_template('flowcell_libraries_app.html')
75 app_c = RequestContext(request, app_context)
76 return HttpResponse( app_t.render(app_c) )
78 def library_to_flowcells(request, lib_id):
80 Display information about all the flowcells a library has been run on.
84 lib = Library.objects.get(library_id=lib_id)
86 return HttpResponse("Library %s does not exist" % (lib_id))
89 interesting_flowcells = {} # aka flowcells we're looking at
90 for lane in LANE_LIST:
91 lane_library = getattr(lib, 'lane_%d_library' % (lane,))
92 for fc in lane_library.all():
93 flowcell_id, id = parse_flowcell_id(fc.flowcell_id)
94 if flowcell_id not in interesting_flowcells:
95 interesting_flowcells[flowcell_id] = get_flowcell_result_dict(flowcell_id)
96 flowcell_list.append((fc.flowcell_id, lane))
100 lane_summary_list = []
102 for fc, lane in flowcell_list:
103 lane_summary, err_list = _summary_stats(fc, lane)
105 eland_results.extend(_make_eland_results(fc, lane, interesting_flowcells))
106 lane_summary_list.extend(lane_summary)
109 'page_name': 'Library Details',
111 'eland_results': eland_results,
112 'lane_summary_list': lane_summary_list,
114 context.update(SAMPLES_CONTEXT_DEFAULTS)
116 return render_to_response(
117 'samples/library_detail.html',
119 context_instance = RequestContext(request))
121 def summaryhtm_fc_cnm(request, flowcell_id, cnm):
123 returns a Summary.htm file if it exists.
125 fc_id, status = parse_flowcell_id(flowcell_id)
126 d = get_flowcell_result_dict(fc_id)
129 return HttpResponse('<b>Results for Flowcell %s not found.</b>' % (fc_id))
132 return HttpResponse('<b>Results for Flowcell %s; %s not found.</b>' % (fc_id, cnm))
134 summary_filepath = d[cnm]['summary']
136 if summary_filepath is None:
137 return HttpResponse('<b>Summary.htm for Flowcell %s; %s not found.</b>' % (fc_id, cnm))
139 f = open(summary_filepath, 'r')
141 return HttpResponse(f)
144 def result_fc_cnm_eland_lane(request, flowcell_id, cnm, lane):
146 returns an eland_file upon calling.
148 fc_id, status = parse_flowcell_id(flowcell_id)
149 d = get_flowcell_result_dict(fc_id)
152 return HttpResponse('<b>Results for Flowcell %s not found.</b>' % (fc_id))
155 return HttpResponse('<b>Results for Flowcell %s; %s not found.</b>' % (fc_id, cnm))
157 erd = d[cnm]['eland_results']
161 return HttpResponse('<b>Results for Flowcell %s; %s; lane %s not found.</b>' % (fc_id, cnm, lane))
165 #f = opener.autoopen(filepath, 'r')
166 # return HttpResponse(f, mimetype="application/x-elandresult")
168 f = open(filepath, 'r')
169 return HttpResponse(f, mimetype='application/x-bzip2')
173 def bedfile_fc_cnm_eland_lane_ucsc(request, fc_id, cnm, lane):
175 returns a bed file for a given flowcell, CN-M (i.e. C1-33), and lane (ucsc compatible)
177 return bedfile_fc_cnm_eland_lane(request, fc_id, cnm, lane, ucsc_compatible=True)
180 def bedfile_fc_cnm_eland_lane(request, flowcell_id, cnm, lane, ucsc_compatible=False):
182 returns a bed file for a given flowcell, CN-M (i.e. C1-33), and lane
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))
202 fi = opener.autoopen(filepath, 'r')
205 name, description = makebed.make_description( fc_id, lane )
207 bedgen = makebed.make_bed_from_eland_generator(fi, name, description)
210 return HttpResponse(bedgen)
212 return HttpResponse(bedgen, mimetype="application/x-bedfile")
215 def _summary_stats(flowcell_id, lane_id):
217 Return the summary statistics for a given flowcell, lane, and end.
219 fc_id, status = parse_flowcell_id(flowcell_id)
220 fc_result_dict = get_flowcell_result_dict(fc_id)
225 if fc_result_dict is None:
226 err_list.append('Results for Flowcell %s not found.' % (fc_id))
227 return (summary_list, err_list)
229 for cycle_width in fc_result_dict:
230 xmlpath = fc_result_dict[cycle_width]['run_xml']
233 err_list.append('Run xml for Flowcell %s(%s) not found.' % (fc_id, cycle_width))
236 run = load_pipeline_run_xml(xmlpath)
237 gerald_summary = run.gerald.summary.lane_results
238 for end in range(len(gerald_summary)):
239 eland_summary = run.gerald.eland_results.results[end][lane_id]
240 # add information to lane_summary
241 eland_summary.flowcell_id = flowcell_id
242 eland_summary.clusters = gerald_summary[end][lane_id].cluster
243 eland_summary.cycle_width = cycle_width
244 if hasattr(eland_summary, 'genome_map'):
245 eland_summary.summarized_reads = runfolder.summarize_mapped_reads(
246 eland_summary.genome_map,
247 eland_summary.mapped_reads)
249 # grab some more information out of the flowcell db
250 flowcell = FlowCell.objects.get(flowcell_id=flowcell_id)
251 pm_field = 'lane_%d_pM' % (lane_id)
252 eland_summary.successful_pm = getattr(flowcell, pm_field)
254 summary_list.append(eland_summary)
256 #except Exception, e:
257 # summary_list.append("Summary report needs to be updated.")
258 # logging.error("Exception: " + str(e))
260 return (summary_list, err_list)
262 def _summary_stats_old(flowcell_id, lane):
264 return a dictionary of summary stats for a given flowcell_id & lane.
266 fc_id, status = parse_flowcell_id(flowcell_id)
267 fc_result_dict = get_flowcell_result_dict(fc_id)
273 if fc_result_dict is None:
274 err_list.append('Results for Flowcell %s not found.' % (fc_id))
275 return (dict_list, err_list, summary_list)
277 for cnm in fc_result_dict:
279 xmlpath = fc_result_dict[cnm]['run_xml']
282 err_list.append('Run xml for Flowcell %s(%s) not found.' % (fc_id, cnm))
285 tree = ElementTree.parse(xmlpath).getroot()
286 results = runfolder.PipelineRun(pathname='', xml=tree)
288 lane_report = runfolder.summarize_lane(results.gerald, lane)
289 summary_list.append(os.linesep.join(lane_report))
291 summary_list.append("Summary report needs to be updated.")
292 logging.error("Exception: " + str(e))
294 print "----------------------------------"
295 print "-- DOES NOT SUPPORT PAIRED END ---"
296 print "----------------------------------"
297 lane_results = results.gerald.summary[0][lane]
302 d['average_alignment_score'] = lrs.average_alignment_score
303 d['average_first_cycle_intensity'] = lrs.average_first_cycle_intensity
304 d['cluster'] = lrs.cluster
306 d['flowcell'] = flowcell_id
308 d['percent_error_rate'] = lrs.percent_error_rate
309 d['percent_intensity_after_20_cycles'] = lrs.percent_intensity_after_20_cycles
310 d['percent_pass_filter_align'] = lrs.percent_pass_filter_align
311 d['percent_pass_filter_clusters'] = lrs.percent_pass_filter_clusters
313 #FIXME: function finished, but need to take advantage of
314 # may need to take in a list of lanes so we only have to
315 # load the xml file once per flowcell rather than once
319 return (dict_list, err_list, summary_list)
322 def get_eland_result_type(pathname):
324 Guess the eland result file type from the filename
326 path, filename = os.path.split(pathname)
327 if 'extended' in filename:
329 elif 'multi' in filename:
331 elif 'result' in filename:
336 def _make_eland_results(flowcell_id, lane, interesting_flowcells):
337 fc_id, status = parse_flowcell_id(flowcell_id)
338 cur_fc = interesting_flowcells.get(fc_id, None)
342 flowcell = FlowCell.objects.get(flowcell_id=flowcell_id)
343 # Loop throw storage devices if a result has been archived
345 if cur_fc is not None:
346 for lts in flowcell.longtermstorage_set.all():
347 for sd in lts.storage_devices.all():
348 # Use barcode_id if it exists
349 if sd.barcode_id is not None and sd.barcode_id != '':
350 storage_id_list.append(sd.barcode_id)
353 storage_id_list.append(sd.uuid)
355 # Formatting for template use
356 if len(storage_id_list) == 0:
359 storage_ids = ', '.join(storage_id_list)
362 for cycle in cur_fc.keys():
363 result_path = cur_fc[cycle]['eland_results'].get(lane, None)
364 result_link = make_result_link(fc_id, cycle, lane, result_path)
365 results.append({'flowcell_id': fc_id,
368 'summary_url': make_summary_url(flowcell_id, cycle),
369 'result_url': result_link[0],
370 'result_label': result_link[1],
371 'bed_url': result_link[2],
372 'storage_ids': storage_ids
376 def make_summary_url(flowcell_id, cycle_name):
377 url = '/results/%s/%s/summary/' % (flowcell_id, cycle_name)
380 def make_result_link(flowcell_id, cycle_name, lane, eland_result_path):
381 if eland_result_path is None:
384 result_type = get_eland_result_type(eland_result_path)
385 result_url = '/results/%s/%s/eland_result/%s' % (flowcell_id, cycle_name, lane)
386 result_label = 'eland %s' % (result_type,)
388 if result_type == 'result':
389 bed_url_pattern = '/results/%s/%s/bedfile/%s'
390 bed_url = bed_url_pattern % (flowcell_id, cycle_name, lane)
392 return (result_url, result_label, bed_url)
394 def _files(flowcell_id, lane):
396 Sets up available files for download
400 flowcell_id, id = parse_flowcell_id(flowcell_id)
401 d = get_flowcell_result_dict(flowcell_id)
408 # c_name == 'CN-M' (i.e. C1-33)
411 if d[c_name]['summary'] is not None:
412 output.append('<a href="/results/%s/%s/summary/">summary(%s)</a>' \
413 % (flowcell_id, c_name, c_name))
415 erd = d[c_name]['eland_results']
417 result_type = get_eland_result_type(erd[lane])
418 result_url_pattern = '<a href="/results/%s/%s/eland_result/%s">eland %s(%s)</a>'
419 output.append(result_url_pattern % (flowcell_id, c_name, lane, result_type, c_name))
420 if result_type == 'result':
421 bed_url_pattern = '<a href="/results/%s/%s/bedfile/%s">bedfile(%s)</a>'
422 output.append(bed_url_pattern % (flowcell_id, c_name, lane, c_name))
427 return '(' + '|'.join(output) + ')'
429 def library_id_to_admin_url(request, lib_id):
430 lib = Library.objects.get(library_id=lib_id)
431 return HttpResponseRedirect('/admin/samples/library/%s' % (lib.id,))
434 def user_profile(request):
436 Information about the user
439 'page_name': 'User Profile',
441 #'bcmagic': BarcodeMagicForm(),
442 #'select': 'settings',
444 context.update(SAMPLES_CONTEXT_DEFAULTS)
445 return render_to_response('registration/profile.html', context,
446 context_instance=RequestContext(request))