1 from __future__ import absolute_import, print_function, unicode_literals
3 # Create your views here.
8 from django.contrib.admin.sites import site as admin_site
9 from django.views.decorators.csrf import csrf_exempt
10 from django.http import HttpResponse, HttpResponseRedirect, Http404
11 from django.shortcuts import render, get_object_or_404
12 from django.template import RequestContext
13 from django.template.loader import get_template
14 from django.contrib.auth.decorators import login_required
16 from htsworkflow.auth import require_api_key
17 from experiments.models import FlowCell, LANE_STATUS_MAP
18 from .changelist import HTSChangeList
19 from .models import Antibody, Library, Species
20 from .admin import LibraryOptions
21 from .results import get_flowcell_result_dict
22 from bcmagic.forms import BarcodeMagicForm
23 from htsworkflow.pipelines import runfolder
24 from htsworkflow.pipelines.samplekey import SampleKey
25 from htsworkflow.util.conversion import str_or_none, parse_flowcell_id
26 from htsworkflow.util import makebed
27 from htsworkflow.util import opener
29 LANE_LIST = [1, 2, 3, 4, 5, 6, 7, 8]
30 SAMPLES_CONTEXT_DEFAULTS = {
31 'app_name': 'Flowcell/Library Tracker',
32 'bcmagic': BarcodeMagicForm()
35 LOGGER = logging.getLogger(__name__)
38 def library(request, todo_only=False):
39 filters = {'hidden__exact': 0}
41 filters['lane'] = None
43 fcl = HTSChangeList(request, Library,
44 list_filter=['affiliations', 'library_species'],
45 search_fields=['id', 'library_name', 'amplified_from_sample__id'],
47 model_admin=LibraryOptions(Library, admin_site),
51 'library_list': fcl.result_list,
52 'title': 'Library Index',
53 'todo_only': todo_only}
55 t = get_template('samples/library_index.html')
56 c = RequestContext(request, context)
57 return HttpResponse(t.render(c))
60 def library_not_run(request):
61 return library(request, todo_only=True)
64 def library_to_flowcells(request, lib_id):
66 Display information about all the flowcells a library has been run on.
69 lib = Library.objects.get(id=lib_id)
71 raise Http404('Library %s does not exist' % (lib_id,))
74 flowcell_run_results = {} # aka flowcells we're looking at
75 for lane in lib.lane_set.all():
77 flowcell_id, id = parse_flowcell_id(fc.flowcell_id)
78 if flowcell_id not in flowcell_run_results:
79 flowcell_run_results[flowcell_id] = get_flowcell_result_dict(flowcell_id)
80 flowcell_list.append((fc.flowcell_id, lane.lane_number))
83 lane_summary_list = []
85 for fc, lane_number in flowcell_list:
86 lane_summary, err_list = _summary_stats(fc, lane_number, lib_id)
87 lane_summary_list.extend(lane_summary)
89 eland_results.extend(_make_eland_results(fc, lane_number, flowcell_run_results))
92 'page_name': 'Library Details',
94 'eland_results': eland_results,
95 'lane_summary_list': lane_summary_list,
97 context.update(SAMPLES_CONTEXT_DEFAULTS)
99 return render(request, 'samples/library_detail.html', context)
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, content_type="application/x-elandresult")
149 f = open(filepath, 'r')
150 return HttpResponse(f, content_type='application/x-bzip2')
153 def bedfile_fc_cnm_eland_lane_ucsc(request, fc_id, cnm, lane):
155 returns a bed file for a given flowcell, CN-M (i.e. C1-33), and lane (ucsc compatible)
157 return bedfile_fc_cnm_eland_lane(request, fc_id, cnm, lane, ucsc_compatible=True)
160 def bedfile_fc_cnm_eland_lane(request, flowcell_id, cnm, lane, ucsc_compatible=False):
162 returns a bed file for a given flowcell, CN-M (i.e. C1-33), and lane
164 fc_id, status = parse_flowcell_id(flowcell_id)
165 d = get_flowcell_result_dict(fc_id)
168 return HttpResponse('<b>Results for Flowcell %s not found.</b>' % (fc_id))
171 return HttpResponse('<b>Results for Flowcell %s; %s not found.</b>' % (fc_id, cnm))
173 erd = d[cnm]['eland_results']
177 return HttpResponse('<b>Results for Flowcell %s; %s; lane %s not found.</b>' % (fc_id, cnm, lane))
182 fi = opener.autoopen(filepath, 'r')
185 name, description = makebed.make_description(fc_id, lane)
187 bedgen = makebed.make_bed_from_eland_generator(fi, name, description)
190 return HttpResponse(bedgen)
192 return HttpResponse(bedgen, content_type="application/x-bedfile")
195 def _summary_stats(flowcell_id, lane_id, library_id):
197 Return the summary statistics for a given flowcell, lane, and end.
199 fc_id, status = parse_flowcell_id(flowcell_id)
200 fc_result_dict = get_flowcell_result_dict(fc_id)
205 if fc_result_dict is None:
206 err_list.append('Results for Flowcell %s not found.' % (fc_id))
207 return (summary_list, err_list)
209 for cycle_width in fc_result_dict:
210 xmlpath = fc_result_dict[cycle_width]['run_xml']
213 err_list.append('Run xml for Flowcell %s(%s) not found.' % (fc_id, cycle_width))
216 run = runfolder.load_pipeline_run_xml(xmlpath)
217 # skip if we don't have available metadata.
218 if run.gerald is None or run.gerald.summary is None:
221 gerald_summary = run.gerald.summary.lane_results
222 key = SampleKey(lane=lane_id, sample='s')
223 eland_results = list(run.gerald.eland_results.find_keys(key))
224 key = SampleKey(lane=lane_id, sample=library_id)
225 eland_results.extend(run.gerald.eland_results.find_keys(key))
226 for key in eland_results:
227 eland_summary = run.gerald.eland_results.results[key]
228 # add information to lane_summary
229 eland_summary.flowcell_id = flowcell_id
231 read = key.read-1 if key.read is not None else 0
233 eland_summary.clusters = gerald_summary[read][key.lane].cluster
234 except (IndexError, KeyError) as e:
235 eland_summary.clustes = None
236 eland_summary.cycle_width = cycle_width
237 if hasattr(eland_summary, 'genome_map'):
238 eland_summary.summarized_reads = runfolder.summarize_mapped_reads(
239 eland_summary.genome_map,
240 eland_summary.mapped_reads)
242 # grab some more information out of the flowcell db
243 flowcell = FlowCell.objects.get(flowcell_id=flowcell_id)
244 #pm_field = 'lane_%d_pM' % (lane_id)
245 lanes = flowcell.lane_set.filter(lane_number=lane_id)
246 eland_summary.flowcell = flowcell
247 eland_summary.lanes = lanes
249 summary_list.append(eland_summary)
251 #except Exception as e:
252 # summary_list.append("Summary report needs to be updated.")
253 # LOGGER.error("Exception: " + str(e))
255 return (summary_list, err_list)
258 def get_eland_result_type(pathname):
260 Guess the eland result file type from the filename
262 path, filename = os.path.split(pathname)
263 if 'extended' in filename:
265 elif 'multi' in filename:
267 elif 'result' in filename:
273 def _make_eland_results(flowcell_id, lane_number, interesting_flowcells):
274 fc_id, status = parse_flowcell_id(flowcell_id)
275 cur_fc = interesting_flowcells.get(fc_id, None)
279 flowcell = FlowCell.objects.get(flowcell_id=flowcell_id)
280 lanes = flowcell.lane_set.filter(lane_number=lane_number)
281 # Loop throw storage devices if a result has been archived
283 if cur_fc is not None:
284 for lts in flowcell.longtermstorage_set.all():
285 for sd in lts.storage_devices.all():
286 # Use barcode_id if it exists
287 if sd.barcode_id is not None and sd.barcode_id != '':
288 storage_id_list.append(sd.barcode_id)
291 storage_id_list.append(sd.uuid)
293 # Formatting for template use
294 if len(storage_id_list) == 0:
297 storage_ids = ', '.join(['<a href="/inventory/%s/">%s</a>' % (s, s) for s in storage_id_list])
300 for cycle in cur_fc.keys():
301 result_path = cur_fc[cycle]['eland_results'].get(lanes[0], None)
302 result_link = make_result_link(fc_id, cycle, lanes[0], result_path)
303 results.append({'flowcell_id': fc_id,
304 'flowcell': flowcell,
305 'run_date': flowcell.run_date,
308 'summary_url': make_summary_url(flowcell_id, cycle),
309 'result_url': result_link[0],
310 'result_label': result_link[1],
311 'bed_url': result_link[2],
312 'storage_ids': storage_ids})
316 def make_summary_url(flowcell_id, cycle_name):
317 url = '/results/%s/%s/summary/' % (flowcell_id, cycle_name)
321 def make_result_link(flowcell_id, cycle_name, lane, eland_result_path):
322 if eland_result_path is None:
325 result_type = get_eland_result_type(eland_result_path)
326 result_url = '/results/%s/%s/eland_result/%s' % (flowcell_id, cycle_name, lane)
327 result_label = 'eland %s' % (result_type,)
329 if result_type == 'result':
330 bed_url_pattern = '/results/%s/%s/bedfile/%s'
331 bed_url = bed_url_pattern % (flowcell_id, cycle_name, lane)
333 return (result_url, result_label, bed_url)
336 def _files(flowcell_id, lane):
338 Sets up available files for download
342 flowcell_id, id = parse_flowcell_id(flowcell_id)
343 d = get_flowcell_result_dict(flowcell_id)
350 # c_name == 'CN-M' (i.e. C1-33)
353 if d[c_name]['summary'] is not None:
354 output.append('<a href="/results/%s/%s/summary/">summary(%s)</a>' %
355 (flowcell_id, c_name, c_name))
357 erd = d[c_name]['eland_results']
359 result_type = get_eland_result_type(erd[lane])
360 result_url_pattern = '<a href="/results/%s/%s/eland_result/%s">eland %s(%s)</a>'
361 output.append(result_url_pattern % (flowcell_id, c_name, lane, result_type, c_name))
362 if result_type == 'result':
363 bed_url_pattern = '<a href="/results/%s/%s/bedfile/%s">bedfile(%s)</a>'
364 output.append(bed_url_pattern % (flowcell_id, c_name, lane, c_name))
369 return '(' + '|'.join(output) + ')'
372 def library_id_to_admin_url(request, lib_id):
373 lib = Library.objects.get(id=lib_id)
374 return HttpResponseRedirect('/admin/samples/library/%s' % (lib.id,))
377 def library_dict(library_id):
379 Given a library id construct a dictionary containing important information
380 return None if nothing was found
383 lib = Library.objects.get(id=library_id)
384 except Library.DoesNotExist as e:
387 #lane_info = lane_information(lib.lane_set)
389 for lane in lib.lane_set.all():
390 lane_info.append({'flowcell': lane.flowcell.flowcell_id,
391 'lane_number': lane.lane_number,
393 'paired_end': lane.flowcell.paired_end,
394 'read_length': lane.flowcell.read_length,
395 'status_code': lane.status,
396 'status': LANE_STATUS_MAP[lane.status]})
400 # 'aligned_reads': lib.aligned_reads,
401 #'amplified_into_sample': lib.amplified_into_sample, # into is a colleciton...
402 #'amplified_from_sample_id': lib.amplified_from_sample,
403 #'antibody_name': lib.antibody_name(), # we have no antibodies.
404 'antibody_id': lib.antibody_id,
405 'cell_line_id': lib.cell_line_id,
406 'cell_line': str_or_none(lib.cell_line),
407 'experiment_type': lib.experiment_type.name,
408 'experiment_type_id': lib.experiment_type_id,
409 'gel_cut_size': lib.gel_cut_size,
410 'hidden': lib.hidden,
412 'insert_size': lib.insert_size,
413 'lane_set': lane_info,
414 'library_id': lib.id,
415 'library_name': lib.library_name,
416 'library_species': lib.library_species.scientific_name,
417 'library_species_id': lib.library_species_id,
418 #'library_type': lib.library_type.name,
419 'library_type_id': lib.library_type_id,
420 'made_for': lib.made_for,
421 'made_by': lib.made_by,
423 'replicate': lib.replicate,
424 'stopping_point': lib.stopping_point,
425 'successful_pM': str_or_none(lib.successful_pM),
426 'undiluted_concentration': str_or_none(lib.undiluted_concentration)
428 if lib.library_type_id is None:
429 info['library_type'] = None
431 info['library_type'] = lib.library_type.name
436 def library_json(request, library_id):
438 Return a json formatted library dictionary
440 require_api_key(request)
441 # what validation should we do on library_id?
443 lib = library_dict(library_id)
447 lib_json = json.dumps({'result': lib})
448 return HttpResponse(lib_json, content_type='application/json')
452 def species_json(request, species_id):
454 Return information about a species.
459 def species(request, species_id):
460 species = get_object_or_404(Species, id=species_id)
462 context = {'species': species}
464 return render(request, "samples/species_detail.html", context)
467 def antibodies(request):
468 context = {'antibodies': Antibody.objects.order_by('antigene')}
469 return render(request, "samples/antibody_index.html", context)
473 def user_profile(request):
475 Information about the user
478 'page_name': 'User Profile',
480 # 'bcmagic': BarcodeMagicForm(),
481 # 'select': 'settings',
483 context.update(SAMPLES_CONTEXT_DEFAULTS)
484 return render(requst, 'registration/profile.html', context)