comparison visualise.py @ 5:1df2bfce5c24

first features are working, partial match table
author Jan Kanis <jan.code@jankanis.nl>
date Wed, 07 May 2014 18:49:54 +0200
parents
children 9e7927673089
comparison
equal deleted inserted replaced
4:34211f5b83fd 5:1df2bfce5c24
1 #!/usr/bin/env python3
2
3 # Copyright The Hyve B.V. 2014
4 # License: GPL version 3 or higher
5
6 import sys
7 import warnings
8 from itertools import repeat
9 from lxml import objectify
10 import jinja2
11
12
13 def color_idx(length):
14 if length < 40:
15 return 0
16 elif length < 50:
17 return 1
18 elif length < 80:
19 return 2
20 elif length < 200:
21 return 3
22 return 4
23
24
25 colors = ['black', 'blue', 'green', 'magenta', 'red']
26
27 blast = objectify.parse('blast xml example1.xml').getroot()
28 loader = jinja2.FileSystemLoader(searchpath='.')
29 environment = jinja2.Environment(loader=loader)
30 environment.filters['color'] = lambda length: match_colors[color_idx(length)]
31
32 def match_colors():
33 """
34 An iterator that yields lists of length-color pairs.
35 """
36
37 hits = blast.BlastOutput_iterations.Iteration.Iteration_hits.Hit
38 query_length = blast["BlastOutput_query-len"]
39 # sort hits by longest hotspot first
40 hits = sorted(hits, key=lambda h: max(hsp['Hsp_align-len'] for hsp in h.Hit_hsps.Hsp), reverse=True)
41
42 for hit in hits:
43 # sort hotspots from short to long, so we can overwrite index colors of
44 # short matches with those of long ones.
45 hotspots = sorted(hit.Hit_hsps.Hsp, key=lambda hsp: hsp['Hsp_align-len'])
46 table = bytearray([255]) * query_length
47 for hsp in hotspots:
48 frm = hsp['Hsp_query-from'] - 1
49 to = hsp['Hsp_query-to'] - 1
50 table[frm:to] = repeat(color_idx(hsp['Hsp_align-len']), to - frm)
51
52 matches = []
53 last = table[0]
54 count = 0
55 for i in range(int(query_length)):
56 if table[i] == last:
57 count += 1
58 continue
59 matches.append((count, colors[last] if last != 255 else 'none'))
60 last = table[i]
61 count = 1
62 matches.append((count, colors[last] if last != 255 else 'none'))
63
64 yield dict(colors=matches, link="#hit"+hit.Hit_num.text)
65
66
67 def main():
68 template = environment.get_template('visualise.html.jinja')
69
70 params = (('Query ID', blast["BlastOutput_query-ID"]),
71 ('Query definition', blast["BlastOutput_query-def"]),
72 ('Query length', blast["BlastOutput_query-len"]),
73 ('Program', blast.BlastOutput_version),
74 ('Database', blast.BlastOutput_db),
75 )
76
77 if len(blast.BlastOutput_iterations.Iteration) > 1:
78 warnings.warn("Multiple 'Iteration' elements found, showing only the first")
79
80 sys.stdout.write(template.render(blast=blast,
81 hits=blast.BlastOutput_iterations.Iteration.Iteration_hits.Hit,
82 colors=colors,
83 match_colors=match_colors(),
84 params=params))
85
86 main()