graphlay 0.2.1__cp39-abi3-win_amd64.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
graphlay/__init__.py ADDED
@@ -0,0 +1,325 @@
1
+ """Deterministic graph layout.
2
+
3
+ The engine is graphlay, a layered (Sugiyama-style) layout engine in Rust with orthogonal or
4
+ diagonal edge routing, a tidy-tree layout, quality metrics and an SVG renderer. A graph goes
5
+ in as a dict, a JSON string, a `Graph` built here, or a networkx graph, and a `Layout` comes
6
+ back with a position per node and a polyline per edge. In a notebook, a `Layout` displays
7
+ itself as a drawing.
8
+ """
9
+
10
+ from __future__ import annotations
11
+
12
+ import json
13
+ from typing import Any, Dict, List, Mapping, Optional, Sequence, Tuple, Union
14
+
15
+ from . import _native
16
+ from ._native import GraphlayError
17
+
18
+ __all__ = [
19
+ "Graph",
20
+ "GraphlayError",
21
+ "Layout",
22
+ "Svg",
23
+ "fingerprint",
24
+ "layout",
25
+ "layout_tree",
26
+ "metrics",
27
+ "options",
28
+ "presets",
29
+ "render_scene",
30
+ "reroute",
31
+ "sketch",
32
+ ]
33
+
34
+ __version__ = _native.version()
35
+
36
+ GraphLike = Union[Mapping[str, Any], str, "Graph", Any]
37
+ """A graph the functions here accept: a dict with `nodes` and `edges` as the engine's JSON
38
+ request spells them, that JSON as a string, a `Graph`, or a networkx graph."""
39
+
40
+
41
+ class Graph:
42
+ """A graph to lay out, built node by node.
43
+
44
+ Each node has a size in px and an id of your choice, and `layout().positions()` is keyed
45
+ by those ids. Edges name their ends by id or by the index `node()` returned.
46
+ """
47
+
48
+ def __init__(self) -> None:
49
+ self.nodes: List[Dict[str, Any]] = []
50
+ self.edges: List[Dict[str, Any]] = []
51
+ self.ids: List[Any] = []
52
+ self._index: Dict[Any, int] = {}
53
+
54
+ def node(
55
+ self,
56
+ id: Any = None,
57
+ *,
58
+ width: float = 120.0,
59
+ height: float = 50.0,
60
+ shape: str = "box",
61
+ label: Optional[str] = None,
62
+ **fields: Any,
63
+ ) -> int:
64
+ """Adds a node and returns its index. `fields` are further node fields of the
65
+ engine's request, such as `rank`, `group`, `parent`, `position` or `pinned`."""
66
+ index = len(self.nodes)
67
+ if id is None:
68
+ id = index
69
+ if id in self._index:
70
+ raise ValueError(f"node {id!r} was added twice")
71
+ node = {"size": {"width": float(width), "height": float(height)}, "shape": shape}
72
+ node["key"] = str(id) if label is None else label
73
+ node.update(fields)
74
+ self.nodes.append(node)
75
+ self.ids.append(id)
76
+ self._index[id] = index
77
+ return index
78
+
79
+ def edge(self, source: Any, target: Any, *, weight: float = 1.0, **fields: Any) -> int:
80
+ """Adds an edge between two node ids (or indices) and returns its index. `fields` are
81
+ further edge fields of the request, such as `thickness`, `label_size` or `group`."""
82
+ edge = {"source": self._resolve(source), "target": self._resolve(target), "weight": weight}
83
+ edge.update(fields)
84
+ self.edges.append(edge)
85
+ return len(self.edges) - 1
86
+
87
+ def _resolve(self, ref: Any) -> int:
88
+ if ref in self._index:
89
+ return self._index[ref]
90
+ if isinstance(ref, int) and 0 <= ref < len(self.nodes):
91
+ return ref
92
+ raise ValueError(f"no node {ref!r}")
93
+
94
+ def to_dict(self) -> Dict[str, Any]:
95
+ """The graph as the engine's request spells it."""
96
+ return {"nodes": self.nodes, "edges": self.edges}
97
+
98
+ @classmethod
99
+ def from_networkx(
100
+ cls,
101
+ g: Any,
102
+ *,
103
+ width: float = 120.0,
104
+ height: float = 50.0,
105
+ shape: str = "box",
106
+ ) -> "Graph":
107
+ """A `Graph` from a networkx graph. Node attributes `width`, `height`, `shape` and
108
+ `label` override the defaults, and the edge attributes `weight` and `thickness` pass
109
+ through. An undirected graph is drawn with each edge pointing the way networkx lists
110
+ it."""
111
+ out = cls()
112
+ for n, data in g.nodes(data=True):
113
+ fields = {k: v for k, v in data.items() if k in ("rank", "group", "parent", "pinned")}
114
+ out.node(
115
+ n,
116
+ width=data.get("width", width),
117
+ height=data.get("height", height),
118
+ shape=data.get("shape", shape),
119
+ label=data.get("label"),
120
+ **fields,
121
+ )
122
+ for u, v, data in g.edges(data=True):
123
+ fields = {k: v for k, v in data.items() if k in ("thickness", "label_size", "group")}
124
+ out.edge(u, v, weight=float(data.get("weight", 1.0)), **fields)
125
+ return out
126
+
127
+
128
+ class Svg(str):
129
+ """SVG markup. Displays as the drawing in a notebook."""
130
+
131
+ def _repr_svg_(self) -> str:
132
+ return str(self)
133
+
134
+ def save(self, path: str) -> None:
135
+ """Writes the markup to `path`."""
136
+ with open(path, "w", encoding="utf-8") as f:
137
+ f.write(self)
138
+
139
+
140
+ class Layout:
141
+ """Where every node went and how every edge was drawn.
142
+
143
+ `nodes[i]` and `edges[i]` follow the input order and are the engine's own dicts: a node
144
+ has `center` and `size`, an edge has `points` from source to target, border to border.
145
+ """
146
+
147
+ def __init__(self, raw: Dict[str, Any], request: str, ids: Sequence[Any]) -> None:
148
+ self.raw = raw
149
+ self._request = request
150
+ self.ids = list(ids)
151
+
152
+ @property
153
+ def nodes(self) -> List[Dict[str, Any]]:
154
+ return self.raw["nodes"]
155
+
156
+ @property
157
+ def edges(self) -> List[Dict[str, Any]]:
158
+ return self.raw["edges"]
159
+
160
+ @property
161
+ def bounds(self) -> Dict[str, Any]:
162
+ """The drawing's bounding box: `min` and `max` points."""
163
+ return self.raw["bounds"]
164
+
165
+ def positions(self, *, flip_y: bool = False) -> Dict[Any, Tuple[float, float]]:
166
+ """Node centres by node id, ready for `networkx.draw(g, pos=...)`. SVG y grows
167
+ downwards, so pass `flip_y` for a plot whose y grows upwards."""
168
+ sign = -1.0 if flip_y else 1.0
169
+ # `+ 0.0` turns the -0.0 a flipped zero would give into 0.0.
170
+ return {
171
+ id: (n["center"]["x"], sign * n["center"]["y"] + 0.0)
172
+ for id, n in zip(self.ids, self.nodes)
173
+ }
174
+
175
+ def to_dict(self) -> Dict[str, Any]:
176
+ return self.raw
177
+
178
+ def to_json(self) -> str:
179
+ return json.dumps(self.raw)
180
+
181
+ def fingerprint(self) -> str:
182
+ """A stable fingerprint of the drawing, the same in every binding."""
183
+ return _native.fingerprint(self.to_json())
184
+
185
+ def metrics(self) -> Dict[str, Any]:
186
+ """Quality metrics of the drawing: crossings, bends, node-edge hits and more."""
187
+ return json.loads(_native.metrics(self._request, self.to_json()))
188
+
189
+ def sketch(
190
+ self,
191
+ *,
192
+ labels: Optional[Sequence[str]] = None,
193
+ lane_names: Optional[Sequence[str]] = None,
194
+ background: Optional[str] = "#ffffff",
195
+ padding: float = 24.0,
196
+ ) -> Svg:
197
+ """A plain drawing: boxes with labels, edges with arrowheads, lanes behind."""
198
+ opts = _sketch_options(labels, lane_names, background, padding)
199
+ return Svg(_native.sketch(self._request, self.to_json(), opts))
200
+
201
+ def sketch_scene(
202
+ self,
203
+ *,
204
+ labels: Optional[Sequence[str]] = None,
205
+ lane_names: Optional[Sequence[str]] = None,
206
+ background: Optional[str] = "#ffffff",
207
+ padding: float = 24.0,
208
+ ) -> Dict[str, Any]:
209
+ """The plain drawing as a scene dict, to restyle and pass to `render_scene`."""
210
+ opts = _sketch_options(labels, lane_names, background, padding)
211
+ return json.loads(_native.sketch_scene(self._request, self.to_json(), opts))
212
+
213
+ def _repr_svg_(self) -> str:
214
+ return str(self.sketch())
215
+
216
+ def __repr__(self) -> str:
217
+ return f"Layout({len(self.nodes)} nodes, {len(self.edges)} edges)"
218
+
219
+
220
+ def _sketch_options(
221
+ labels: Optional[Sequence[str]],
222
+ lane_names: Optional[Sequence[str]],
223
+ background: Optional[str],
224
+ padding: float,
225
+ ) -> str:
226
+ return json.dumps(
227
+ {
228
+ "labels": list(labels or []),
229
+ "lane_names": list(lane_names or []),
230
+ "background": background,
231
+ "padding": padding,
232
+ }
233
+ )
234
+
235
+
236
+ def _graph_dict(graph: GraphLike) -> Tuple[Dict[str, Any], List[Any]]:
237
+ """The engine's graph dict and the node ids, from any accepted input."""
238
+ if isinstance(graph, Graph):
239
+ return graph.to_dict(), graph.ids
240
+ if isinstance(graph, str):
241
+ graph = json.loads(graph)
242
+ if isinstance(graph, Mapping):
243
+ if "graph" in graph and "nodes" not in graph:
244
+ graph = graph["graph"]
245
+ nodes = graph.get("nodes", [])
246
+ return dict(graph), list(range(len(nodes)))
247
+ if hasattr(graph, "nodes") and hasattr(graph, "edges") and callable(graph.edges):
248
+ built = Graph.from_networkx(graph)
249
+ return built.to_dict(), built.ids
250
+ raise TypeError(f"not a graph: {type(graph).__name__}")
251
+
252
+
253
+ def _request(graph: GraphLike, preset: Optional[str], options: Optional[Mapping[str, Any]]) -> Tuple[str, List[Any]]:
254
+ g, ids = _graph_dict(graph)
255
+ request: Dict[str, Any] = {"graph": g}
256
+ if preset is not None:
257
+ request["preset"] = preset
258
+ if options:
259
+ request["options"] = dict(options)
260
+ return json.dumps(request), ids
261
+
262
+
263
+ def layout(
264
+ graph: GraphLike,
265
+ *,
266
+ preset: str = "layered",
267
+ options: Optional[Mapping[str, Any]] = None,
268
+ ) -> Layout:
269
+ """Lays out `graph` with the layered engine.
270
+
271
+ `preset` is one of `presets()`. `options` is a patch over the preset's options, such as
272
+ `{"direction": "topbottom", "routing": {"style": "diagonal"}}`.
273
+ """
274
+ request, ids = _request(graph, preset, options)
275
+ return Layout(json.loads(_native.layout(request)), request, ids)
276
+
277
+
278
+ def reroute(
279
+ graph: GraphLike,
280
+ *,
281
+ preset: str = "layered",
282
+ options: Optional[Mapping[str, Any]] = None,
283
+ ) -> Layout:
284
+ """Re-routes the edges over the `position` each node carries, without moving a node.
285
+ For a drag, give every node its current centre and the dragged one its new centre."""
286
+ request, ids = _request(graph, preset, options)
287
+ return Layout(json.loads(_native.reroute(request)), request, ids)
288
+
289
+
290
+ def layout_tree(graph: GraphLike, *, options: Optional[Mapping[str, Any]] = None) -> Layout:
291
+ """Lays out a rooted tree or forest with the tidy-tree engine, parents centred over
292
+ their children."""
293
+ request, ids = _request(graph, None, options)
294
+ return Layout(json.loads(_native.layout_tree(request)), request, ids)
295
+
296
+
297
+ def metrics(layout: Layout) -> Dict[str, Any]:
298
+ """Quality metrics of a layout, the same as `layout.metrics()`."""
299
+ return layout.metrics()
300
+
301
+
302
+ def fingerprint(layout: Layout) -> str:
303
+ """A stable fingerprint of a layout, the same as `layout.fingerprint()`."""
304
+ return layout.fingerprint()
305
+
306
+
307
+ def sketch(layout: Layout, **kwargs: Any) -> Svg:
308
+ """A plain drawing of a layout, the same as `layout.sketch(...)`."""
309
+ return layout.sketch(**kwargs)
310
+
311
+
312
+ def presets() -> List[str]:
313
+ """The presets a layout can start from."""
314
+ return list(_native.presets())
315
+
316
+
317
+ def options(preset: str = "layered") -> Dict[str, Any]:
318
+ """The full options of a preset, to see or edit every field."""
319
+ return json.loads(_native.options(preset))
320
+
321
+
322
+ def render_scene(scene: Mapping[str, Any], palette: Optional[Mapping[str, Any]] = None) -> Svg:
323
+ """Draws a scene (the engine's `svg::Scene`, e.g., from `Layout.sketch_scene`) to SVG.
324
+ `palette` holds the fallback colours, and `None` means the default ones."""
325
+ return Svg(_native.render_scene(json.dumps(scene), json.dumps(palette) if palette else ""))
graphlay/_native.pyd ADDED
Binary file
graphlay/_native.pyi ADDED
@@ -0,0 +1,14 @@
1
+ class GraphlayError(ValueError):
2
+ """An error the engine reported: a bad request, an invalid graph or a limit exceeded."""
3
+
4
+ def version() -> str: ...
5
+ def layout(request: str) -> str: ...
6
+ def reroute(request: str) -> str: ...
7
+ def layout_tree(request: str) -> str: ...
8
+ def metrics(request: str, layout: str) -> str: ...
9
+ def fingerprint(layout: str) -> str: ...
10
+ def presets() -> list[str]: ...
11
+ def options(preset: str) -> str: ...
12
+ def render_scene(scene: str, palette: str) -> str: ...
13
+ def sketch(request: str, layout: str, options: str) -> str: ...
14
+ def sketch_scene(request: str, layout: str, options: str) -> str: ...
graphlay/py.typed ADDED
File without changes
@@ -0,0 +1,63 @@
1
+ Metadata-Version: 2.4
2
+ Name: graphlay
3
+ Version: 0.2.1
4
+ Classifier: Development Status :: 4 - Beta
5
+ Classifier: Intended Audience :: Developers
6
+ Classifier: Intended Audience :: Science/Research
7
+ Classifier: Programming Language :: Python :: 3
8
+ Classifier: Programming Language :: Rust
9
+ Classifier: Topic :: Scientific/Engineering :: Visualization
10
+ Requires-Dist: networkx>=3.0 ; extra == 'networkx'
11
+ Provides-Extra: networkx
12
+ Summary: Deterministic layered graph layout, tidy trees and SVG rendering, in Rust
13
+ Keywords: graph,layout,sugiyama,layered,svg,networkx
14
+ License-Expression: MIT OR Apache-2.0
15
+ Requires-Python: >=3.9
16
+ Description-Content-Type: text/markdown; charset=UTF-8; variant=GFM
17
+ Project-URL: Homepage, https://aarkue.github.io/graphlay/
18
+ Project-URL: Repository, https://github.com/aarkue/graphlay
19
+
20
+ # graphlay
21
+
22
+ Deterministic graph layout for Python: a layered (Sugiyama-style) engine with orthogonal or
23
+ diagonal edge routing, a tidy-tree layout, quality metrics and an SVG renderer. The engine is
24
+ [graphlay](https://github.com/aarkue/graphlay), written in Rust. The wheels are prebuilt, so there
25
+ is nothing to compile.
26
+
27
+ ```sh
28
+ pip install graphlay
29
+ ```
30
+
31
+ ```python
32
+ import graphlay
33
+
34
+ g = graphlay.Graph()
35
+ g.node("start", width=60, height=30, shape="ellipse")
36
+ g.node("work", label="Do the work")
37
+ g.node("end", width=60, height=30, shape="ellipse")
38
+ g.edge("start", "work")
39
+ g.edge("work", "end")
40
+
41
+ drawing = graphlay.layout(g, preset="process_map", options={"routing": {"style": "diagonal"}})
42
+ drawing.positions() # {"start": (x, y), ...}
43
+ drawing.edges[0]["points"] # the polyline, border to border
44
+ drawing # in a notebook: the drawing itself
45
+ drawing.sketch().save("drawing.svg")
46
+ ```
47
+
48
+ A networkx graph works directly, and `positions()` feeds `networkx.draw`:
49
+
50
+ ```python
51
+ import networkx as nx
52
+
53
+ g = nx.DiGraph([("a", "b"), ("b", "c"), ("a", "c")])
54
+ pos = graphlay.layout(g).positions(flip_y=True)
55
+ nx.draw(g, pos)
56
+ ```
57
+
58
+ `drawing.sketch_scene()` returns the same drawing as a scene dict. Change colours or labels in
59
+ it and draw it with `graphlay.render_scene(scene)`.
60
+
61
+ The [guide](https://aarkue.github.io/graphlay/docs/guide) explains the options and the
62
+ [gallery](https://aarkue.github.io/graphlay/docs/gallery) shows what they do.
63
+
@@ -0,0 +1,8 @@
1
+ graphlay/__init__.py,sha256=KMiqdQ00Yyu-6okRzrii-E4UWr2rJIauifatHrhFfMw,11768
2
+ graphlay/_native.pyd,sha256=RISELSoHXxkKhMQj59UBRJCMP_jdQtt6DeaT5YFzsmc,3426304
3
+ graphlay/_native.pyi,sha256=dUSNpZVztium54t3M5b0u48ZGiYgGJDU6mFVT5ObK0E,634
4
+ graphlay/py.typed,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
5
+ graphlay-0.2.1.dist-info/METADATA,sha256=bNsL8NHRVwtfyqDDGwloXQd31oYezc9rcKNW1T97UHk,2287
6
+ graphlay-0.2.1.dist-info/WHEEL,sha256=xe4_tbg8wYdeh4O7nLbnWckzIQtCR4nODDgwke_TKy8,95
7
+ graphlay-0.2.1.dist-info/sboms/graphlay-py.cyclonedx.json,sha256=k-MzIJFxxZrCdjgPPX6ZpzLiZFseDUPNr-cApqf40fk,36595
8
+ graphlay-0.2.1.dist-info/RECORD,,
@@ -0,0 +1,4 @@
1
+ Wheel-Version: 1.0
2
+ Generator: maturin (1.15.0)
3
+ Root-Is-Purelib: false
4
+ Tag: cp39-abi3-win_amd64