1 # Create your views here.
10 import simplejson as json
12 from django.contrib.csrf.middleware import csrf_exempt
13 from htsworkflow.frontend.auth import require_api_key
14 from htsworkflow.frontend.experiments.models import FlowCell, Lane, LANE_STATUS_MAP
15 from htsworkflow.frontend.samples.changelist import ChangeList
16 from htsworkflow.frontend.samples.models import Antibody, Library, Species, HTSUser
17 from htsworkflow.frontend.samples.results import get_flowcell_result_dict
18 from htsworkflow.frontend.bcmagic.forms import BarcodeMagicForm
19 from htsworkflow.pipelines.runfolder import load_pipeline_run_xml
20 from htsworkflow.pipelines import runfolder
21 from htsworkflow.pipelines.eland import ResultLane
22 from htsworkflow.util.conversion import unicode_or_none, parse_flowcell_id
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, get_object_or_404
30 from django.template import RequestContext
31 from django.template.loader import get_template
32 from django.contrib.auth.decorators import login_required
33 from django.conf import settings
35 LANE_LIST = [1,2,3,4,5,6,7,8]
36 SAMPLES_CONTEXT_DEFAULTS = {
37 'app_name': 'Flowcell/Library Tracker',
38 'bcmagic': BarcodeMagicForm()
41 def count_lanes(lane_set):
47 counts = [[0,0,0,],[0,0,0]]
49 for lane in lane_set.all():
50 if lane.flowcell.paired_end:
54 if lane.flowcell.read_length < 40:
55 read_type = short_read
56 elif lane.flowcell.read_length < 100:
57 read_type = medium_read
60 counts[lane_type][read_type] += 1
64 def create_library_context(cl):
66 Create a list of libraries that includes how many lanes were run
69 #for lib in library_items.object_list:
70 for lib in cl.result_list:
72 summary['library'] = lib
73 summary['library_id'] = lib.id
74 summary['library_name'] = lib.library_name
75 summary['species_name' ] = lib.library_species.scientific_name
76 if lib.amplified_from_sample is not None:
77 summary['amplified_from'] = lib.amplified_from_sample.id
79 summary['amplified_from'] = ''
80 lanes_run = count_lanes(lib.lane_set)
82 for row in xrange(len(lanes_run)):
83 for col in xrange(len(lanes_run[row])):
84 if lanes_run[row][col] == 0:
85 lanes_run[row][col] = ''
86 summary['lanes_run'] = lanes_run
87 summary['is_archived'] = lib.is_archived()
88 records.append(summary)
89 cl.result_count = unicode(cl.paginator._count)
90 return {'library_list': records }
94 fcl = ChangeList(request, Library,
95 list_filter=['affiliations', 'library_species'],
96 search_fields=['id', 'library_name', 'amplified_from_sample__id'],
98 queryset=Library.objects.filter(hidden__exact=0)
101 context = { 'cl': fcl, 'title': 'Library Index'}
102 context.update(create_library_context(fcl))
103 t = get_template('samples/library_index.html')
104 c = RequestContext(request, context)
105 return HttpResponse( t.render(c) )
108 def library_to_flowcells(request, lib_id):
110 Display information about all the flowcells a library has been run on.
114 lib = Library.objects.get(id=lib_id)
116 return HttpResponse("Library %s does not exist" % (lib_id))
119 flowcell_run_results = {} # aka flowcells we're looking at
120 for lane in lib.lane_set.all():
122 flowcell_id, id = parse_flowcell_id(fc.flowcell_id)
123 if flowcell_id not in flowcell_run_results:
124 flowcell_run_results[flowcell_id] = get_flowcell_result_dict(flowcell_id)
125 flowcell_list.append((fc.flowcell_id, lane.lane_number))
128 lane_summary_list = []
130 for fc, lane_number in flowcell_list:
131 lane_summary, err_list = _summary_stats(fc, lane_number)
132 lane_summary_list.extend(lane_summary)
134 eland_results.extend(_make_eland_results(fc, lane_number, flowcell_run_results))
137 'page_name': 'Library Details',
139 'eland_results': eland_results,
140 'lane_summary_list': lane_summary_list,
142 context.update(SAMPLES_CONTEXT_DEFAULTS)
144 return render_to_response(
145 'samples/library_detail.html',
147 context_instance = RequestContext(request))
149 def lanes_for(request, username=None):
151 Generate a report of recent activity for a user
154 if username is not None:
155 user = HTSUser.objects.get(username=username)
156 query.update({'library__affiliations__users__id':user.id})
157 fcl = ChangeList(request, Lane,
159 search_fields=['flowcell__flowcell_id', 'library__id', 'library__library_name'],
161 queryset=Lane.objects.filter(**query)
164 context = { 'lanes': fcl, 'title': 'Lane Index'}
166 return render_to_response(
167 'samples/lanes_for.html',
169 context_instance = RequestContext(request)
173 def summaryhtm_fc_cnm(request, flowcell_id, cnm):
175 returns a Summary.htm file if it exists.
177 fc_id, status = parse_flowcell_id(flowcell_id)
178 d = get_flowcell_result_dict(fc_id)
181 return HttpResponse('<b>Results for Flowcell %s not found.</b>' % (fc_id))
184 return HttpResponse('<b>Results for Flowcell %s; %s not found.</b>' % (fc_id, cnm))
186 summary_filepath = d[cnm]['summary']
188 if summary_filepath is None:
189 return HttpResponse('<b>Summary.htm for Flowcell %s; %s not found.</b>' % (fc_id, cnm))
191 f = open(summary_filepath, 'r')
193 return HttpResponse(f)
196 def result_fc_cnm_eland_lane(request, flowcell_id, cnm, lane):
198 returns an eland_file upon calling.
200 fc_id, status = parse_flowcell_id(flowcell_id)
201 d = get_flowcell_result_dict(fc_id)
204 return HttpResponse('<b>Results for Flowcell %s not found.</b>' % (fc_id))
207 return HttpResponse('<b>Results for Flowcell %s; %s not found.</b>' % (fc_id, cnm))
209 erd = d[cnm]['eland_results']
213 return HttpResponse('<b>Results for Flowcell %s; %s; lane %s not found.</b>' % (fc_id, cnm, lane))
217 #f = opener.autoopen(filepath, 'r')
218 # return HttpResponse(f, mimetype="application/x-elandresult")
220 f = open(filepath, 'r')
221 return HttpResponse(f, mimetype='application/x-bzip2')
225 def bedfile_fc_cnm_eland_lane_ucsc(request, fc_id, cnm, lane):
227 returns a bed file for a given flowcell, CN-M (i.e. C1-33), and lane (ucsc compatible)
229 return bedfile_fc_cnm_eland_lane(request, fc_id, cnm, lane, ucsc_compatible=True)
232 def bedfile_fc_cnm_eland_lane(request, flowcell_id, cnm, lane, ucsc_compatible=False):
234 returns a bed file for a given flowcell, CN-M (i.e. C1-33), and lane
236 fc_id, status = parse_flowcell_id(flowcell_id)
237 d = get_flowcell_result_dict(fc_id)
240 return HttpResponse('<b>Results for Flowcell %s not found.</b>' % (fc_id))
243 return HttpResponse('<b>Results for Flowcell %s; %s not found.</b>' % (fc_id, cnm))
245 erd = d[cnm]['eland_results']
249 return HttpResponse('<b>Results for Flowcell %s; %s; lane %s not found.</b>' % (fc_id, cnm, lane))
254 fi = opener.autoopen(filepath, 'r')
257 name, description = makebed.make_description( fc_id, lane )
259 bedgen = makebed.make_bed_from_eland_generator(fi, name, description)
262 return HttpResponse(bedgen)
264 return HttpResponse(bedgen, mimetype="application/x-bedfile")
267 def _summary_stats(flowcell_id, lane_id):
269 Return the summary statistics for a given flowcell, lane, and end.
271 fc_id, status = parse_flowcell_id(flowcell_id)
272 fc_result_dict = get_flowcell_result_dict(fc_id)
277 if fc_result_dict is None:
278 err_list.append('Results for Flowcell %s not found.' % (fc_id))
279 return (summary_list, err_list)
281 for cycle_width in fc_result_dict:
282 xmlpath = fc_result_dict[cycle_width]['run_xml']
285 err_list.append('Run xml for Flowcell %s(%s) not found.' % (fc_id, cycle_width))
288 run = load_pipeline_run_xml(xmlpath)
289 gerald_summary = run.gerald.summary.lane_results
290 for end in range(len(gerald_summary)):
291 end_summary = run.gerald.eland_results.results[end]
292 if end_summary.has_key(lane_id):
293 eland_summary = run.gerald.eland_results.results[end][lane_id]
295 eland_summary = ResultLane(lane_id=lane_id, end=end)
296 # add information to lane_summary
297 eland_summary.flowcell_id = flowcell_id
298 if len(gerald_summary) > end and gerald_summary[end].has_key(lane_id):
299 eland_summary.clusters = gerald_summary[end][lane_id].cluster
301 eland_summary.clusters = None
302 eland_summary.cycle_width = cycle_width
303 if hasattr(eland_summary, 'genome_map'):
304 eland_summary.summarized_reads = runfolder.summarize_mapped_reads(
305 eland_summary.genome_map,
306 eland_summary.mapped_reads)
308 # grab some more information out of the flowcell db
309 flowcell = FlowCell.objects.get(flowcell_id=flowcell_id)
310 #pm_field = 'lane_%d_pM' % (lane_id)
311 lane_obj = flowcell.lane_set.get(lane_number=lane_id)
312 eland_summary.flowcell = flowcell
313 eland_summary.lane = lane_obj
315 summary_list.append(eland_summary)
317 #except Exception, e:
318 # summary_list.append("Summary report needs to be updated.")
319 # logging.error("Exception: " + str(e))
321 return (summary_list, err_list)
324 def get_eland_result_type(pathname):
326 Guess the eland result file type from the filename
328 path, filename = os.path.split(pathname)
329 if 'extended' in filename:
331 elif 'multi' in filename:
333 elif 'result' in filename:
338 def _make_eland_results(flowcell_id, lane_number, interesting_flowcells):
339 fc_id, status = parse_flowcell_id(flowcell_id)
340 cur_fc = interesting_flowcells.get(fc_id, None)
344 flowcell = FlowCell.objects.get(flowcell_id=flowcell_id)
345 lane = flowcell.lane_set.get(lane_number=lane_number)
346 # Loop throw storage devices if a result has been archived
348 if cur_fc is not None:
349 for lts in flowcell.longtermstorage_set.all():
350 for sd in lts.storage_devices.all():
351 # Use barcode_id if it exists
352 if sd.barcode_id is not None and sd.barcode_id != '':
353 storage_id_list.append(sd.barcode_id)
356 storage_id_list.append(sd.uuid)
358 # Formatting for template use
359 if len(storage_id_list) == 0:
362 storage_ids = ', '.join([ '<a href="/inventory/%s/">%s</a>' % (s,s) for s in storage_id_list ])
365 for cycle in cur_fc.keys():
366 result_path = cur_fc[cycle]['eland_results'].get(lane, None)
367 result_link = make_result_link(fc_id, cycle, lane, result_path)
368 results.append({'flowcell_id': fc_id,
369 'flowcell': flowcell,
370 'run_date': flowcell.run_date,
373 'summary_url': make_summary_url(flowcell_id, cycle),
374 'result_url': result_link[0],
375 'result_label': result_link[1],
376 'bed_url': result_link[2],
377 'storage_ids': storage_ids
381 def make_summary_url(flowcell_id, cycle_name):
382 url = '/results/%s/%s/summary/' % (flowcell_id, cycle_name)
385 def make_result_link(flowcell_id, cycle_name, lane, eland_result_path):
386 if eland_result_path is None:
389 result_type = get_eland_result_type(eland_result_path)
390 result_url = '/results/%s/%s/eland_result/%s' % (flowcell_id, cycle_name, lane)
391 result_label = 'eland %s' % (result_type,)
393 if result_type == 'result':
394 bed_url_pattern = '/results/%s/%s/bedfile/%s'
395 bed_url = bed_url_pattern % (flowcell_id, cycle_name, lane)
397 return (result_url, result_label, bed_url)
399 def _files(flowcell_id, lane):
401 Sets up available files for download
405 flowcell_id, id = parse_flowcell_id(flowcell_id)
406 d = get_flowcell_result_dict(flowcell_id)
413 # c_name == 'CN-M' (i.e. C1-33)
416 if d[c_name]['summary'] is not None:
417 output.append('<a href="/results/%s/%s/summary/">summary(%s)</a>' \
418 % (flowcell_id, c_name, c_name))
420 erd = d[c_name]['eland_results']
422 result_type = get_eland_result_type(erd[lane])
423 result_url_pattern = '<a href="/results/%s/%s/eland_result/%s">eland %s(%s)</a>'
424 output.append(result_url_pattern % (flowcell_id, c_name, lane, result_type, c_name))
425 if result_type == 'result':
426 bed_url_pattern = '<a href="/results/%s/%s/bedfile/%s">bedfile(%s)</a>'
427 output.append(bed_url_pattern % (flowcell_id, c_name, lane, c_name))
432 return '(' + '|'.join(output) + ')'
434 def library_id_to_admin_url(request, lib_id):
435 lib = Library.objects.get(id=lib_id)
436 return HttpResponseRedirect('/admin/samples/library/%s' % (lib.id,))
438 def library_dict(library_id):
440 Given a library id construct a dictionary containing important information
441 return None if nothing was found
444 lib = Library.objects.get(id = library_id)
445 except Library.DoesNotExist, e:
448 #lane_info = lane_information(lib.lane_set)
450 for lane in lib.lane_set.all():
451 lane_info.append( {'flowcell':lane.flowcell.flowcell_id,
452 'lane_number': lane.lane_number,
453 'paired_end': lane.flowcell.paired_end,
454 'read_length': lane.flowcell.read_length,
455 'status_code': lane.status,
456 'status': LANE_STATUS_MAP[lane.status]} )
460 # 'aligned_reads': lib.aligned_reads,
461 #'amplified_into_sample': lib.amplified_into_sample, # into is a colleciton...
462 #'amplified_from_sample_id': lib.amplified_from_sample,
463 #'antibody_name': lib.antibody_name(), # we have no antibodies.
464 'antibody_id': lib.antibody_id,
465 'cell_line_id': lib.cell_line_id,
466 'cell_line': unicode_or_none(lib.cell_line),
467 'experiment_type': lib.experiment_type.name,
468 'experiment_type_id': lib.experiment_type_id,
469 'gel_cut_size': lib.gel_cut_size,
470 'hidden': lib.hidden,
472 'insert_size': lib.insert_size,
473 'lane_set': lane_info,
474 'library_id': lib.id,
475 'library_name': lib.library_name,
476 'library_species': lib.library_species.scientific_name,
477 'library_species_id': lib.library_species_id,
478 #'library_type': lib.library_type.name,
479 'library_type_id': lib.library_type_id,
480 'made_for': lib.made_for,
481 'made_by': lib.made_by,
483 'replicate': lib.replicate,
484 'stopping_point': lib.stopping_point,
485 'successful_pM': unicode_or_none(lib.successful_pM),
486 'undiluted_concentration': unicode_or_none(lib.undiluted_concentration)
488 if lib.library_type_id is None:
489 info['library_type'] = None
491 info['library_type'] = lib.library_type.name
495 def library_json(request, library_id):
497 Return a json formatted library dictionary
499 require_api_key(request)
500 # what validation should we do on library_id?
502 lib = library_dict(library_id)
506 lib_json = json.dumps(lib)
507 return HttpResponse(lib_json, mimetype='application/json')
510 def species_json(request, species_id):
512 Return information about a species.
516 def species(request, species_id):
517 species = get_object_or_404(Species, id=species_id)
519 context = RequestContext(request,
520 { 'species': species })
522 return render_to_response("samples/species_detail.html", context)
524 def antibodies(request):
525 context = RequestContext(request,
526 {'antibodies': Antibody.objects.order_by('antigene')})
527 return render_to_response("samples/antibody_index.html", context)
530 def user_profile(request):
532 Information about the user
535 'page_name': 'User Profile',
537 #'bcmagic': BarcodeMagicForm(),
538 #'select': 'settings',
540 context.update(SAMPLES_CONTEXT_DEFAULTS)
541 return render_to_response('registration/profile.html', context,
542 context_instance=RequestContext(request))