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 }
92 def library(request, todo_only=False):
93 queryset = Library.objects.filter(hidden__exact=0)
95 queryset = queryset.filter(lane=None)
97 fcl = ChangeList(request, Library,
98 list_filter=['affiliations', 'library_species'],
99 search_fields=['id', 'library_name', 'amplified_from_sample__id'],
104 context = { 'cl': fcl, 'title': 'Library Index', 'todo_only': todo_only}
105 context.update(create_library_context(fcl))
106 t = get_template('samples/library_index.html')
107 c = RequestContext(request, context)
108 return HttpResponse( t.render(c) )
110 def library_todo(request):
111 return library(request, todo_only=True)
113 def library_to_flowcells(request, lib_id):
115 Display information about all the flowcells a library has been run on.
119 lib = Library.objects.get(id=lib_id)
121 return HttpResponse("Library %s does not exist" % (lib_id))
124 flowcell_run_results = {} # aka flowcells we're looking at
125 for lane in lib.lane_set.all():
127 flowcell_id, id = parse_flowcell_id(fc.flowcell_id)
128 if flowcell_id not in flowcell_run_results:
129 flowcell_run_results[flowcell_id] = get_flowcell_result_dict(flowcell_id)
130 flowcell_list.append((fc.flowcell_id, lane.lane_number))
133 lane_summary_list = []
135 for fc, lane_number in flowcell_list:
136 lane_summary, err_list = _summary_stats(fc, lane_number)
137 lane_summary_list.extend(lane_summary)
139 eland_results.extend(_make_eland_results(fc, lane_number, flowcell_run_results))
142 'page_name': 'Library Details',
144 'eland_results': eland_results,
145 'lane_summary_list': lane_summary_list,
147 context.update(SAMPLES_CONTEXT_DEFAULTS)
149 return render_to_response(
150 'samples/library_detail.html',
152 context_instance = RequestContext(request))
154 def lanes_for(request, username=None):
156 Generate a report of recent activity for a user
159 if username is not None:
160 user = HTSUser.objects.get(username=username)
161 query.update({'library__affiliations__users__id':user.id})
162 fcl = ChangeList(request, Lane,
164 search_fields=['flowcell__flowcell_id', 'library__id', 'library__library_name'],
166 queryset=Lane.objects.filter(**query)
169 context = { 'lanes': fcl, 'title': 'Lane Index'}
171 return render_to_response(
172 'samples/lanes_for.html',
174 context_instance = RequestContext(request)
178 def summaryhtm_fc_cnm(request, flowcell_id, cnm):
180 returns a Summary.htm file if it exists.
182 fc_id, status = parse_flowcell_id(flowcell_id)
183 d = get_flowcell_result_dict(fc_id)
186 return HttpResponse('<b>Results for Flowcell %s not found.</b>' % (fc_id))
189 return HttpResponse('<b>Results for Flowcell %s; %s not found.</b>' % (fc_id, cnm))
191 summary_filepath = d[cnm]['summary']
193 if summary_filepath is None:
194 return HttpResponse('<b>Summary.htm for Flowcell %s; %s not found.</b>' % (fc_id, cnm))
196 f = open(summary_filepath, 'r')
198 return HttpResponse(f)
201 def result_fc_cnm_eland_lane(request, flowcell_id, cnm, lane):
203 returns an eland_file upon calling.
205 fc_id, status = parse_flowcell_id(flowcell_id)
206 d = get_flowcell_result_dict(fc_id)
209 return HttpResponse('<b>Results for Flowcell %s not found.</b>' % (fc_id))
212 return HttpResponse('<b>Results for Flowcell %s; %s not found.</b>' % (fc_id, cnm))
214 erd = d[cnm]['eland_results']
218 return HttpResponse('<b>Results for Flowcell %s; %s; lane %s not found.</b>' % (fc_id, cnm, lane))
222 #f = opener.autoopen(filepath, 'r')
223 # return HttpResponse(f, mimetype="application/x-elandresult")
225 f = open(filepath, 'r')
226 return HttpResponse(f, mimetype='application/x-bzip2')
230 def bedfile_fc_cnm_eland_lane_ucsc(request, fc_id, cnm, lane):
232 returns a bed file for a given flowcell, CN-M (i.e. C1-33), and lane (ucsc compatible)
234 return bedfile_fc_cnm_eland_lane(request, fc_id, cnm, lane, ucsc_compatible=True)
237 def bedfile_fc_cnm_eland_lane(request, flowcell_id, cnm, lane, ucsc_compatible=False):
239 returns a bed file for a given flowcell, CN-M (i.e. C1-33), and lane
241 fc_id, status = parse_flowcell_id(flowcell_id)
242 d = get_flowcell_result_dict(fc_id)
245 return HttpResponse('<b>Results for Flowcell %s not found.</b>' % (fc_id))
248 return HttpResponse('<b>Results for Flowcell %s; %s not found.</b>' % (fc_id, cnm))
250 erd = d[cnm]['eland_results']
254 return HttpResponse('<b>Results for Flowcell %s; %s; lane %s not found.</b>' % (fc_id, cnm, lane))
259 fi = opener.autoopen(filepath, 'r')
262 name, description = makebed.make_description( fc_id, lane )
264 bedgen = makebed.make_bed_from_eland_generator(fi, name, description)
267 return HttpResponse(bedgen)
269 return HttpResponse(bedgen, mimetype="application/x-bedfile")
272 def _summary_stats(flowcell_id, lane_id):
274 Return the summary statistics for a given flowcell, lane, and end.
276 fc_id, status = parse_flowcell_id(flowcell_id)
277 fc_result_dict = get_flowcell_result_dict(fc_id)
282 if fc_result_dict is None:
283 err_list.append('Results for Flowcell %s not found.' % (fc_id))
284 return (summary_list, err_list)
286 for cycle_width in fc_result_dict:
287 xmlpath = fc_result_dict[cycle_width]['run_xml']
290 err_list.append('Run xml for Flowcell %s(%s) not found.' % (fc_id, cycle_width))
293 run = load_pipeline_run_xml(xmlpath)
294 gerald_summary = run.gerald.summary.lane_results
295 for end in range(len(gerald_summary)):
296 end_summary = run.gerald.eland_results.results[end]
297 if end_summary.has_key(lane_id):
298 eland_summary = run.gerald.eland_results.results[end][lane_id]
300 eland_summary = ResultLane(lane_id=lane_id, end=end)
301 # add information to lane_summary
302 eland_summary.flowcell_id = flowcell_id
303 if len(gerald_summary) > end and gerald_summary[end].has_key(lane_id):
304 eland_summary.clusters = gerald_summary[end][lane_id].cluster
306 eland_summary.clusters = None
307 eland_summary.cycle_width = cycle_width
308 if hasattr(eland_summary, 'genome_map'):
309 eland_summary.summarized_reads = runfolder.summarize_mapped_reads(
310 eland_summary.genome_map,
311 eland_summary.mapped_reads)
313 # grab some more information out of the flowcell db
314 flowcell = FlowCell.objects.get(flowcell_id=flowcell_id)
315 #pm_field = 'lane_%d_pM' % (lane_id)
316 lane_obj = flowcell.lane_set.get(lane_number=lane_id)
317 eland_summary.flowcell = flowcell
318 eland_summary.lane = lane_obj
320 summary_list.append(eland_summary)
322 #except Exception, e:
323 # summary_list.append("Summary report needs to be updated.")
324 # logging.error("Exception: " + str(e))
326 return (summary_list, err_list)
329 def get_eland_result_type(pathname):
331 Guess the eland result file type from the filename
333 path, filename = os.path.split(pathname)
334 if 'extended' in filename:
336 elif 'multi' in filename:
338 elif 'result' in filename:
343 def _make_eland_results(flowcell_id, lane_number, interesting_flowcells):
344 fc_id, status = parse_flowcell_id(flowcell_id)
345 cur_fc = interesting_flowcells.get(fc_id, None)
349 flowcell = FlowCell.objects.get(flowcell_id=flowcell_id)
350 lane = flowcell.lane_set.get(lane_number=lane_number)
351 # Loop throw storage devices if a result has been archived
353 if cur_fc is not None:
354 for lts in flowcell.longtermstorage_set.all():
355 for sd in lts.storage_devices.all():
356 # Use barcode_id if it exists
357 if sd.barcode_id is not None and sd.barcode_id != '':
358 storage_id_list.append(sd.barcode_id)
361 storage_id_list.append(sd.uuid)
363 # Formatting for template use
364 if len(storage_id_list) == 0:
367 storage_ids = ', '.join([ '<a href="/inventory/%s/">%s</a>' % (s,s) for s in storage_id_list ])
370 for cycle in cur_fc.keys():
371 result_path = cur_fc[cycle]['eland_results'].get(lane, None)
372 result_link = make_result_link(fc_id, cycle, lane, result_path)
373 results.append({'flowcell_id': fc_id,
374 'flowcell': flowcell,
375 'run_date': flowcell.run_date,
378 'summary_url': make_summary_url(flowcell_id, cycle),
379 'result_url': result_link[0],
380 'result_label': result_link[1],
381 'bed_url': result_link[2],
382 'storage_ids': storage_ids
386 def make_summary_url(flowcell_id, cycle_name):
387 url = '/results/%s/%s/summary/' % (flowcell_id, cycle_name)
390 def make_result_link(flowcell_id, cycle_name, lane, eland_result_path):
391 if eland_result_path is None:
394 result_type = get_eland_result_type(eland_result_path)
395 result_url = '/results/%s/%s/eland_result/%s' % (flowcell_id, cycle_name, lane)
396 result_label = 'eland %s' % (result_type,)
398 if result_type == 'result':
399 bed_url_pattern = '/results/%s/%s/bedfile/%s'
400 bed_url = bed_url_pattern % (flowcell_id, cycle_name, lane)
402 return (result_url, result_label, bed_url)
404 def _files(flowcell_id, lane):
406 Sets up available files for download
410 flowcell_id, id = parse_flowcell_id(flowcell_id)
411 d = get_flowcell_result_dict(flowcell_id)
418 # c_name == 'CN-M' (i.e. C1-33)
421 if d[c_name]['summary'] is not None:
422 output.append('<a href="/results/%s/%s/summary/">summary(%s)</a>' \
423 % (flowcell_id, c_name, c_name))
425 erd = d[c_name]['eland_results']
427 result_type = get_eland_result_type(erd[lane])
428 result_url_pattern = '<a href="/results/%s/%s/eland_result/%s">eland %s(%s)</a>'
429 output.append(result_url_pattern % (flowcell_id, c_name, lane, result_type, c_name))
430 if result_type == 'result':
431 bed_url_pattern = '<a href="/results/%s/%s/bedfile/%s">bedfile(%s)</a>'
432 output.append(bed_url_pattern % (flowcell_id, c_name, lane, c_name))
437 return '(' + '|'.join(output) + ')'
439 def library_id_to_admin_url(request, lib_id):
440 lib = Library.objects.get(id=lib_id)
441 return HttpResponseRedirect('/admin/samples/library/%s' % (lib.id,))
443 def library_dict(library_id):
445 Given a library id construct a dictionary containing important information
446 return None if nothing was found
449 lib = Library.objects.get(id = library_id)
450 except Library.DoesNotExist, e:
453 #lane_info = lane_information(lib.lane_set)
455 for lane in lib.lane_set.all():
456 lane_info.append( {'flowcell':lane.flowcell.flowcell_id,
457 'lane_number': lane.lane_number,
458 'paired_end': lane.flowcell.paired_end,
459 'read_length': lane.flowcell.read_length,
460 'status_code': lane.status,
461 'status': LANE_STATUS_MAP[lane.status]} )
465 # 'aligned_reads': lib.aligned_reads,
466 #'amplified_into_sample': lib.amplified_into_sample, # into is a colleciton...
467 #'amplified_from_sample_id': lib.amplified_from_sample,
468 #'antibody_name': lib.antibody_name(), # we have no antibodies.
469 'antibody_id': lib.antibody_id,
470 'cell_line_id': lib.cell_line_id,
471 'cell_line': unicode_or_none(lib.cell_line),
472 'experiment_type': lib.experiment_type.name,
473 'experiment_type_id': lib.experiment_type_id,
474 'gel_cut_size': lib.gel_cut_size,
475 'hidden': lib.hidden,
477 'insert_size': lib.insert_size,
478 'lane_set': lane_info,
479 'library_id': lib.id,
480 'library_name': lib.library_name,
481 'library_species': lib.library_species.scientific_name,
482 'library_species_id': lib.library_species_id,
483 #'library_type': lib.library_type.name,
484 'library_type_id': lib.library_type_id,
485 'made_for': lib.made_for,
486 'made_by': lib.made_by,
488 'replicate': lib.replicate,
489 'stopping_point': lib.stopping_point,
490 'successful_pM': unicode_or_none(lib.successful_pM),
491 'undiluted_concentration': unicode_or_none(lib.undiluted_concentration)
493 if lib.library_type_id is None:
494 info['library_type'] = None
496 info['library_type'] = lib.library_type.name
500 def library_json(request, library_id):
502 Return a json formatted library dictionary
504 require_api_key(request)
505 # what validation should we do on library_id?
507 lib = library_dict(library_id)
511 lib_json = json.dumps(lib)
512 return HttpResponse(lib_json, mimetype='application/json')
515 def species_json(request, species_id):
517 Return information about a species.
521 def species(request, species_id):
522 species = get_object_or_404(Species, id=species_id)
524 context = RequestContext(request,
525 { 'species': species })
527 return render_to_response("samples/species_detail.html", context)
529 def antibodies(request):
530 context = RequestContext(request,
531 {'antibodies': Antibody.objects.order_by('antigene')})
532 return render_to_response("samples/antibody_index.html", context)
535 def user_profile(request):
537 Information about the user
540 'page_name': 'User Profile',
542 #'bcmagic': BarcodeMagicForm(),
543 #'select': 'settings',
545 context.update(SAMPLES_CONTEXT_DEFAULTS)
546 return render_to_response('registration/profile.html', context,
547 context_instance=RequestContext(request))