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',
71 app_context.update(SAMPLES_CONTEXT_DEFAULTS)
73 app_t = get_template('flowcell_libraries_app.html')
74 app_c = RequestContext(request, app_context)
75 return HttpResponse( app_t.render(app_c) )
77 def library_to_flowcells(request, lib_id):
79 Display information about all the flowcells a library has been run on.
83 lib = Library.objects.get(library_id=lib_id)
85 return HttpResponse("Library %s does not exist" % (lib_id))
88 interesting_flowcells = {} # aka flowcells we're looking at
89 for lane in LANE_LIST:
90 lane_library = getattr(lib, 'lane_%d_library' % (lane,))
91 for fc in lane_library.all():
92 flowcell_id, id = parse_flowcell_id(fc.flowcell_id)
93 if flowcell_id not in interesting_flowcells:
94 interesting_flowcells[flowcell_id] = get_flowcell_result_dict(flowcell_id)
95 flowcell_list.append((fc.flowcell_id, lane))
99 lane_summary_list = []
101 for fc, lane in flowcell_list:
102 lane_summary, err_list = _summary_stats(fc, lane)
104 eland_results.extend(_make_eland_results(fc, lane, interesting_flowcells))
105 lane_summary_list.extend(lane_summary)
107 return render_to_response(
108 'samples/library_detail.html',
110 'eland_results': eland_results,
111 'lane_summary_list': lane_summary_list,
113 context_instance = RequestContext(request))
115 def summaryhtm_fc_cnm(request, flowcell_id, cnm):
117 returns a Summary.htm file if it exists.
119 fc_id, status = parse_flowcell_id(flowcell_id)
120 d = get_flowcell_result_dict(fc_id)
123 return HttpResponse('<b>Results for Flowcell %s not found.</b>' % (fc_id))
126 return HttpResponse('<b>Results for Flowcell %s; %s not found.</b>' % (fc_id, cnm))
128 summary_filepath = d[cnm]['summary']
130 if summary_filepath is None:
131 return HttpResponse('<b>Summary.htm for Flowcell %s; %s not found.</b>' % (fc_id, cnm))
133 f = open(summary_filepath, 'r')
135 return HttpResponse(f)
138 def result_fc_cnm_eland_lane(request, flowcell_id, cnm, lane):
140 returns an eland_file upon calling.
142 fc_id, status = parse_flowcell_id(flowcell_id)
143 d = get_flowcell_result_dict(fc_id)
146 return HttpResponse('<b>Results for Flowcell %s not found.</b>' % (fc_id))
149 return HttpResponse('<b>Results for Flowcell %s; %s not found.</b>' % (fc_id, cnm))
151 erd = d[cnm]['eland_results']
155 return HttpResponse('<b>Results for Flowcell %s; %s; lane %s not found.</b>' % (fc_id, cnm, lane))
159 #f = opener.autoopen(filepath, 'r')
160 # return HttpResponse(f, mimetype="application/x-elandresult")
162 f = open(filepath, 'r')
163 return HttpResponse(f, mimetype='application/x-bzip2')
167 def bedfile_fc_cnm_eland_lane_ucsc(request, fc_id, cnm, lane):
169 returns a bed file for a given flowcell, CN-M (i.e. C1-33), and lane (ucsc compatible)
171 return bedfile_fc_cnm_eland_lane(request, fc_id, cnm, lane, ucsc_compatible=True)
174 def bedfile_fc_cnm_eland_lane(request, flowcell_id, cnm, lane, ucsc_compatible=False):
176 returns a bed file for a given flowcell, CN-M (i.e. C1-33), and lane
178 fc_id, status = parse_flowcell_id(flowcell_id)
179 d = get_flowcell_result_dict(fc_id)
182 return HttpResponse('<b>Results for Flowcell %s not found.</b>' % (fc_id))
185 return HttpResponse('<b>Results for Flowcell %s; %s not found.</b>' % (fc_id, cnm))
187 erd = d[cnm]['eland_results']
191 return HttpResponse('<b>Results for Flowcell %s; %s; lane %s not found.</b>' % (fc_id, cnm, lane))
196 fi = opener.autoopen(filepath, 'r')
199 name, description = makebed.make_description( fc_id, lane )
201 bedgen = makebed.make_bed_from_eland_generator(fi, name, description)
204 return HttpResponse(bedgen)
206 return HttpResponse(bedgen, mimetype="application/x-bedfile")
209 def _summary_stats(flowcell_id, lane_id):
211 Return the summary statistics for a given flowcell, lane, and end.
213 fc_id, status = parse_flowcell_id(flowcell_id)
214 fc_result_dict = get_flowcell_result_dict(fc_id)
219 if fc_result_dict is None:
220 err_list.append('Results for Flowcell %s not found.' % (fc_id))
221 return (summary_list, err_list)
223 for cycle_width in fc_result_dict:
224 xmlpath = fc_result_dict[cycle_width]['run_xml']
227 err_list.append('Run xml for Flowcell %s(%s) not found.' % (fc_id, cycle_width))
230 run = load_pipeline_run_xml(xmlpath)
231 gerald_summary = run.gerald.summary.lane_results
232 for end in range(len(gerald_summary)):
233 eland_summary = run.gerald.eland_results.results[end][lane_id]
234 # add information to lane_summary
235 eland_summary.flowcell_id = flowcell_id
236 eland_summary.clusters = gerald_summary[end][lane_id].cluster
237 eland_summary.cycle_width = cycle_width
238 if hasattr(eland_summary, 'genome_map'):
239 eland_summary.summarized_reads = runfolder.summarize_mapped_reads(
240 eland_summary.genome_map,
241 eland_summary.mapped_reads)
243 # grab some more information out of the flowcell db
244 flowcell = FlowCell.objects.get(flowcell_id=flowcell_id)
245 pm_field = 'lane_%d_pM' % (lane_id)
246 eland_summary.successful_pm = getattr(flowcell, pm_field)
248 summary_list.append(eland_summary)
250 #except Exception, e:
251 # summary_list.append("Summary report needs to be updated.")
252 # logging.error("Exception: " + str(e))
254 return (summary_list, err_list)
256 def _summary_stats_old(flowcell_id, lane):
258 return a dictionary of summary stats for a given flowcell_id & lane.
260 fc_id, status = parse_flowcell_id(flowcell_id)
261 fc_result_dict = get_flowcell_result_dict(fc_id)
267 if fc_result_dict is None:
268 err_list.append('Results for Flowcell %s not found.' % (fc_id))
269 return (dict_list, err_list, summary_list)
271 for cnm in fc_result_dict:
273 xmlpath = fc_result_dict[cnm]['run_xml']
276 err_list.append('Run xml for Flowcell %s(%s) not found.' % (fc_id, cnm))
279 tree = ElementTree.parse(xmlpath).getroot()
280 results = runfolder.PipelineRun(pathname='', xml=tree)
282 lane_report = runfolder.summarize_lane(results.gerald, lane)
283 summary_list.append(os.linesep.join(lane_report))
285 summary_list.append("Summary report needs to be updated.")
286 logging.error("Exception: " + str(e))
288 print "----------------------------------"
289 print "-- DOES NOT SUPPORT PAIRED END ---"
290 print "----------------------------------"
291 lane_results = results.gerald.summary[0][lane]
296 d['average_alignment_score'] = lrs.average_alignment_score
297 d['average_first_cycle_intensity'] = lrs.average_first_cycle_intensity
298 d['cluster'] = lrs.cluster
300 d['flowcell'] = flowcell_id
302 d['percent_error_rate'] = lrs.percent_error_rate
303 d['percent_intensity_after_20_cycles'] = lrs.percent_intensity_after_20_cycles
304 d['percent_pass_filter_align'] = lrs.percent_pass_filter_align
305 d['percent_pass_filter_clusters'] = lrs.percent_pass_filter_clusters
307 #FIXME: function finished, but need to take advantage of
308 # may need to take in a list of lanes so we only have to
309 # load the xml file once per flowcell rather than once
313 return (dict_list, err_list, summary_list)
316 def get_eland_result_type(pathname):
318 Guess the eland result file type from the filename
320 path, filename = os.path.split(pathname)
321 if 'extended' in filename:
323 elif 'multi' in filename:
325 elif 'result' in filename:
330 def _make_eland_results(flowcell_id, lane, interesting_flowcells):
331 fc_id, status = parse_flowcell_id(flowcell_id)
332 cur_fc = interesting_flowcells.get(fc_id, None)
336 flowcell = FlowCell.objects.get(flowcell_id=flowcell_id)
337 # Loop throw storage devices if a result has been archived
339 if cur_fc is not None:
340 for lts in flowcell.longtermstorage_set.all():
341 for sd in lts.storage_devices.all():
342 # Use barcode_id if it exists
343 if sd.barcode_id is not None and sd.barcode_id != '':
344 storage_id_list.append(sd.barcode_id)
347 storage_id_list.append(sd.uuid)
349 # Formatting for template use
350 if len(storage_id_list) == 0:
353 storage_ids = ', '.join(storage_id_list)
356 for cycle in cur_fc.keys():
357 result_path = cur_fc[cycle]['eland_results'].get(lane, None)
358 result_link = make_result_link(fc_id, cycle, lane, result_path)
359 results.append({'flowcell_id': fc_id,
362 'summary_url': make_summary_url(flowcell_id, cycle),
363 'result_url': result_link[0],
364 'result_label': result_link[1],
365 'bed_url': result_link[2],
366 'storage_ids': storage_ids
370 def make_summary_url(flowcell_id, cycle_name):
371 url = '/results/%s/%s/summary/' % (flowcell_id, cycle_name)
374 def make_result_link(flowcell_id, cycle_name, lane, eland_result_path):
375 if eland_result_path is None:
378 result_type = get_eland_result_type(eland_result_path)
379 result_url = '/results/%s/%s/eland_result/%s' % (flowcell_id, cycle_name, lane)
380 result_label = 'eland %s' % (result_type,)
382 if result_type == 'result':
383 bed_url_pattern = '/results/%s/%s/bedfile/%s'
384 bed_url = bed_url_pattern % (flowcell_id, cycle_name, lane)
386 return (result_url, result_label, bed_url)
388 def _files(flowcell_id, lane):
390 Sets up available files for download
394 flowcell_id, id = parse_flowcell_id(flowcell_id)
395 d = get_flowcell_result_dict(flowcell_id)
402 # c_name == 'CN-M' (i.e. C1-33)
405 if d[c_name]['summary'] is not None:
406 output.append('<a href="/results/%s/%s/summary/">summary(%s)</a>' \
407 % (flowcell_id, c_name, c_name))
409 erd = d[c_name]['eland_results']
411 result_type = get_eland_result_type(erd[lane])
412 result_url_pattern = '<a href="/results/%s/%s/eland_result/%s">eland %s(%s)</a>'
413 output.append(result_url_pattern % (flowcell_id, c_name, lane, result_type, c_name))
414 if result_type == 'result':
415 bed_url_pattern = '<a href="/results/%s/%s/bedfile/%s">bedfile(%s)</a>'
416 output.append(bed_url_pattern % (flowcell_id, c_name, lane, c_name))
421 return '(' + '|'.join(output) + ')'
423 def library_id_to_admin_url(request, lib_id):
424 lib = Library.objects.get(library_id=lib_id)
425 return HttpResponseRedirect('/admin/samples/library/%s' % (lib.id,))
428 def user_profile(request):
430 Information about the user
433 'page_name': 'User Profile',
435 #'bcmagic': BarcodeMagicForm(),
436 #'select': 'settings',
438 context.update(SAMPLES_CONTEXT_DEFAULTS)
439 return render_to_response('registration/profile.html', context,
440 context_instance=RequestContext(request))