Coverage for src/python/ensembl/vep/render/graph/dot.py: 100%
31 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 graph as Graphviz DOT."""
16from __future__ import annotations
18from ensembl.vep.render.graph.model import Graph
20__all__ = ["render_dot"]
23def _quote(text: str) -> str:
24 """Return text escaped for a DOT double-quoted string."""
25 return text.replace("\\", "\\\\").replace('"', '\\"')
28def render_dot(graph: Graph) -> str:
29 """Return a graph as a DOT digraph.
31 Node semantics are emitted as attributes rather than as an appearance, so a caller styling the
32 output with their own Graphviz theme has everything the builder knew.
33 """
34 lines = [f'digraph "{_quote(graph.title)}" {{', " rankdir=LR;", " node [shape=box];"]
36 for layer in graph.layers():
37 members = []
38 for node in graph.nodes_in_layer(layer):
39 members.append(f'"{_quote(node.identifier)}"')
40 lines.append(f" {{ rank=same; {' '.join(members)} }}")
42 for node in graph.nodes:
43 attributes = [f'label="{_quote(node.label)}"']
44 if node.kind:
45 attributes.append(f'kind="{_quote(node.kind)}"')
46 if node.state:
47 attributes.append(f'state="{_quote(node.state)}"')
48 if node.hits:
49 attributes.append(f'hits="{node.hits}"')
50 lines.append(f' "{_quote(node.identifier)}" [{", ".join(attributes)}];')
52 for edge in graph.edges:
53 attributes = []
54 if edge.label:
55 attributes.append(f'label="{_quote(edge.label)}"')
56 if edge.kind:
57 attributes.append(f'kind="{_quote(edge.kind)}"')
58 suffix = f' [{", ".join(attributes)}]' if attributes else ""
59 lines.append(f' "{_quote(edge.source)}" -> "{_quote(edge.target)}"{suffix};')
61 lines.append("}")
62 return "\n".join(lines)