File: test_KGML_graphics.py

package info (click to toggle)
python-biopython 1.68%2Bdfsg-3~bpo8%2B1
  • links: PTS, VCS
  • area: main
  • in suites: jessie-backports
  • size: 46,856 kB
  • sloc: python: 160,306; xml: 93,216; ansic: 9,118; sql: 1,208; makefile: 155; sh: 63
file content (188 lines) | stat: -rw-r--r-- 8,009 bytes parent folder | download | duplicates (2)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
#!/usr/bin/env python
#
# Copyright 2013, 2014 by Leighton Pritchard.  All rights reserved.
# This code is part of the Biopython distribution and governed by its
# license.  Please see the LICENSE file that should have been included
# as part of this package.

"""Tests for general functionality of the KGML modules."""

# Builtins
from __future__ import with_statement
import os
import unittest

# Biopython
from Bio.Graphics.ColorSpiral import ColorSpiral

# Do we have ReportLab?  Raise error if not present.
from Bio import MissingExternalDependencyError
try:
    # Not actually using these imports directly:
    from reportlab.pdfgen.canvas import Canvas
    from reportlab.lib.pagesizes import A4
    from reportlab.lib.colors import HexColor
except ImportError:
    raise MissingExternalDependencyError(
        "Install reportlab if you want to use Bio.Graphics.")

try:
    c = HexColor('#8080F780')
except TypeError:
    # Known to fail under ReportLab 2.6 with:
    # unsupported operand type(s) for &: 'int' and 'float'
    # ReportLab 2.7+ also offers hasAlpha=True rather than alpha=True
    raise MissingExternalDependencyError(
        "Install at least reportlab 2.7 for transparency support.")

# Do we have PIL?
try:
    from PIL import Image
except ImportError:
    raise MissingExternalDependencyError(
        "Install Pillow or its predecessor PIL (Python Imaging Library) "
        "if you want to use bitmaps from KGML.")


# Biopython Bio.KEGG.KGML
from Bio.KEGG.KGML.KGML_parser import read
from Bio.Graphics.KGML_vis import KGMLCanvas

__docformat__ = "restructuredtext en"


# The PathwayData class is also imported by the online test module in
# test_KGML_graphics_online.py
class PathwayData(object):
    """Convenience structure for testing pathway data"""
    def __init__(self, name, element_counts, show_pathway_image=False):
        self.infilename = os.path.join("KEGG", "ko%s.xml" % name)
        self.outfilename = os.path.join("KEGG", "ko%s.kgml" % name)
        self.element_counts = element_counts
        self.pathway_image = os.path.join("KEGG", "map%s.png" % name)
        self.show_pathway_image = show_pathway_image
        self.output_stem = "Graphics/map%s" % name


class KGMLPathwayTest(unittest.TestCase):
    """Import XML file and write KGML

    Import the ko01100 metabolic map from a local .xml KGML file,
    and write valid KGML output for each.
    """
    def setUp(self):
        # Does our output directory exist?  If not, create it
        if not os.path.isdir('KEGG'):
            os.mkdir('KEGG')
        # Define some data to work with as a list of tuples:
        # (infilename, outfilename, (entry_count, ortholog_count,
        # compound_count, map_counts), pathway_image,
        # show_image_map)
        self.data = [
            PathwayData("01100", (3628, 1726, 1746, 149)),
            PathwayData("03070", (81, 72, 8, 1), True),
            ]
        # A list of KO IDs that we're going to use to modify pathway
        # appearance. These are KO IDs for reactions that take part in ko00020,
        # the TCA cycle
        self.ko_ids = \
            set(['ko:K00239', 'ko:K00240', 'ko:K00241', 'ko:K00242',
                 'ko:K00244', 'ko:K00245', 'ko:K00246', 'ko:K00247',
                 'ko:K00174', 'ko:K00175', 'ko:K00177', 'ko:K00176',
                 'ko:K00382', 'ko:K00164', 'ko:K00164', 'ko:K00658',
                 'ko:K01902', 'ko:K01903', 'ko:K01899', 'ko:K01900',
                 'ko:K01899', 'ko:K01900', 'ko:K00031', 'ko:K00030',
                 'ko:K00031', 'ko:K01648', 'ko:K00234', 'ko:K00235',
                 'ko:K00236', 'ko:K00237', 'ko:K01676', 'ko:K01677',
                 'ko:K01678', 'ko:K01679', 'ko:K01681', 'ko:K01682',
                 'ko:K01681', 'ko:K01682', 'ko:K01647', 'ko:K00025',
                 'ko:K00026', 'ko:K00024', 'ko:K01958', 'ko:K01959',
                 'ko:K01960', 'ko:K00163', 'ko:K00161', 'ko:K00162',
                 'ko:K00163', 'ko:K00161', 'ko:K00162', 'ko:K00382',
                 'ko:K00627', 'ko:K00169', 'ko:K00170', 'ko:K00172',
                 'ko:K00171', 'ko:K01643', 'ko:K01644', 'ko:K01646',
                 'ko:K01610', 'ko:K01596'])

    def test_render_KGML_basic(self):
        """Basic rendering of KGML: write to PDF without modification."""
        # We test rendering of the original KEGG KGML using only local
        # files.
        for p in self.data:
            with open(p.infilename, 'rU') as f:
                pathway = read(f)
                pathway.image = p.pathway_image
                kgml_map = KGMLCanvas(pathway)
                kgml_map.import_imagemap = p.show_pathway_image
                kgml_map.draw(p.output_stem + '_original.pdf')

    def test_render_KGML_modify(self):
        """Rendering of KGML to PDF, with modification."""
        # We test rendering of the original KGML for KO01100,
        # modifying line width for the lipid pathway
        p = self.data
        with open(p[0].infilename) as f:
            pathway = read(f)
            mod_rs = [e for e in pathway.orthologs if
                      len(set(e.name.split()).intersection(self.ko_ids))]
            for r in mod_rs:
                for g in r.graphics:
                    g.width = 10
            kgml_map = KGMLCanvas(pathway)
            kgml_map.draw(p[0].output_stem + '_widths.pdf')
        # We test rendering of the original KGML for KO3070,
        # modifying the reaction colours for each ortholog entry
        with open(p[1].infilename) as f:
            pathway = read(f)
            orthologs = [e for e in pathway.orthologs]
            # Use Biopython's ColorSpiral to generate colours
            cs = ColorSpiral(a=2, b=0.2, v_init=0.85, v_final=0.5,
                             jitter=0.03)
            colors = cs.get_colors(len(orthologs))
            for o, c in zip(orthologs, colors):
                for g in o.graphics:
                    g.bgcolor = c
            kgml_map = KGMLCanvas(pathway)
            pathway.image = p[1].pathway_image
            kgml_map.import_imagemap = p[1].show_pathway_image
            kgml_map.draw(p[1].output_stem + '_colors.pdf')

    def test_render_KGML_transparency(self):
        """Rendering of KGML to PDF, with color alpha channel."""
        # We test rendering of the original KGML for KO01100,
        # modifying alpha channel for the lipid pathway
        p = self.data
        with open(p[0].infilename) as f:
            pathway = read(f)
            mod_rs = [e for e in pathway.orthologs if
                      len(set(e.name.split()).intersection(self.ko_ids))]
            for r in mod_rs:
                for g in r.graphics:
                    # Modify hex colour directly by appending alpha channel
                    # to hex string
                    g.fgcolor = g.fgcolor + "77"
                    g.width = 20
            kgml_map = KGMLCanvas(pathway)
            kgml_map.draw(p[0].output_stem + '_transparency.pdf')
        # We test rendering of the original KGML for KO3070,
        # modifying the alpha channel for each ortholog entry
        with open(p[1].infilename) as f:
            pathway = read(f)
            orthologs = [e for e in pathway.orthologs]
            # Use Biopython's ColorSpiral to generate colours
            cs = ColorSpiral(a=2, b=0.2, v_init=0.85, v_final=0.5,
                             jitter=0.03)
            colors = cs.get_colors(len(orthologs))
            for o, c in zip(orthologs, colors):
                # Modify color tuples to add alpha channel
                c = c + (0.5, )
                for g in o.graphics:
                    g.bgcolor = c
            kgml_map = KGMLCanvas(pathway)
            pathway.image = p[1].pathway_image
            kgml_map.import_imagemap = p[1].show_pathway_image
            kgml_map.draw(p[1].output_stem + '_transparency.pdf')


if __name__ == '__main__':
    runner = unittest.TextTestRunner(verbosity=2)
    unittest.main(testRunner=runner)