Coverage for src/python/ensembl/vep/render/graph/layout.py: 92%
113 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"""Placing a layered graph on a canvas.
16These graphs are small -- tens of facts and rules -- and already carry the layer each node belongs
17to, so laying them out is arithmetic rather than a general graph-drawing problem. Layers become
18columns, and a node's position within its column follows declaration order.
19"""
21from __future__ import annotations
23from attrs import define, field
25from ensembl.vep.render.graph.model import Graph, Node
27__all__ = ["Layout", "Placement", "layered", "tree"]
29LAYER_GAP = 220
30"""Horizontal distance between the left edges of two adjacent layers, in pixels."""
31NODE_GAP = 18
32"""Vertical distance between two nodes in the same layer, in pixels."""
33NODE_WIDTH = 170
34NODE_HEIGHT = 34
35OPERATOR_WIDTH = 64
36RULE_WIDTH = 220
37MARGIN = 24
38"""Space left around the drawing, in pixels."""
41@define(frozen=True, kw_only=True, auto_attribs=True)
42class Placement:
43 """Where one node sits on the canvas.
45 Attributes:
46 node (Node): The node placed.
47 x (int): Left edge, in pixels.
48 y (int): Top edge, in pixels.
49 width (int): Box width, in pixels.
50 height (int): Box height, in pixels.
51 """
53 node: Node
54 x: int
55 y: int
56 width: int = field(default=NODE_WIDTH)
57 height: int = field(default=NODE_HEIGHT)
59 @property
60 def centre_y(self) -> int:
61 """Return the vertical midpoint, where an edge attaches."""
62 return self.y + self.height // 2
64 @property
65 def right(self) -> int:
66 """Return the right edge, where an outgoing edge leaves."""
67 return self.x + self.width
70@define(frozen=True, kw_only=True, auto_attribs=True)
71class Layout:
72 """A graph with a position for every node.
74 Attributes:
75 graph (Graph): The graph laid out.
76 placements (tuple[Placement, ...]): One entry per node, in the graph's own order.
77 width (int): Canvas width, in pixels.
78 height (int): Canvas height, in pixels.
79 """
81 graph: Graph
82 placements: tuple[Placement, ...]
83 width: int
84 height: int
86 def placement(self, identifier: str) -> Placement:
87 """Return the placement of one node.
89 Raises:
90 KeyError: If no node has that identifier.
91 """
92 for placement in self.placements:
93 if placement.node.identifier == identifier:
94 return placement
95 raise KeyError(f"Unknown node '{identifier}'")
98def _node_width(node: Node) -> int:
99 """Return the width assigned to a node kind."""
100 if node.kind == "operator":
101 return OPERATOR_WIDTH
102 if node.kind == "rule":
103 return RULE_WIDTH
104 return NODE_WIDTH
107def _column_x(column: int, width: int) -> int:
108 """Return a node's left edge, centred in its layer column."""
109 return MARGIN + column * LAYER_GAP + (NODE_WIDTH - width) // 2
112def _canvas_width(placements: list[Placement]) -> int:
113 """Return the width covering every placed node."""
114 if not placements:
115 return MARGIN * 2 + NODE_WIDTH
116 return max(placement.right for placement in placements) + MARGIN
119def layered(graph: Graph) -> Layout:
120 """Lay a graph out in columns, one per layer.
122 Layers are taken from the nodes themselves rather than inferred, because the domain already
123 knows the answer: a fact's layer is its cost tier, a rule's is its rank.
124 """
125 layers = graph.layers()
126 placements: list[Placement] = []
127 tallest_column = 0
129 for column, layer in enumerate(layers):
130 nodes = graph.nodes_in_layer(layer)
131 for row, node in enumerate(nodes):
132 width = _node_width(node)
133 x = _column_x(column, width)
134 y = MARGIN + row * (NODE_HEIGHT + NODE_GAP)
135 placements.append(Placement(node=node, x=x, y=y, width=width))
136 column_height = len(nodes) * (NODE_HEIGHT + NODE_GAP) - NODE_GAP
137 tallest_column = max(tallest_column, column_height)
139 width = _canvas_width(placements)
140 height = MARGIN * 2 + max(tallest_column, NODE_HEIGHT)
141 return Layout(graph=graph, placements=tuple(placements), width=width, height=height)
144def tree(graph: Graph) -> Layout:
145 """Lay a child-to-parent tree out with every parent centred on its children.
147 Edges must point from an operand towards its parent. The one node with no outgoing edge is the
148 root. Leaves keep graph declaration order, making the result stable while preserving sibling
149 order from the source expression.
151 Raises:
152 ValueError: If the graph is disconnected, cyclic, or gives a node more than one parent.
153 """
154 if not graph.nodes: 154 ↛ 155line 154 didn't jump to line 155 because the condition on line 154 was never true
155 return layered(graph)
157 identifiers = {node.identifier for node in graph.nodes}
158 children: dict[str, list[str]] = {identifier: [] for identifier in identifiers}
159 parents: dict[str, str] = {}
160 for edge in graph.edges:
161 if edge.source not in identifiers or edge.target not in identifiers: 161 ↛ 162line 161 didn't jump to line 162 because the condition on line 161 was never true
162 continue
163 if edge.source in parents: 163 ↛ 164line 163 didn't jump to line 164 because the condition on line 163 was never true
164 raise ValueError(f"Node '{edge.source}' has more than one parent")
165 parents[edge.source] = edge.target
166 children[edge.target].append(edge.source)
168 roots = [node.identifier for node in graph.nodes if node.identifier not in parents]
169 if len(roots) != 1:
170 raise ValueError("A tree must have exactly one root")
172 centres: dict[str, int] = {}
173 visiting: set[str] = set()
174 next_leaf_centre = MARGIN + NODE_HEIGHT // 2
176 def place_centre(identifier: str) -> int:
177 nonlocal next_leaf_centre
178 if identifier in centres: 178 ↛ 179line 178 didn't jump to line 179 because the condition on line 178 was never true
179 return centres[identifier]
180 if identifier in visiting: 180 ↛ 181line 180 didn't jump to line 181 because the condition on line 180 was never true
181 raise ValueError("A tree cannot contain a cycle")
182 visiting.add(identifier)
184 child_identifiers = children[identifier]
185 if child_identifiers:
186 child_centres = [place_centre(child) for child in child_identifiers]
187 centre = (child_centres[0] + child_centres[-1]) // 2
188 else:
189 centre = next_leaf_centre
190 next_leaf_centre += NODE_HEIGHT + NODE_GAP
192 visiting.remove(identifier)
193 centres[identifier] = centre
194 return centre
196 place_centre(roots[0])
197 if len(centres) != len(graph.nodes): 197 ↛ 198line 197 didn't jump to line 198 because the condition on line 197 was never true
198 raise ValueError("A tree must be connected")
200 columns = {layer: column for column, layer in enumerate(graph.layers())}
201 placements: list[Placement] = []
202 for node in graph.nodes:
203 width = _node_width(node)
204 x = _column_x(columns[node.layer], width)
205 y = centres[node.identifier] - NODE_HEIGHT // 2
206 placements.append(Placement(node=node, x=x, y=y, width=width))
208 width = _canvas_width(placements)
209 height = max(placement.y + placement.height for placement in placements) + MARGIN
210 return Layout(graph=graph, placements=tuple(placements), width=width, height=height)