Coverage for src/python/ensembl/vep/render/graph/svg.py: 100%
71 statements
« prev ^ index » next coverage.py v7.17.2, created at 2026-11-18 14:41 +0000
« prev ^ index » next coverage.py v7.17.2, created at 2026-11-18 14:41 +0000
1# See the NOTICE file distributed with this work for additional information
2# regarding copyright ownership.
3#
4# Licensed under the Apache License, Version 2.0 (the "License");
5# you may not use this file except in compliance with the License.
6# You may obtain a copy of the License at
7# http://www.apache.org/licenses/LICENSE-2.0
8#
9# Unless required by applicable law or agreed to in writing, software
10# distributed under the License is distributed on an "AS IS" BASIS,
11# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12# See the License for the specific language governing permissions and
13# limitations under the License.
14"""Rendering a laid-out graph as inline SVG.
16The one place node semantics become an appearance: a builder says a node was forced false, this
17module decides that means a dashed grey box.
18"""
20from __future__ import annotations
22import re
23from collections.abc import Mapping
24from xml.sax.saxutils import escape, quoteattr
26from ensembl.vep.render.graph.layout import Layout, layered
27from ensembl.vep.render.graph.model import Graph
28from ensembl.vep.render.theme import Colour, Font
30__all__ = ["STATE_COLOURS", "render_svg"]
32STATE_COLOURS = {
33 "operator": Colour.LIGHT_GREY,
34 "term": Colour.LIGHT_BLUE,
35 "subsumed": Colour.DUCKEGG_BLUE,
36 "suppressor": Colour.DARK_PINK,
37 "computed": Colour.ICE_BLUE,
38 "prefilled": Colour.DUCKEGG_BLUE,
39 "cached": Colour.NEON_BLUE,
40 "forced_false": Colour.LIGHT_GREY,
41 "fired": Colour.LIGHT_BLUE,
42 "pruned": Colour.MEDIUM_LIGHT_GREY,
43 "emitted": Colour.BLUE,
44 "true": Colour.LIGHT_BLUE,
45 "false": Colour.RED,
46 "unreached": Colour.WHITE,
47 "impact_high": Colour.DARK_PINK,
48 "impact_moderate": Colour.ORANGE,
49 "impact_low": Colour.DUCKEGG_BLUE,
50 "impact_modifier": Colour.LIGHT_GREY,
51}
52"""Node state -> fill colour. A state absent from here falls back to the neutral fill.
54The one place a builder's semantics become an appearance: ``subsumed`` and ``suppressor`` are the
55two directions of suppression, and they are coloured apart so which way it runs is readable without
56following the arrowheads.
57"""
59DEFAULT_FILL = Colour.WHITE
60DEFAULT_TEXT = Colour.BLACK
61STATE_TEXT_COLOURS = {"false": Colour.WHITE}
62STROKE = Colour.DARK_GREY
63EDGE_COLOUR = Colour.GREY
64LABEL_SIZE = 11
65DETAIL_SIZE = 9
66_UNSAFE_IDENTIFIER = re.compile(r"[^0-9A-Za-z_-]")
69def _fill_for(state: str) -> Colour:
70 """Return the fill a node state is drawn with."""
71 return STATE_COLOURS.get(state, DEFAULT_FILL)
74def _dashed(state: str) -> bool:
75 """Return whether a node state is drawn with a dashed outline."""
76 return state in {"forced_false", "unreached"}
79def _text_for(state: str) -> Colour:
80 """Return a readable text colour for a node state."""
81 return STATE_TEXT_COLOURS.get(state, DEFAULT_TEXT)
84def _node_svg(layout: Layout, links: Mapping[str, str]) -> list[str]:
85 """Return one SVG group per placed node."""
86 parts = []
87 for placement in layout.placements:
88 node = placement.node
89 text_colour = _text_for(node.state)
90 dash = ' stroke-dasharray="4 3"' if _dashed(node.state) else ""
91 radius = placement.height // 2 if node.kind == "operator" else 0
92 stroke_width = 2 if node.kind == "rule" else 1
93 node_parts = [
94 f'<rect x="{placement.x}" y="{placement.y}" width="{placement.width}" '
95 f'height="{placement.height}" fill="{_fill_for(node.state).value}" '
96 f'stroke="{STROKE.value}" stroke-width="{stroke_width}" rx="{radius}"{dash}/>'
97 ]
98 text_x = placement.x + 8
99 node_parts.append(
100 f'<text x="{text_x}" y="{placement.y + 15}" font-size="{LABEL_SIZE}" '
101 f'fill="{text_colour.value}">{escape(node.label)}</text>'
102 )
103 if node.detail:
104 node_parts.append(
105 f'<text x="{text_x}" y="{placement.y + 27}" font-size="{DETAIL_SIZE}" '
106 f'fill="{text_colour.value}">{escape(node.detail)}</text>'
107 )
108 body = "".join(node_parts)
109 if node.identifier in links:
110 parts.append(f"<a href={quoteattr(links[node.identifier])}>{body}</a>")
111 else:
112 parts.append(body)
113 return parts
116def _edge_svg(layout: Layout, marker_identifier: str) -> list[str]:
117 """Return one SVG path per edge whose endpoints were both placed."""
118 parts = []
119 for edge in layout.graph.edges:
120 try:
121 source = layout.placement(edge.source)
122 target = layout.placement(edge.target)
123 except KeyError:
124 continue
125 start_x = source.right
126 start_y = source.centre_y
127 end_x = target.x
128 end_y = target.centre_y
129 control = (start_x + end_x) // 2
130 parts.append(
131 f'<path d="M {start_x} {start_y} C {control} {start_y}, {control} {end_y}, '
132 f'{end_x} {end_y}" fill="none" stroke="{EDGE_COLOUR.value}" stroke-width="1" '
133 f'marker-end="url(#{marker_identifier})"/>'
134 )
135 if edge.label:
136 label_x = (start_x + end_x) // 2
137 label_y = (start_y + end_y) // 2 - 4
138 parts.append(
139 f'<text x="{label_x}" y="{label_y}" text-anchor="middle" '
140 f'font-size="{DETAIL_SIZE}" fill="{Colour.DARK_GREY.value}">{escape(edge.label)}</text>'
141 )
142 return parts
145def _marker_identifier(title: str) -> str:
146 """Return an SVG identifier unique to a titled graph on an HTML page."""
147 suffix = _UNSAFE_IDENTIFIER.sub("-", title).strip("-") or "graph"
148 return f"arrow-{suffix}"
151def render_svg(
152 graph: Graph,
153 layout: Layout | None = None,
154 *,
155 links: Mapping[str, str] | None = None,
156) -> str:
157 """Return a graph as a standalone ``<svg>`` element.
159 Args:
160 graph (Graph): The graph to draw.
161 layout (Layout | None): A layout to use, or None to lay the graph out in columns.
162 links (Mapping[str, str] | None): Optional node identifiers to link destinations.
164 Returns:
165 str: The SVG markup, self-contained apart from the font stack it names.
166 """
167 placed = layout or layered(graph)
168 marker_identifier = _marker_identifier(graph.title)
169 marker = (
170 f'<defs><marker id="{marker_identifier}" viewBox="0 0 8 8" refX="7" refY="4" markerWidth="6" '
171 f'markerHeight="6" orient="auto"><path d="M 0 0 L 8 4 L 0 8 z" '
172 f'fill="{EDGE_COLOUR.value}"/></marker></defs>'
173 )
174 body = "\n ".join(_edge_svg(placed, marker_identifier) + _node_svg(placed, links or {}))
175 title = f"<title>{escape(graph.title)}</title>" if graph.title else ""
176 return (
177 f'<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 {placed.width} {placed.height}" '
178 f'width="{placed.width}" height="{placed.height}" '
179 f'font-family="{Font.BODY.value}">{title}\n {marker}\n {body}\n</svg>'
180 )