Show the "Amplified from sample" as the parent library id and allow
[htsworkflow.git] / htsworkflow / frontend / samples / views.py
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
11
12 from django.http import HttpResponse
13 from django.template import RequestContext
14 from django.template.loader import get_template
15
16 import StringIO
17 import logging
18 import os
19
20 LANE_LIST = [1,2,3,4,5,6,7,8]
21
22 def create_library_context(cl):
23     """
24     Create a list of libraries that includes how many lanes were run
25     """
26     records = []
27     #for lib in library_items.object_list:
28     for lib in cl.result_list:
29        summary = {}
30        summary['library_id'] = lib.library_id
31        summary['library_name'] = lib.library_name
32        summary['species_name' ] = lib.library_species.scientific_name
33        if lib.amplified_from_sample is not None:
34            summary['amplified_from'] = lib.amplified_from_sample.library_id
35        else:
36            summary['amplified_from'] = ''
37        lanes_run = 0
38        for lane_id in LANE_LIST:
39            lane = getattr(lib, 'lane_%d_library' % (lane_id,))
40            lanes_run += len( lane.all() )
41        summary['lanes_run'] = lanes_run
42        records.append(summary)
43     cl.result_count = unicode(cl.paginator._count) + u" libraries"
44     return {'library_list': records }
45
46 def library(request):
47    # build changelist
48     fcl = ChangeList(request, Library,
49         list_filter=['affiliations', 'library_species'],
50         search_fields=['library_id', 'library_name', 'amplified_from_sample__library_id'],
51         list_per_page=200,
52         queryset=Library.objects.filter(hidden__exact=0)
53     )
54
55     context = { 'cl': fcl, 'title': 'Library Index'}
56     context.update(create_library_context(fcl))
57     t = get_template('samples/library_index.html')
58     c = RequestContext(request, context)
59     return HttpResponse( t.render(c) )
60
61 def library_to_flowcells(request, lib_id):
62     """
63     Display information about all the flowcells a library has been run on.
64     """
65     t = get_template("samples/library_detail.html")
66     
67     try:
68       lib = Library.objects.get(library_id=lib_id)
69     except:
70       return HttpResponse("Library %s does not exist" % (lib_id))
71     
72     output = []
73     
74     output.append('<b>Library ID:</b> %s' % (lib.library_id))
75     output.append('<b>Name:</b> %s' % (lib.library_name))
76     output.append('<b>Species:</b> %s' % (lib.library_species.scientific_name))
77     output.append('')
78     
79     output.append('<b>FLOWCELL - LANE:</b>')
80     
81     output.extend([ '%s - Lane 1 %s' % (fc.flowcell_id, _files(fc.flowcell_id, 1)) for fc in lib.lane_1_library.all() ])
82     output.extend([ '%s - Lane 2 %s' % (fc.flowcell_id, _files(fc.flowcell_id, 2)) for fc in lib.lane_2_library.all() ])
83     output.extend([ '%s - Lane 3 %s' % (fc.flowcell_id, _files(fc.flowcell_id, 3)) for fc in lib.lane_3_library.all() ])
84     output.extend([ '%s - Lane 4 %s' % (fc.flowcell_id, _files(fc.flowcell_id, 4)) for fc in lib.lane_4_library.all() ])
85     output.extend([ '%s - Lane 5 %s' % (fc.flowcell_id, _files(fc.flowcell_id, 5)) for fc in lib.lane_5_library.all() ])
86     output.extend([ '%s - Lane 6 %s' % (fc.flowcell_id, _files(fc.flowcell_id, 6)) for fc in lib.lane_6_library.all() ])
87     output.extend([ '%s - Lane 7 %s' % (fc.flowcell_id, _files(fc.flowcell_id, 7)) for fc in lib.lane_7_library.all() ])
88     output.extend([ '%s - Lane 8 %s' % (fc.flowcell_id, _files(fc.flowcell_id, 8)) for fc in lib.lane_8_library.all() ])
89     
90     record_count = lib.lane_1_library.count() + \
91                     lib.lane_2_library.count() + \
92                     lib.lane_3_library.count() + \
93                     lib.lane_4_library.count() + \
94                     lib.lane_5_library.count() + \
95                     lib.lane_6_library.count() + \
96                     lib.lane_7_library.count() + \
97                     lib.lane_8_library.count()
98     
99     flowcell_list = []
100     flowcell_list.extend([ (fc.flowcell_id, 1) for fc in lib.lane_1_library.all() ])
101     flowcell_list.extend([ (fc.flowcell_id, 2) for fc in lib.lane_2_library.all() ])
102     flowcell_list.extend([ (fc.flowcell_id, 3) for fc in lib.lane_3_library.all() ])
103     flowcell_list.extend([ (fc.flowcell_id, 4) for fc in lib.lane_4_library.all() ])
104     flowcell_list.extend([ (fc.flowcell_id, 5) for fc in lib.lane_5_library.all() ])
105     flowcell_list.extend([ (fc.flowcell_id, 6) for fc in lib.lane_6_library.all() ])
106     flowcell_list.extend([ (fc.flowcell_id, 7) for fc in lib.lane_7_library.all() ])
107     flowcell_list.extend([ (fc.flowcell_id, 8) for fc in lib.lane_8_library.all() ])
108     flowcell_list.sort()
109     
110     lane_summary_list = []
111     for fc, lane in flowcell_list:
112         lane_summary, err_list = _summary_stats(fc, lane)
113         
114         lane_summary_list.extend(lane_summary)
115     
116         for err in err_list:    
117             output.append(err)
118    
119     output.append('<br />')
120     output.append(t.render(RequestContext(request, {'lane_summary_list': lane_summary_list})))
121     output.append('<br />')
122     
123     if record_count == 0:
124         output.append("None Found")
125     
126     return HttpResponse('<br />\n'.join(output))
127
128
129 def summaryhtm_fc_cnm(request, fc_id, cnm):
130     """
131     returns a Summary.htm file if it exists.
132     """
133     fc_id, status = parse_flowcell_id(fc_id)
134     d = get_flowcell_result_dict(fc_id)
135     
136     if d is None:
137         return HttpResponse('<b>Results for Flowcell %s not found.</b>' % (fc_id))
138     
139     if cnm not in d:
140         return HttpResponse('<b>Results for Flowcell %s; %s not found.</b>' % (fc_id, cnm))
141     
142     summary_filepath = d[cnm]['summary']
143     
144     if summary_filepath is None:
145         return HttpResponse('<b>Summary.htm for Flowcell %s; %s not found.</b>' % (fc_id, cnm))
146     
147     f = open(summary_filepath, 'r')
148     
149     return HttpResponse(f)
150
151
152 def result_fc_cnm_eland_lane(request, fc_id, cnm, lane):
153     """
154     returns an eland_file upon calling.
155     """
156     fc_id, status = parse_flowcell_id(fc_id)
157     d = get_flowcell_result_dict(fc_id)
158     
159     if d is None:
160         return HttpResponse('<b>Results for Flowcell %s not found.</b>' % (fc_id))
161     
162     if cnm not in d:
163         return HttpResponse('<b>Results for Flowcell %s; %s not found.</b>' % (fc_id, cnm))
164     
165     erd = d[cnm]['eland_results']
166     lane = int(lane)
167     
168     if lane not in erd:
169         return HttpResponse('<b>Results for Flowcell %s; %s; lane %s not found.</b>' % (fc_id, cnm, lane))
170     
171     filepath = erd[lane]
172     
173     f = opener.autoopen(filepath, 'r')
174     
175     return HttpResponse(f, mimetype="application/x-elandresult")
176
177
178 def bedfile_fc_cnm_eland_lane_ucsc(request, fc_id, cnm, lane):
179     """
180     returns a bed file for a given flowcell, CN-M (i.e. C1-33), and lane (ucsc compatible)
181     """
182     return bedfile_fc_cnm_eland_lane(request, fc_id, cnm, lane, ucsc_compatible=True)
183
184
185 def bedfile_fc_cnm_eland_lane(request, fc_id, cnm, lane, ucsc_compatible=False):
186     """
187     returns a bed file for a given flowcell, CN-M (i.e. C1-33), and lane
188     """
189     fc_id, status = parse_flowcell_id(fc_id)
190     d = get_flowcell_result_dict(fc_id)
191     
192     if d is None:
193         return HttpResponse('<b>Results for Flowcell %s not found.</b>' % (fc_id))
194     
195     if cnm not in d:
196         return HttpResponse('<b>Results for Flowcell %s; %s not found.</b>' % (fc_id, cnm))
197     
198     erd = d[cnm]['eland_results']
199     lane = int(lane)
200     
201     if lane not in erd:
202         return HttpResponse('<b>Results for Flowcell %s; %s; lane %s not found.</b>' % (fc_id, cnm, lane))
203     
204     filepath = erd[lane]
205     
206     # Eland result file
207     fi = opener.autoopen(filepath, 'r')
208     # output memory file
209     
210     name, description = makebed.make_description( fc_id, lane )
211     
212     bedgen = makebed.make_bed_from_eland_generator(fi, name, description)
213     
214     if ucsc_compatible:
215         return HttpResponse(bedgen)
216     else:
217         return HttpResponse(bedgen, mimetype="application/x-bedfile")
218
219
220 def _summary_stats(flowcell_id, lane_id):
221     """
222     Return the summary statistics for a given flowcell, lane, and end.
223     """
224     fc_id, status = parse_flowcell_id(flowcell_id)
225     fc_result_dict = get_flowcell_result_dict(fc_id)
226
227     summary_list = []
228     err_list = []
229     
230     if fc_result_dict is None:
231         err_list.append('Results for Flowcell %s not found.' % (fc_id))
232         return (summary_list, err_list)
233
234     for cycle_width in fc_result_dict:
235         xmlpath = fc_result_dict[cycle_width]['run_xml']
236         
237         if xmlpath is None:
238             err_list.append('Run xml for Flowcell %s(%s) not found.' % (fc_id, cycle_width))
239             continue
240         
241         try:
242             run = load_pipeline_run_xml(xmlpath)
243             gerald_summary = run.gerald.summary.lane_results
244             for end in range(len(gerald_summary)):
245                 eland_summary = run.gerald.eland_results.results[end][lane_id]
246                 # add information to lane_summary
247                 eland_summary.flowcell_id = flowcell_id
248                 eland_summary.clusters = gerald_summary[end][lane_id].cluster
249                 eland_summary.cycle_width = cycle_width
250                 eland_summary.summarized_reads = runfolder.summarize_mapped_reads(eland_summary.genome_map, eland_summary.mapped_reads)
251
252                 # grab some more information out of the flowcell db
253                 flowcell = FlowCell.objects.get(flowcell_id=fc_id)
254                 pm_field = 'lane_%d_pM' % (lane_id)
255                 eland_summary.successful_pm = getattr(flowcell, pm_field)
256
257                 summary_list.append(eland_summary)
258
259         except Exception, e:
260             summary_list.append("Summary report needs to be updated.")
261             logging.error("Exception: " + str(e))
262     
263     return (summary_list, err_list)
264
265 def _summary_stats_old(flowcell_id, lane):
266     """
267     return a dictionary of summary stats for a given flowcell_id & lane.
268     """
269     fc_id, status = parse_flowcell_id(flowcell_id)
270     fc_result_dict = get_flowcell_result_dict(fc_id)
271     
272     dict_list = []
273     err_list = []
274     summary_list = []
275     
276     if fc_result_dict is None:
277         err_list.append('Results for Flowcell %s not found.' % (fc_id))
278         return (dict_list, err_list, summary_list)
279     
280     for cnm in fc_result_dict:
281     
282         xmlpath = fc_result_dict[cnm]['run_xml']
283         
284         if xmlpath is None:
285             err_list.append('Run xml for Flowcell %s(%s) not found.' % (fc_id, cnm))
286             continue
287         
288         tree = ElementTree.parse(xmlpath).getroot()
289         results = runfolder.PipelineRun(pathname='', xml=tree)
290         try:
291             lane_report = runfolder.summarize_lane(results.gerald, lane)
292             summary_list.append(os.linesep.join(lane_report))
293         except Exception, e:
294             summary_list.append("Summary report needs to be updated.")
295             logging.error("Exception: " + str(e))
296        
297         print "----------------------------------"
298         print "-- DOES NOT SUPPORT PAIRED END ---"
299         print "----------------------------------"
300         lane_results = results.gerald.summary[0][lane]
301         lrs = lane_results
302         
303         d = {}
304         
305         d['average_alignment_score'] = lrs.average_alignment_score
306         d['average_first_cycle_intensity'] = lrs.average_first_cycle_intensity
307         d['cluster'] = lrs.cluster
308         d['lane'] = lrs.lane
309         d['flowcell'] = flowcell_id
310         d['cnm'] = cnm
311         d['percent_error_rate'] = lrs.percent_error_rate
312         d['percent_intensity_after_20_cycles'] = lrs.percent_intensity_after_20_cycles
313         d['percent_pass_filter_align'] = lrs.percent_pass_filter_align
314         d['percent_pass_filter_clusters'] = lrs.percent_pass_filter_clusters
315         
316         #FIXME: function finished, but need to take advantage of
317         #   may need to take in a list of lanes so we only have to
318         #   load the xml file once per flowcell rather than once
319         #   per lane.
320         dict_list.append(d)
321     
322     return (dict_list, err_list, summary_list)
323     
324     
325 def get_eland_result_type(pathname):
326     """
327     Guess the eland result file type from the filename
328     """
329     path, filename = os.path.split(pathname)
330     if 'extended' in filename:
331         return 'extended'
332     elif 'multi' in filename:
333         return 'multi'
334     elif 'result' in filename:
335         return 'result'
336     else:
337         return 'unknown'
338     
339 def _files(flowcell_id, lane):
340     """
341     Sets up available files for download
342     """
343     lane = int(lane)
344
345     flowcell_id, id = parse_flowcell_id(flowcell_id)
346     d = get_flowcell_result_dict(flowcell_id)
347     
348     if d is None:
349         return ''
350     
351     output = []
352     
353     # c_name == 'CN-M' (i.e. C1-33)
354     for c_name in d:
355         
356         if d[c_name]['summary'] is not None:
357             output.append('<a href="/results/%s/%s/summary/">summary(%s)</a>' \
358                           % (flowcell_id, c_name, c_name))
359         
360         erd = d[c_name]['eland_results']
361         if lane in erd:
362             result_type = get_eland_result_type(erd[lane])
363             result_url_pattern = '<a href="/results/%s/%s/eland_result/%s">eland %s(%s)</a>'
364             output.append(result_url_pattern % (flowcell_id, c_name, lane, result_type, c_name))
365             if result_type == 'result':
366                 bed_url_pattern = '<a href="/results/%s/%s/bedfile/%s">bedfile(%s)</a>'
367                 output.append(bed_url_pattern % (flowcell_id, c_name, lane, c_name))
368     
369     if len(output) == 0:
370         return ''
371     
372     return '(' + '|'.join(output) + ')'
373