diff visualise.py @ 7:9e7927673089

intermediate commit before converting some tables to divs
author Jan Kanis <jan.code@jankanis.nl>
date Thu, 08 May 2014 16:51:52 +0200
parents 1df2bfce5c24
children 2fbdf2eb27b4
line wrap: on
line diff
--- a/visualise.py	Wed May 07 19:02:20 2014 +0200
+++ b/visualise.py	Thu May 08 16:51:52 2014 +0200
@@ -4,6 +4,7 @@
 # License: GPL version 3 or higher
 
 import sys
+import math
 import warnings
 from itertools import repeat
 from lxml import objectify
@@ -26,19 +27,24 @@
 
 blast = objectify.parse('blast xml example1.xml').getroot()
 loader = jinja2.FileSystemLoader(searchpath='.')
-environment = jinja2.Environment(loader=loader)
+environment = jinja2.Environment(loader=loader, lstrip_blocks=True, trim_blocks=True, autoescape=True)
 environment.filters['color'] = lambda length: match_colors[color_idx(length)]
 
+query_length = int(blast["BlastOutput_query-len"])
+
+hits = blast.BlastOutput_iterations.Iteration.Iteration_hits.Hit
+# sort hits by longest hotspot first
+ordered_hits = sorted(hits,
+                      key=lambda h: max(hsp['Hsp_align-len'] for hsp in h.Hit_hsps.Hsp),
+                      reverse=True)
+
 def match_colors():
     """
     An iterator that yields lists of length-color pairs. 
     """
+
+    percent_multiplier = 100 / query_length
     
-    hits = blast.BlastOutput_iterations.Iteration.Iteration_hits.Hit
-    query_length = blast["BlastOutput_query-len"]
-    # sort hits by longest hotspot first
-    hits = sorted(hits, key=lambda h: max(hsp['Hsp_align-len'] for hsp in h.Hit_hsps.Hsp), reverse=True)
-
     for hit in hits:
         # sort hotspots from short to long, so we can overwrite index colors of
         # short matches with those of long ones.
@@ -46,24 +52,58 @@
         table = bytearray([255]) * query_length
         for hsp in hotspots:
             frm = hsp['Hsp_query-from'] - 1
-            to = hsp['Hsp_query-to'] - 1
+            to = int(hsp['Hsp_query-to'])
             table[frm:to] = repeat(color_idx(hsp['Hsp_align-len']), to - frm)
 
         matches = []
         last = table[0]
         count = 0
-        for i in range(int(query_length)):
+        for i in range(query_length):
             if table[i] == last:
                 count += 1
                 continue
-            matches.append((count, colors[last] if last != 255 else 'none'))
+            matches.append((count * percent_multiplier, colors[last] if last != 255 else 'none'))
             last = table[i]
             count = 1
-        matches.append((count, colors[last] if last != 255 else 'none'))
+        matches.append((count * percent_multiplier, colors[last] if last != 255 else 'none'))
+
+        yield dict(colors=matches, link="#hit"+hit.Hit_num.text, defline=hit.Hit_def)
+
 
-        yield dict(colors=matches, link="#hit"+hit.Hit_num.text)
+def queryscale():
+    max_labels = 10
+    skip = math.ceil(query_length / max_labels)
+    percent_multiplier = 100 / query_length
+    for i in range(1, query_length+1):
+        if i % skip == 0:
+            yield dict(label = i, width = skip * percent_multiplier)
+    if query_length % skip != 0:
+        yield dict(label = query_length, width = (query_length % skip) * percent_multiplier)
 
 
+def hit_info():
+
+    for hit in ordered_hits:
+        hsps = hit.Hit_hsps.Hsp
+
+        cover = [False] * query_length
+        for hsp in hsps:
+            cover[hsp['Hsp_query-from']-1 : int(hsp['Hsp_query-to'])] = repeat(True, int(hsp['Hsp_align-len']))
+        cover_count = cover.count(True)
+        
+        def hsp_val(path):
+            return (hsp[path] for hsp in hsps)
+        
+        yield dict(description = hit.Hit_def,
+                   maxscore = max(hsp_val('Hsp_bit-score')),
+                   totalscore = sum(hsp_val('Hsp_bit-score')),
+                   cover = "{:.0%}".format(cover_count / query_length),
+                   e_value = min(hsp_val('Hsp_evalue')),
+                   # FIXME: is this the correct formula vv?
+                   ident = "{:.0%}".format(min(hsp.Hsp_identity / hsp['Hsp_align-len'] for hsp in hsps)),
+                   accession = hit.Hit_accession)
+                   
+        
 def main():
     template = environment.get_template('visualise.html.jinja')
 
@@ -78,9 +118,12 @@
         warnings.warn("Multiple 'Iteration' elements found, showing only the first")
 
     sys.stdout.write(template.render(blast=blast,
-                                     hits=blast.BlastOutput_iterations.Iteration.Iteration_hits.Hit,
+                                     length=query_length,
+                                     #hits=blast.BlastOutput_iterations.Iteration.Iteration_hits.Hit,
                                      colors=colors,
                                      match_colors=match_colors(),
+                                     queryscale=queryscale(),
+                                     hit_info=hit_info(),
                                      params=params))
 
 main()