pygraphds 0.1.0__py3-none-any.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.
pygraphds/__init__.py
ADDED
pygraphds/graph.py
ADDED
|
@@ -0,0 +1,482 @@
|
|
|
1
|
+
"""A small, beginner-friendly undirected graph implementation."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
from collections import deque
|
|
6
|
+
from copy import deepcopy
|
|
7
|
+
import math
|
|
8
|
+
from typing import Optional
|
|
9
|
+
|
|
10
|
+
|
|
11
|
+
class Graph:
|
|
12
|
+
"""Store an undirected graph with string-named nodes.
|
|
13
|
+
|
|
14
|
+
A graph can contain any number of connected components. Self-loops and
|
|
15
|
+
duplicate edges are not allowed. Nodes and edges keep the order in which
|
|
16
|
+
they were added.
|
|
17
|
+
|
|
18
|
+
Node and edge data are stored as supplied. The getters return those same
|
|
19
|
+
data objects; :meth:`copy` makes a deep, independent copy of the graph.
|
|
20
|
+
|
|
21
|
+
Examples
|
|
22
|
+
--------
|
|
23
|
+
>>> graph = Graph()
|
|
24
|
+
>>> graph.add_node("A")
|
|
25
|
+
>>> graph.add_node("B")
|
|
26
|
+
>>> graph.add_edge("A", "B")
|
|
27
|
+
>>> graph.get_neighbors("A")
|
|
28
|
+
['B']
|
|
29
|
+
"""
|
|
30
|
+
|
|
31
|
+
def __init__(self) -> None:
|
|
32
|
+
self._node_data: dict[str, object] = {}
|
|
33
|
+
self._adjacency: dict[str, list[str]] = {}
|
|
34
|
+
self._edges: list[list[str]] = []
|
|
35
|
+
self._edge_data: list[object] = []
|
|
36
|
+
|
|
37
|
+
@staticmethod
|
|
38
|
+
def _validate_name(name: str) -> None:
|
|
39
|
+
if not isinstance(name, str):
|
|
40
|
+
raise TypeError("Node names must be strings.")
|
|
41
|
+
if not name.strip():
|
|
42
|
+
raise ValueError("Node names cannot be empty or whitespace only.")
|
|
43
|
+
|
|
44
|
+
def _require_node(self, name: str) -> None:
|
|
45
|
+
self._validate_name(name)
|
|
46
|
+
if name not in self._node_data:
|
|
47
|
+
raise KeyError(f"Node {name!r} does not exist.")
|
|
48
|
+
|
|
49
|
+
def _find_edge_index(self, nodeA: str, nodeB: str) -> Optional[int]:
|
|
50
|
+
for index, edge in enumerate(self._edges):
|
|
51
|
+
if (edge[0] == nodeA and edge[1] == nodeB) or (
|
|
52
|
+
edge[0] == nodeB and edge[1] == nodeA
|
|
53
|
+
):
|
|
54
|
+
return index
|
|
55
|
+
return None
|
|
56
|
+
|
|
57
|
+
def add_node(self, name: str, data: object = None) -> None:
|
|
58
|
+
"""Add a node and optional data.
|
|
59
|
+
|
|
60
|
+
Raises ``ValueError`` if the name is empty or already in the graph.
|
|
61
|
+
"""
|
|
62
|
+
self._validate_name(name)
|
|
63
|
+
if name in self._node_data:
|
|
64
|
+
raise ValueError(f"Node {name!r} already exists.")
|
|
65
|
+
self._node_data[name] = data
|
|
66
|
+
self._adjacency[name] = []
|
|
67
|
+
|
|
68
|
+
def delete_node(self, name: str) -> None:
|
|
69
|
+
"""Delete a node and every edge connected to it.
|
|
70
|
+
|
|
71
|
+
Raises ``KeyError`` if the node does not exist.
|
|
72
|
+
"""
|
|
73
|
+
self._require_node(name)
|
|
74
|
+
for neighbor in self._adjacency[name].copy():
|
|
75
|
+
self.delete_edge(name, neighbor)
|
|
76
|
+
del self._node_data[name]
|
|
77
|
+
del self._adjacency[name]
|
|
78
|
+
|
|
79
|
+
def rename_node(self, old_name: str, new_name: str) -> None:
|
|
80
|
+
"""Rename a node without changing its data or edge order.
|
|
81
|
+
|
|
82
|
+
Raises ``KeyError`` if ``old_name`` is missing and ``ValueError`` if
|
|
83
|
+
``new_name`` is empty or already belongs to another node.
|
|
84
|
+
"""
|
|
85
|
+
self._require_node(old_name)
|
|
86
|
+
self._validate_name(new_name)
|
|
87
|
+
if old_name == new_name:
|
|
88
|
+
return
|
|
89
|
+
if new_name in self._node_data:
|
|
90
|
+
raise ValueError(f"Node {new_name!r} already exists.")
|
|
91
|
+
|
|
92
|
+
self._node_data = {
|
|
93
|
+
new_name if name == old_name else name: data
|
|
94
|
+
for name, data in self._node_data.items()
|
|
95
|
+
}
|
|
96
|
+
self._adjacency = {
|
|
97
|
+
new_name if name == old_name else name: [
|
|
98
|
+
new_name if neighbor == old_name else neighbor
|
|
99
|
+
for neighbor in neighbors
|
|
100
|
+
]
|
|
101
|
+
for name, neighbors in self._adjacency.items()
|
|
102
|
+
}
|
|
103
|
+
self._edges = [
|
|
104
|
+
[new_name if endpoint == old_name else endpoint for endpoint in edge]
|
|
105
|
+
for edge in self._edges
|
|
106
|
+
]
|
|
107
|
+
|
|
108
|
+
def add_edge(self, nodeA: str, nodeB: str, data: object = None) -> None:
|
|
109
|
+
"""Connect two existing nodes and store optional edge data.
|
|
110
|
+
|
|
111
|
+
Edges are undirected. Raises ``KeyError`` if either node is missing,
|
|
112
|
+
and ``ValueError`` for a self-loop or an edge that already exists.
|
|
113
|
+
"""
|
|
114
|
+
self._require_node(nodeA)
|
|
115
|
+
self._require_node(nodeB)
|
|
116
|
+
if nodeA == nodeB:
|
|
117
|
+
raise ValueError("Self-loops are not supported.")
|
|
118
|
+
if nodeB in self._adjacency[nodeA]:
|
|
119
|
+
raise ValueError(f"Edge {nodeA!r} -- {nodeB!r} already exists.")
|
|
120
|
+
|
|
121
|
+
self._edges.append([nodeA, nodeB])
|
|
122
|
+
self._edge_data.append(data)
|
|
123
|
+
self._adjacency[nodeA].append(nodeB)
|
|
124
|
+
self._adjacency[nodeB].append(nodeA)
|
|
125
|
+
|
|
126
|
+
def delete_edge(self, nodeA: str, nodeB: str) -> None:
|
|
127
|
+
"""Remove an edge between two nodes, regardless of argument order.
|
|
128
|
+
|
|
129
|
+
Raises ``KeyError`` if either node or the edge does not exist.
|
|
130
|
+
"""
|
|
131
|
+
self._require_node(nodeA)
|
|
132
|
+
self._require_node(nodeB)
|
|
133
|
+
edge_index = self._find_edge_index(nodeA, nodeB)
|
|
134
|
+
if edge_index is None:
|
|
135
|
+
raise KeyError(f"Edge {nodeA!r} -- {nodeB!r} does not exist.")
|
|
136
|
+
|
|
137
|
+
edge = self._edges.pop(edge_index)
|
|
138
|
+
self._edge_data.pop(edge_index)
|
|
139
|
+
self._adjacency[edge[0]].remove(edge[1])
|
|
140
|
+
self._adjacency[edge[1]].remove(edge[0])
|
|
141
|
+
|
|
142
|
+
def get_node_data(self, name: str) -> object:
|
|
143
|
+
"""Return a node's data. Raises ``KeyError`` if the node is missing."""
|
|
144
|
+
self._require_node(name)
|
|
145
|
+
return self._node_data[name]
|
|
146
|
+
|
|
147
|
+
def set_node_data(self, name: str, data: object) -> None:
|
|
148
|
+
"""Replace a node's data. Raises ``KeyError`` if the node is missing."""
|
|
149
|
+
self._require_node(name)
|
|
150
|
+
self._node_data[name] = data
|
|
151
|
+
|
|
152
|
+
def get_edge_data(self, nodeA: str, nodeB: str) -> object:
|
|
153
|
+
"""Return edge data, accepting either endpoint order.
|
|
154
|
+
|
|
155
|
+
Raises ``KeyError`` if either node or the edge is missing.
|
|
156
|
+
"""
|
|
157
|
+
self._require_node(nodeA)
|
|
158
|
+
self._require_node(nodeB)
|
|
159
|
+
edge_index = self._find_edge_index(nodeA, nodeB)
|
|
160
|
+
if edge_index is None:
|
|
161
|
+
raise KeyError(f"Edge {nodeA!r} -- {nodeB!r} does not exist.")
|
|
162
|
+
return self._edge_data[edge_index]
|
|
163
|
+
|
|
164
|
+
def set_edge_data(self, nodeA: str, nodeB: str, data: object) -> None:
|
|
165
|
+
"""Replace edge data, accepting either endpoint order.
|
|
166
|
+
|
|
167
|
+
Raises ``KeyError`` if either node or the edge is missing.
|
|
168
|
+
"""
|
|
169
|
+
self._require_node(nodeA)
|
|
170
|
+
self._require_node(nodeB)
|
|
171
|
+
edge_index = self._find_edge_index(nodeA, nodeB)
|
|
172
|
+
if edge_index is None:
|
|
173
|
+
raise KeyError(f"Edge {nodeA!r} -- {nodeB!r} does not exist.")
|
|
174
|
+
self._edge_data[edge_index] = data
|
|
175
|
+
|
|
176
|
+
def contains_node(self, name: str) -> bool:
|
|
177
|
+
"""Return whether a node with this name exists."""
|
|
178
|
+
self._validate_name(name)
|
|
179
|
+
return name in self._node_data
|
|
180
|
+
|
|
181
|
+
def contains_edge(self, nodeA: str, nodeB: str) -> bool:
|
|
182
|
+
"""Return whether an edge exists; endpoint order does not matter."""
|
|
183
|
+
self._validate_name(nodeA)
|
|
184
|
+
self._validate_name(nodeB)
|
|
185
|
+
if nodeA not in self._adjacency or nodeB not in self._adjacency:
|
|
186
|
+
return False
|
|
187
|
+
return nodeB in self._adjacency[nodeA]
|
|
188
|
+
|
|
189
|
+
def get_nodes_count(self) -> int:
|
|
190
|
+
"""Return the number of nodes."""
|
|
191
|
+
return len(self._node_data)
|
|
192
|
+
|
|
193
|
+
def get_edges_count(self) -> int:
|
|
194
|
+
"""Return the number of undirected edges."""
|
|
195
|
+
return len(self._edges)
|
|
196
|
+
|
|
197
|
+
def get_degree(self, node: str) -> int:
|
|
198
|
+
"""Return how many edges touch ``node``.
|
|
199
|
+
|
|
200
|
+
Raises ``KeyError`` if the node does not exist.
|
|
201
|
+
"""
|
|
202
|
+
self._require_node(node)
|
|
203
|
+
return len(self._adjacency[node])
|
|
204
|
+
|
|
205
|
+
def get_nodes(self) -> list[str]:
|
|
206
|
+
"""Return node names in the order they were added."""
|
|
207
|
+
return list(self._node_data)
|
|
208
|
+
|
|
209
|
+
def get_edges(self, node: Optional[str] = None) -> list[list[str]]:
|
|
210
|
+
"""Return edge endpoint pairs as lists.
|
|
211
|
+
|
|
212
|
+
With no argument, return every edge in insertion order. If ``node`` is
|
|
213
|
+
supplied, return only its incident edges. Each pair keeps the endpoint
|
|
214
|
+
order used when that edge was added. Returned lists are independent.
|
|
215
|
+
"""
|
|
216
|
+
if node is not None:
|
|
217
|
+
self._require_node(node)
|
|
218
|
+
return [edge.copy() for edge in self._edges if node in edge]
|
|
219
|
+
return [edge.copy() for edge in self._edges]
|
|
220
|
+
|
|
221
|
+
def get_neighbors(self, node: str) -> list[str]:
|
|
222
|
+
"""Return the nodes directly connected to ``node``.
|
|
223
|
+
|
|
224
|
+
Neighbors are only one edge away, in the order their edges were added.
|
|
225
|
+
Raises ``KeyError`` if the node does not exist.
|
|
226
|
+
"""
|
|
227
|
+
self._require_node(node)
|
|
228
|
+
return self._adjacency[node].copy()
|
|
229
|
+
|
|
230
|
+
def get_path(self, nodeA: str, nodeB: str) -> Optional[list[str]]:
|
|
231
|
+
"""Return a shortest path, or ``None`` if no path exists.
|
|
232
|
+
|
|
233
|
+
The path includes both endpoints. If the endpoints are the same, the
|
|
234
|
+
result is a one-node list. Raises ``KeyError`` if an endpoint is absent.
|
|
235
|
+
"""
|
|
236
|
+
self._require_node(nodeA)
|
|
237
|
+
self._require_node(nodeB)
|
|
238
|
+
if nodeA == nodeB:
|
|
239
|
+
return [nodeA]
|
|
240
|
+
|
|
241
|
+
parents: dict[str, Optional[str]] = {nodeA: None}
|
|
242
|
+
queue = deque([nodeA])
|
|
243
|
+
while queue:
|
|
244
|
+
current = queue.popleft()
|
|
245
|
+
for neighbor in self._adjacency[current]:
|
|
246
|
+
if neighbor in parents:
|
|
247
|
+
continue
|
|
248
|
+
parents[neighbor] = current
|
|
249
|
+
if neighbor == nodeB:
|
|
250
|
+
path = []
|
|
251
|
+
step: Optional[str] = nodeB
|
|
252
|
+
while step is not None:
|
|
253
|
+
path.append(step)
|
|
254
|
+
step = parents[step]
|
|
255
|
+
path.reverse()
|
|
256
|
+
return path
|
|
257
|
+
queue.append(neighbor)
|
|
258
|
+
return None
|
|
259
|
+
|
|
260
|
+
def get_connected_components(self) -> list[list[str]]:
|
|
261
|
+
"""Return each connected group of nodes as a list.
|
|
262
|
+
|
|
263
|
+
Components are listed by their earliest-added node; nodes within each
|
|
264
|
+
component follow a breadth-first visit order.
|
|
265
|
+
"""
|
|
266
|
+
components = []
|
|
267
|
+
visited = set()
|
|
268
|
+
for start in self._node_data:
|
|
269
|
+
if start in visited:
|
|
270
|
+
continue
|
|
271
|
+
component = []
|
|
272
|
+
queue = deque([start])
|
|
273
|
+
visited.add(start)
|
|
274
|
+
while queue:
|
|
275
|
+
current = queue.popleft()
|
|
276
|
+
component.append(current)
|
|
277
|
+
for neighbor in self._adjacency[current]:
|
|
278
|
+
if neighbor not in visited:
|
|
279
|
+
visited.add(neighbor)
|
|
280
|
+
queue.append(neighbor)
|
|
281
|
+
components.append(component)
|
|
282
|
+
return components
|
|
283
|
+
|
|
284
|
+
def get_isolated_nodes(self) -> list[str]:
|
|
285
|
+
"""Return nodes with no edges, in node insertion order."""
|
|
286
|
+
return [name for name in self._node_data if not self._adjacency[name]]
|
|
287
|
+
|
|
288
|
+
def is_connected(self) -> bool:
|
|
289
|
+
"""Return whether every node is in one connected component.
|
|
290
|
+
|
|
291
|
+
An empty graph is considered disconnected.
|
|
292
|
+
"""
|
|
293
|
+
return bool(self._node_data) and len(self.get_connected_components()) == 1
|
|
294
|
+
|
|
295
|
+
def find_cycles(self) -> list[list[str]]:
|
|
296
|
+
"""Return every unique simple cycle in the graph.
|
|
297
|
+
|
|
298
|
+
Each cycle repeats its first node at the end, for example
|
|
299
|
+
``["A", "B", "C", "A"]``. A cycle is reported once, regardless of
|
|
300
|
+
its starting point or direction. Finding all simple cycles can take
|
|
301
|
+
exponential time when a graph contains many cycles.
|
|
302
|
+
"""
|
|
303
|
+
node_order = {name: index for index, name in enumerate(self._node_data)}
|
|
304
|
+
cycles = []
|
|
305
|
+
|
|
306
|
+
for start in self._node_data:
|
|
307
|
+
start_index = node_order[start]
|
|
308
|
+
path = [start]
|
|
309
|
+
visited = {start}
|
|
310
|
+
|
|
311
|
+
def visit(current: str) -> None:
|
|
312
|
+
for neighbor in self._adjacency[current]:
|
|
313
|
+
if neighbor == start:
|
|
314
|
+
if len(path) >= 3 and node_order[path[1]] < node_order[path[-1]]:
|
|
315
|
+
cycles.append(path.copy() + [start])
|
|
316
|
+
elif node_order[neighbor] > start_index and neighbor not in visited:
|
|
317
|
+
visited.add(neighbor)
|
|
318
|
+
path.append(neighbor)
|
|
319
|
+
visit(neighbor)
|
|
320
|
+
path.pop()
|
|
321
|
+
visited.remove(neighbor)
|
|
322
|
+
|
|
323
|
+
visit(start)
|
|
324
|
+
return cycles
|
|
325
|
+
|
|
326
|
+
def to_ascii(self, crossing: str = "x") -> str:
|
|
327
|
+
"""Return a compact layered ASCII drawing of the graph.
|
|
328
|
+
|
|
329
|
+
``crossing`` chooses the mark where differently directed edge strokes
|
|
330
|
+
meet: ``"x"`` (default), ``"+"``, or ``""`` for a blank. Nodes are
|
|
331
|
+
placed in a five-column grid; edge strokes are drawn behind labels.
|
|
332
|
+
"""
|
|
333
|
+
if crossing != "" and crossing != "+" and crossing != "x":
|
|
334
|
+
raise ValueError('crossing must be "", "+", or "x"')
|
|
335
|
+
names = list(self._node_data)
|
|
336
|
+
if not names:
|
|
337
|
+
return "(empty graph)"
|
|
338
|
+
|
|
339
|
+
labels = {}
|
|
340
|
+
for name in names:
|
|
341
|
+
visible_name = (
|
|
342
|
+
name.replace("\n", "\\n")
|
|
343
|
+
.replace("\r", "\\r")
|
|
344
|
+
.replace("\t", "\\t")
|
|
345
|
+
)
|
|
346
|
+
labels[name] = "[" + visible_name + "]"
|
|
347
|
+
widest_label = max(len(label) for label in labels.values())
|
|
348
|
+
column_count = min(5, len(names))
|
|
349
|
+
column_spacing = max(8, widest_label + 3)
|
|
350
|
+
row_spacing = 4
|
|
351
|
+
positions: dict[str, list[int]] = {}
|
|
352
|
+
for index, name in enumerate(names):
|
|
353
|
+
column = index % column_count
|
|
354
|
+
row = index // column_count
|
|
355
|
+
positions[name] = [2 + column * column_spacing, 1 + row * row_spacing]
|
|
356
|
+
|
|
357
|
+
row_count = (len(names) + column_count - 1) // column_count
|
|
358
|
+
canvas_width = 2 + (column_count - 1) * column_spacing + widest_label + 4
|
|
359
|
+
canvas_height = 1 + (row_count - 1) * row_spacing + 2
|
|
360
|
+
canvas = [[" "] * canvas_width for _ in range(canvas_height)]
|
|
361
|
+
occupied: dict[int, list[str]] = {}
|
|
362
|
+
|
|
363
|
+
for edge in self._edges:
|
|
364
|
+
x1, y1 = positions[edge[0]]
|
|
365
|
+
x2, y2 = positions[edge[1]]
|
|
366
|
+
dx = x2 - x1
|
|
367
|
+
dy = y2 - y1
|
|
368
|
+
if dy == 0:
|
|
369
|
+
stroke = "-"
|
|
370
|
+
elif dx == 0:
|
|
371
|
+
stroke = "|"
|
|
372
|
+
elif dx * dy > 0:
|
|
373
|
+
stroke = "\\"
|
|
374
|
+
else:
|
|
375
|
+
stroke = "/"
|
|
376
|
+
|
|
377
|
+
if dx != 0 and dy != 0:
|
|
378
|
+
step_count = abs(dy)
|
|
379
|
+
else:
|
|
380
|
+
step_count = max(abs(dx), abs(dy))
|
|
381
|
+
for step in range(1, step_count):
|
|
382
|
+
x = round(x1 + dx * step / step_count)
|
|
383
|
+
y = round(y1 + dy * step / step_count)
|
|
384
|
+
cell = y * canvas_width + x
|
|
385
|
+
occupied.setdefault(cell, []).append(stroke)
|
|
386
|
+
|
|
387
|
+
for cell, strokes in occupied.items():
|
|
388
|
+
x = cell % canvas_width
|
|
389
|
+
y = cell // canvas_width
|
|
390
|
+
stroke_kinds = set(strokes)
|
|
391
|
+
if len(stroke_kinds) > 1:
|
|
392
|
+
canvas[y][x] = crossing or " "
|
|
393
|
+
else:
|
|
394
|
+
canvas[y][x] = strokes[0]
|
|
395
|
+
|
|
396
|
+
for name in names:
|
|
397
|
+
x, y = positions[name]
|
|
398
|
+
label = labels[name]
|
|
399
|
+
start = x - (len(label) // 2)
|
|
400
|
+
for offset, character in enumerate(label):
|
|
401
|
+
canvas[y][start + offset] = character
|
|
402
|
+
|
|
403
|
+
return "\n".join("".join(row).rstrip() for row in canvas).strip("\n")
|
|
404
|
+
|
|
405
|
+
def __str__(self) -> str:
|
|
406
|
+
"""Return the default ASCII drawing used by ``print(graph)``."""
|
|
407
|
+
return self.to_ascii()
|
|
408
|
+
|
|
409
|
+
def show(self) -> None:
|
|
410
|
+
"""Draw the graph as an image using Matplotlib.
|
|
411
|
+
|
|
412
|
+
This method requires the optional ``visualization`` dependency. In the
|
|
413
|
+
supported Pyodide browser runtime, Matplotlib's ``show()`` is connected
|
|
414
|
+
to the platform's PNG image renderer.
|
|
415
|
+
"""
|
|
416
|
+
try:
|
|
417
|
+
import matplotlib.pyplot as plt
|
|
418
|
+
except ImportError as error:
|
|
419
|
+
raise ImportError(
|
|
420
|
+
"Graph.show() requires Matplotlib. Install pygraphds with the "
|
|
421
|
+
"'visualization' extra or install matplotlib in your Python runtime."
|
|
422
|
+
) from error
|
|
423
|
+
|
|
424
|
+
names = list(self._node_data)
|
|
425
|
+
figure_size = max(5.0, min(10.0, 4.2 + math.sqrt(max(1, len(names))) * 0.4))
|
|
426
|
+
figure, axes = plt.subplots(figsize=[figure_size, figure_size])
|
|
427
|
+
axes.set_aspect("equal")
|
|
428
|
+
axes.axis("off")
|
|
429
|
+
|
|
430
|
+
if not names:
|
|
431
|
+
axes.text(0.5, 0.5, "Empty graph", ha="center", va="center")
|
|
432
|
+
axes.set_xlim(-1, 1)
|
|
433
|
+
axes.set_ylim(-1, 1)
|
|
434
|
+
else:
|
|
435
|
+
radius = max(1.6, math.sqrt(len(names)) * 0.68)
|
|
436
|
+
positions: dict[str, list[float]] = {}
|
|
437
|
+
for index, name in enumerate(names):
|
|
438
|
+
angle = (2 * math.pi * index / len(names)) - (math.pi / 2)
|
|
439
|
+
positions[name] = [radius * math.cos(angle), radius * math.sin(angle)]
|
|
440
|
+
|
|
441
|
+
for edge in self._edges:
|
|
442
|
+
start = positions[edge[0]]
|
|
443
|
+
end = positions[edge[1]]
|
|
444
|
+
axes.plot(
|
|
445
|
+
[start[0], end[0]],
|
|
446
|
+
[start[1], end[1]],
|
|
447
|
+
color="#64748b",
|
|
448
|
+
linewidth=1.5,
|
|
449
|
+
zorder=1,
|
|
450
|
+
)
|
|
451
|
+
|
|
452
|
+
x_values = [positions[name][0] for name in names]
|
|
453
|
+
y_values = [positions[name][1] for name in names]
|
|
454
|
+
axes.scatter(
|
|
455
|
+
x_values,
|
|
456
|
+
y_values,
|
|
457
|
+
s=560,
|
|
458
|
+
color="#dbeafe",
|
|
459
|
+
edgecolors="#2563eb",
|
|
460
|
+
linewidths=1.5,
|
|
461
|
+
zorder=2,
|
|
462
|
+
)
|
|
463
|
+
for name in names:
|
|
464
|
+
x, y = positions[name]
|
|
465
|
+
axes.text(
|
|
466
|
+
x,
|
|
467
|
+
y,
|
|
468
|
+
name,
|
|
469
|
+
ha="center",
|
|
470
|
+
va="center",
|
|
471
|
+
fontsize=9,
|
|
472
|
+
color="#172554",
|
|
473
|
+
zorder=3,
|
|
474
|
+
)
|
|
475
|
+
axes.margins(0.25)
|
|
476
|
+
|
|
477
|
+
figure.tight_layout()
|
|
478
|
+
plt.show()
|
|
479
|
+
|
|
480
|
+
def copy(self) -> Graph:
|
|
481
|
+
"""Return a deep, independent copy of the complete graph."""
|
|
482
|
+
return deepcopy(self)
|
|
@@ -0,0 +1,86 @@
|
|
|
1
|
+
Metadata-Version: 2.4
|
|
2
|
+
Name: pygraphds
|
|
3
|
+
Version: 0.1.0
|
|
4
|
+
Summary: Beginner-friendly graph data structures and operations
|
|
5
|
+
Author: Dr. Mohamed B.
|
|
6
|
+
License-Expression: MIT
|
|
7
|
+
Project-URL: Documentation, https://pygraphds.readthedocs.io/
|
|
8
|
+
Project-URL: Repository, https://gitlab.com/ujen.teaching/pygraphds
|
|
9
|
+
Project-URL: Issues, https://gitlab.com/ujen.teaching/pygraphds/-/issues
|
|
10
|
+
Keywords: graph,data-structures,education,teaching
|
|
11
|
+
Classifier: Development Status :: 3 - Alpha
|
|
12
|
+
Classifier: Intended Audience :: Education
|
|
13
|
+
Classifier: Operating System :: OS Independent
|
|
14
|
+
Classifier: Programming Language :: Python :: 3
|
|
15
|
+
Classifier: Programming Language :: Python :: 3 :: Only
|
|
16
|
+
Classifier: Topic :: Education
|
|
17
|
+
Classifier: Topic :: Scientific/Engineering :: Mathematics
|
|
18
|
+
Requires-Python: >=3.9
|
|
19
|
+
Description-Content-Type: text/markdown
|
|
20
|
+
License-File: LICENSE
|
|
21
|
+
Provides-Extra: visualization
|
|
22
|
+
Requires-Dist: matplotlib>=3.7; extra == "visualization"
|
|
23
|
+
Dynamic: license-file
|
|
24
|
+
|
|
25
|
+
# pygraphds
|
|
26
|
+
|
|
27
|
+
`pygraphds` is a small, beginner-friendly library for learning graph data
|
|
28
|
+
structures and their most common operations. It focuses on clear names,
|
|
29
|
+
predictable behavior, and short examples instead of a large graph framework.
|
|
30
|
+
|
|
31
|
+
The library provides undirected graphs with string-named nodes, optional node
|
|
32
|
+
and edge data, paths, connected components, cycle finding, a compact terminal
|
|
33
|
+
drawing, and an optional Matplotlib image drawing.
|
|
34
|
+
|
|
35
|
+
## Install
|
|
36
|
+
|
|
37
|
+
```bash
|
|
38
|
+
python -m pip install pygraphds
|
|
39
|
+
```
|
|
40
|
+
|
|
41
|
+
To use `Graph.show()`, install the optional visualization dependency:
|
|
42
|
+
|
|
43
|
+
```bash
|
|
44
|
+
python -m pip install "pygraphds[visualization]"
|
|
45
|
+
```
|
|
46
|
+
|
|
47
|
+
## Quick start
|
|
48
|
+
|
|
49
|
+
```python
|
|
50
|
+
from pygraphds import Graph
|
|
51
|
+
|
|
52
|
+
graph = Graph()
|
|
53
|
+
graph.add_node("Library")
|
|
54
|
+
graph.add_node("Cafe")
|
|
55
|
+
graph.add_node("Park")
|
|
56
|
+
|
|
57
|
+
graph.add_edge("Library", "Cafe", data={"minutes": 4})
|
|
58
|
+
graph.add_edge("Cafe", "Park", data={"minutes": 7})
|
|
59
|
+
|
|
60
|
+
print(graph)
|
|
61
|
+
print(graph.get_neighbors("Cafe"))
|
|
62
|
+
print(graph.get_path("Library", "Park"))
|
|
63
|
+
```
|
|
64
|
+
|
|
65
|
+
Call `graph.show()` to draw the graph as an image. In the EE 460 Pyodide
|
|
66
|
+
browser runtime, load Matplotlib first; `Graph.show()` calls Matplotlib's
|
|
67
|
+
`show()` function so the platform's existing PNG renderer displays the image.
|
|
68
|
+
|
|
69
|
+
## Behavior at a glance
|
|
70
|
+
|
|
71
|
+
- Graphs are undirected.
|
|
72
|
+
- Node names are unique, nonempty strings, and keep insertion order.
|
|
73
|
+
- Self-loops and duplicate edges are not allowed.
|
|
74
|
+
- An edge can only be added when both nodes exist.
|
|
75
|
+
- `get_neighbors(name)` returns nodes one edge away from `name`.
|
|
76
|
+
- `get_path(start, end)` returns a shortest path or `None` when no path exists.
|
|
77
|
+
- Edge endpoints are returned as lists, such as `["Library", "Cafe"]`.
|
|
78
|
+
- `copy()` makes a deep, independent copy, including node and edge data.
|
|
79
|
+
|
|
80
|
+
## Documentation
|
|
81
|
+
|
|
82
|
+
Read the full guide and API reference at [pygraphds on Read the Docs](https://pygraphds.readthedocs.io/).
|
|
83
|
+
|
|
84
|
+
## License
|
|
85
|
+
|
|
86
|
+
MIT
|
|
@@ -0,0 +1,7 @@
|
|
|
1
|
+
pygraphds/__init__.py,sha256=8bljFl7vRnU3WZQzfA7olmeeNhcRWLgcVXPAZOTZjOc,134
|
|
2
|
+
pygraphds/graph.py,sha256=VH91vj4y-qmF1qKrQEStQJe6_eWCsZJCpBgROm4VtYo,18006
|
|
3
|
+
pygraphds-0.1.0.dist-info/licenses/LICENSE,sha256=BGBPK8CC5D40GSEibBizJEDv0rvamCocbHkDaofz7Zw,1071
|
|
4
|
+
pygraphds-0.1.0.dist-info/METADATA,sha256=fdQycIQ3A-ZcUFckmzWHnAo60LtN82e-pZK4S7UzsSA,2799
|
|
5
|
+
pygraphds-0.1.0.dist-info/WHEEL,sha256=mOdXR9C3wMVov7cSY8PY-XCzo3SmmWCHvGQr5csJoao,91
|
|
6
|
+
pygraphds-0.1.0.dist-info/top_level.txt,sha256=IWzM-kKqvEkaUBcbXUUI6Je-EZPcvP93M8b0sLXXqD4,10
|
|
7
|
+
pygraphds-0.1.0.dist-info/RECORD,,
|
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026 Dr. Mohamed B.
|
|
4
|
+
|
|
5
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
6
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
7
|
+
in the Software without restriction, including without limitation the rights
|
|
8
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
9
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
10
|
+
furnished to do so, subject to the following conditions:
|
|
11
|
+
|
|
12
|
+
The above copyright notice and this permission notice shall be included in all
|
|
13
|
+
copies or substantial portions of the Software.
|
|
14
|
+
|
|
15
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
16
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
17
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
18
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
19
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
20
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
21
|
+
SOFTWARE.
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
pygraphds
|