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
22 LANE_LIST = [1,2,3,4,5,6,7,8]
24 def create_library_context(cl):
26 Create a list of libraries that includes how many lanes were run
29 #for lib in library_items.object_list:
30 for lib in cl.result_list:
32 summary['library_id'] = lib.library_id
33 summary['library_name'] = lib.library_name
34 summary['species_name' ] = lib.library_species.scientific_name
35 if lib.amplified_from_sample is not None:
36 summary['amplified_from'] = lib.amplified_from_sample.library_id
38 summary['amplified_from'] = ''
40 for lane_id in LANE_LIST:
41 lane = getattr(lib, 'lane_%d_library' % (lane_id,))
42 lanes_run += len( lane.all() )
43 summary['lanes_run'] = lanes_run
44 summary['is_archived'] = lib.is_archived()
45 records.append(summary)
46 cl.result_count = unicode(cl.paginator._count) + u" libraries"
47 return {'library_list': records }
51 fcl = ChangeList(request, Library,
52 list_filter=['affiliations', 'library_species'],
53 search_fields=['library_id', 'library_name', 'amplified_from_sample__library_id'],
55 queryset=Library.objects.filter(hidden__exact=0)
58 context = { 'cl': fcl, 'title': 'Library Index'}
59 context.update(create_library_context(fcl))
60 t = get_template('samples/library_index.html')
61 c = RequestContext(request, context)
62 return HttpResponse( t.render(c) )
64 def library_to_flowcells(request, lib_id):
66 Display information about all the flowcells a library has been run on.
70 lib = Library.objects.get(library_id=lib_id)
72 return HttpResponse("Library %s does not exist" % (lib_id))
75 interesting_flowcells = {} # aka flowcells we're looking at
76 for lane in LANE_LIST:
77 lane_library = getattr(lib, 'lane_%d_library' % (lane,))
78 for fc in lane_library.all():
79 flowcell_id, id = parse_flowcell_id(fc.flowcell_id)
80 if flowcell_id not in interesting_flowcells:
81 interesting_flowcells[flowcell_id] = get_flowcell_result_dict(flowcell_id)
82 flowcell_list.append((fc.flowcell_id, lane))
86 lane_summary_list = []
88 for fc, lane in flowcell_list:
89 lane_summary, err_list = _summary_stats(fc, lane)
91 eland_results.extend(_make_eland_results(fc, lane, interesting_flowcells))
92 lane_summary_list.extend(lane_summary)
94 return render_to_response(
95 'samples/library_detail.html',
97 'eland_results': eland_results,
98 'lane_summary_list': lane_summary_list,
100 context_instance = RequestContext(request))
102 def summaryhtm_fc_cnm(request, flowcell_id, cnm):
104 returns a Summary.htm file if it exists.
106 fc_id, status = parse_flowcell_id(flowcell_id)
107 d = get_flowcell_result_dict(fc_id)
110 return HttpResponse('<b>Results for Flowcell %s not found.</b>' % (fc_id))
113 return HttpResponse('<b>Results for Flowcell %s; %s not found.</b>' % (fc_id, cnm))
115 summary_filepath = d[cnm]['summary']
117 if summary_filepath is None:
118 return HttpResponse('<b>Summary.htm for Flowcell %s; %s not found.</b>' % (fc_id, cnm))
120 f = open(summary_filepath, 'r')
122 return HttpResponse(f)
125 def result_fc_cnm_eland_lane(request, flowcell_id, cnm, lane):
127 returns an eland_file upon calling.
129 fc_id, status = parse_flowcell_id(flowcell_id)
130 d = get_flowcell_result_dict(fc_id)
133 return HttpResponse('<b>Results for Flowcell %s not found.</b>' % (fc_id))
136 return HttpResponse('<b>Results for Flowcell %s; %s not found.</b>' % (fc_id, cnm))
138 erd = d[cnm]['eland_results']
142 return HttpResponse('<b>Results for Flowcell %s; %s; lane %s not found.</b>' % (fc_id, cnm, lane))
146 #f = opener.autoopen(filepath, 'r')
147 # return HttpResponse(f, mimetype="application/x-elandresult")
149 f = open(filepath, 'r')
150 return HttpResponse(f, mimetype='application/x-bzip2')
154 def bedfile_fc_cnm_eland_lane_ucsc(request, fc_id, cnm, lane):
156 returns a bed file for a given flowcell, CN-M (i.e. C1-33), and lane (ucsc compatible)
158 return bedfile_fc_cnm_eland_lane(request, fc_id, cnm, lane, ucsc_compatible=True)
161 def bedfile_fc_cnm_eland_lane(request, flowcell_id, cnm, lane, ucsc_compatible=False):
163 returns a bed file for a given flowcell, CN-M (i.e. C1-33), and lane
165 fc_id, status = parse_flowcell_id(flowcell_id)
166 d = get_flowcell_result_dict(fc_id)
169 return HttpResponse('<b>Results for Flowcell %s not found.</b>' % (fc_id))
172 return HttpResponse('<b>Results for Flowcell %s; %s not found.</b>' % (fc_id, cnm))
174 erd = d[cnm]['eland_results']
178 return HttpResponse('<b>Results for Flowcell %s; %s; lane %s not found.</b>' % (fc_id, cnm, lane))
183 fi = opener.autoopen(filepath, 'r')
186 name, description = makebed.make_description( fc_id, lane )
188 bedgen = makebed.make_bed_from_eland_generator(fi, name, description)
191 return HttpResponse(bedgen)
193 return HttpResponse(bedgen, mimetype="application/x-bedfile")
196 def _summary_stats(flowcell_id, lane_id):
198 Return the summary statistics for a given flowcell, lane, and end.
200 fc_id, status = parse_flowcell_id(flowcell_id)
201 fc_result_dict = get_flowcell_result_dict(fc_id)
206 if fc_result_dict is None:
207 err_list.append('Results for Flowcell %s not found.' % (fc_id))
208 return (summary_list, err_list)
210 for cycle_width in fc_result_dict:
211 xmlpath = fc_result_dict[cycle_width]['run_xml']
214 err_list.append('Run xml for Flowcell %s(%s) not found.' % (fc_id, cycle_width))
217 run = load_pipeline_run_xml(xmlpath)
218 gerald_summary = run.gerald.summary.lane_results
219 for end in range(len(gerald_summary)):
220 eland_summary = run.gerald.eland_results.results[end][lane_id]
221 # add information to lane_summary
222 eland_summary.flowcell_id = flowcell_id
223 eland_summary.clusters = gerald_summary[end][lane_id].cluster
224 eland_summary.cycle_width = cycle_width
225 if hasattr(eland_summary, 'genome_map'):
226 eland_summary.summarized_reads = runfolder.summarize_mapped_reads(
227 eland_summary.genome_map,
228 eland_summary.mapped_reads)
230 # grab some more information out of the flowcell db
231 flowcell = FlowCell.objects.get(flowcell_id=flowcell_id)
232 pm_field = 'lane_%d_pM' % (lane_id)
233 eland_summary.successful_pm = getattr(flowcell, pm_field)
235 summary_list.append(eland_summary)
237 #except Exception, e:
238 # summary_list.append("Summary report needs to be updated.")
239 # logging.error("Exception: " + str(e))
241 return (summary_list, err_list)
243 def _summary_stats_old(flowcell_id, lane):
245 return a dictionary of summary stats for a given flowcell_id & lane.
247 fc_id, status = parse_flowcell_id(flowcell_id)
248 fc_result_dict = get_flowcell_result_dict(fc_id)
254 if fc_result_dict is None:
255 err_list.append('Results for Flowcell %s not found.' % (fc_id))
256 return (dict_list, err_list, summary_list)
258 for cnm in fc_result_dict:
260 xmlpath = fc_result_dict[cnm]['run_xml']
263 err_list.append('Run xml for Flowcell %s(%s) not found.' % (fc_id, cnm))
266 tree = ElementTree.parse(xmlpath).getroot()
267 results = runfolder.PipelineRun(pathname='', xml=tree)
269 lane_report = runfolder.summarize_lane(results.gerald, lane)
270 summary_list.append(os.linesep.join(lane_report))
272 summary_list.append("Summary report needs to be updated.")
273 logging.error("Exception: " + str(e))
275 print "----------------------------------"
276 print "-- DOES NOT SUPPORT PAIRED END ---"
277 print "----------------------------------"
278 lane_results = results.gerald.summary[0][lane]
283 d['average_alignment_score'] = lrs.average_alignment_score
284 d['average_first_cycle_intensity'] = lrs.average_first_cycle_intensity
285 d['cluster'] = lrs.cluster
287 d['flowcell'] = flowcell_id
289 d['percent_error_rate'] = lrs.percent_error_rate
290 d['percent_intensity_after_20_cycles'] = lrs.percent_intensity_after_20_cycles
291 d['percent_pass_filter_align'] = lrs.percent_pass_filter_align
292 d['percent_pass_filter_clusters'] = lrs.percent_pass_filter_clusters
294 #FIXME: function finished, but need to take advantage of
295 # may need to take in a list of lanes so we only have to
296 # load the xml file once per flowcell rather than once
300 return (dict_list, err_list, summary_list)
303 def get_eland_result_type(pathname):
305 Guess the eland result file type from the filename
307 path, filename = os.path.split(pathname)
308 if 'extended' in filename:
310 elif 'multi' in filename:
312 elif 'result' in filename:
317 def _make_eland_results(flowcell_id, lane, interesting_flowcells):
318 fc_id, status = parse_flowcell_id(flowcell_id)
319 cur_fc = interesting_flowcells.get(fc_id, None)
323 # Loop throw storage devices if a result has been archived
325 for lts in cur_fc.longtermstorage_set.all():
326 for sd in lts.storage_devices.all():
327 # Use barcode_id if it exists
328 if sd.barcode_id is not None and sd.barcode_id != '':
329 storage_id_list.append(sd.barcode_id)
332 storage_id_list.append(sd.uuid)
334 # Formatting for template use
335 if len(storage_id_list) == 0:
338 storage_ids = ', '.join(storage_id_list)
341 for cycle in cur_fc.keys():
342 result_path = cur_fc[cycle]['eland_results'].get(lane, None)
343 result_link = make_result_link(fc_id, cycle, lane, result_path)
344 results.append({'flowcell_id': fc_id,
347 'summary_url': make_summary_url(flowcell_id, cycle),
348 'result_url': result_link[0],
349 'result_label': result_link[1],
350 'bed_url': result_link[2],
351 'storage_ids': storage_ids
355 def make_summary_url(flowcell_id, cycle_name):
356 url = '/results/%s/%s/summary/' % (flowcell_id, cycle_name)
359 def make_result_link(flowcell_id, cycle_name, lane, eland_result_path):
360 if eland_result_path is None:
363 result_type = get_eland_result_type(eland_result_path)
364 result_url = '/results/%s/%s/eland_result/%s' % (flowcell_id, cycle_name, lane)
365 result_label = 'eland %s' % (result_type,)
367 if result_type == 'result':
368 bed_url_pattern = '/results/%s/%s/bedfile/%s'
369 bed_url = bed_url_pattern % (flowcell_id, cycle_name, lane)
371 return (result_url, result_label, bed_url)
373 def _files(flowcell_id, lane):
375 Sets up available files for download
379 flowcell_id, id = parse_flowcell_id(flowcell_id)
380 d = get_flowcell_result_dict(flowcell_id)
387 # c_name == 'CN-M' (i.e. C1-33)
390 if d[c_name]['summary'] is not None:
391 output.append('<a href="/results/%s/%s/summary/">summary(%s)</a>' \
392 % (flowcell_id, c_name, c_name))
394 erd = d[c_name]['eland_results']
396 result_type = get_eland_result_type(erd[lane])
397 result_url_pattern = '<a href="/results/%s/%s/eland_result/%s">eland %s(%s)</a>'
398 output.append(result_url_pattern % (flowcell_id, c_name, lane, result_type, c_name))
399 if result_type == 'result':
400 bed_url_pattern = '<a href="/results/%s/%s/bedfile/%s">bedfile(%s)</a>'
401 output.append(bed_url_pattern % (flowcell_id, c_name, lane, c_name))
406 return '(' + '|'.join(output) + ')'
408 def library_id_to_admin_url(request, lib_id):
409 lib = Library.objects.get(library_id=lib_id)
410 return HttpResponseRedirect('/admin/samples/library/%s' % (lib.id,))