graphwise 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.
- graphwise/__init__.py +151 -0
- graphwise/centrality.py +314 -0
- graphwise/community.py +422 -0
- graphwise/connectivity.py +245 -0
- graphwise/dag.py +160 -0
- graphwise/eulerian.py +170 -0
- graphwise/exceptions.py +47 -0
- graphwise/flow.py +155 -0
- graphwise/graph.py +321 -0
- graphwise/py.typed +0 -0
- graphwise/shortest_paths.py +502 -0
- graphwise/spanning_trees.py +122 -0
- graphwise/traversal.py +129 -0
- graphwise/union_find.py +127 -0
- graphwise-0.1.0.dist-info/METADATA +247 -0
- graphwise-0.1.0.dist-info/RECORD +18 -0
- graphwise-0.1.0.dist-info/WHEEL +4 -0
- graphwise-0.1.0.dist-info/licenses/LICENSE +21 -0
graphwise/traversal.py
ADDED
|
@@ -0,0 +1,129 @@
|
|
|
1
|
+
"""Graph traversal: breadth-first search, depth-first search and random walks.
|
|
2
|
+
|
|
3
|
+
These are the primitives most other graph algorithms are built from. BFS
|
|
4
|
+
visits nodes in order of hop distance, so it finds shortest paths in
|
|
5
|
+
unweighted graphs. DFS goes as deep as it can before backtracking, which is
|
|
6
|
+
what cycle detection, topological sorting and Tarjan's algorithms rely on.
|
|
7
|
+
"""
|
|
8
|
+
|
|
9
|
+
from __future__ import annotations
|
|
10
|
+
|
|
11
|
+
import random
|
|
12
|
+
from collections.abc import Hashable, Iterator
|
|
13
|
+
from typing import Any
|
|
14
|
+
|
|
15
|
+
from .graph import _BaseGraph
|
|
16
|
+
|
|
17
|
+
__all__ = ["bfs", "bfs_layers", "dfs", "random_walk"]
|
|
18
|
+
|
|
19
|
+
|
|
20
|
+
def bfs(graph: _BaseGraph[Any], source: Hashable) -> Iterator[Any]:
|
|
21
|
+
"""Yield the nodes reachable from ``source`` in breadth-first order.
|
|
22
|
+
|
|
23
|
+
Time O(V + E), space O(V).
|
|
24
|
+
|
|
25
|
+
>>> from graphwise import Graph
|
|
26
|
+
>>> list(bfs(Graph([(1, 2), (1, 3), (2, 4)]), 1))
|
|
27
|
+
[1, 2, 3, 4]
|
|
28
|
+
"""
|
|
29
|
+
for layer in bfs_layers(graph, source):
|
|
30
|
+
yield from layer
|
|
31
|
+
|
|
32
|
+
|
|
33
|
+
def bfs_layers(graph: _BaseGraph[Any], source: Hashable) -> Iterator[list[Any]]:
|
|
34
|
+
"""Yield lists of nodes grouped by hop distance from ``source``.
|
|
35
|
+
|
|
36
|
+
Layer ``k`` holds every node whose shortest unweighted path from
|
|
37
|
+
``source`` has ``k`` edges. Time O(V + E).
|
|
38
|
+
|
|
39
|
+
>>> from graphwise import Graph
|
|
40
|
+
>>> list(bfs_layers(Graph([(1, 2), (1, 3), (2, 4)]), 1))
|
|
41
|
+
[[1], [2, 3], [4]]
|
|
42
|
+
"""
|
|
43
|
+
graph._check_node(source)
|
|
44
|
+
adj = graph._adj
|
|
45
|
+
seen = {source}
|
|
46
|
+
layer = [source]
|
|
47
|
+
while layer:
|
|
48
|
+
yield layer
|
|
49
|
+
nxt = []
|
|
50
|
+
for u in layer:
|
|
51
|
+
for v in adj[u]:
|
|
52
|
+
if v not in seen:
|
|
53
|
+
seen.add(v)
|
|
54
|
+
nxt.append(v)
|
|
55
|
+
layer = nxt
|
|
56
|
+
|
|
57
|
+
|
|
58
|
+
def dfs(graph: _BaseGraph[Any], source: Hashable) -> Iterator[Any]:
|
|
59
|
+
"""Yield the nodes reachable from ``source`` in depth-first preorder.
|
|
60
|
+
|
|
61
|
+
The order matches the textbook recursive DFS, but the implementation uses
|
|
62
|
+
an explicit stack, so long paths cannot hit Python's recursion limit.
|
|
63
|
+
Time O(V + E).
|
|
64
|
+
|
|
65
|
+
>>> from graphwise import Graph
|
|
66
|
+
>>> list(dfs(Graph([(1, 2), (1, 3), (2, 4)]), 1))
|
|
67
|
+
[1, 2, 4, 3]
|
|
68
|
+
"""
|
|
69
|
+
graph._check_node(source)
|
|
70
|
+
adj = graph._adj
|
|
71
|
+
seen = {source}
|
|
72
|
+
yield source
|
|
73
|
+
# A stack of neighbour iterators: each entry is one paused recursive call.
|
|
74
|
+
stack: list[Iterator[Any]] = [iter(adj[source])]
|
|
75
|
+
while stack:
|
|
76
|
+
for v in stack[-1]:
|
|
77
|
+
if v not in seen:
|
|
78
|
+
seen.add(v)
|
|
79
|
+
yield v
|
|
80
|
+
stack.append(iter(adj[v]))
|
|
81
|
+
break
|
|
82
|
+
else:
|
|
83
|
+
stack.pop()
|
|
84
|
+
|
|
85
|
+
|
|
86
|
+
def random_walk(
|
|
87
|
+
graph: _BaseGraph[Any],
|
|
88
|
+
start: Hashable,
|
|
89
|
+
steps: int,
|
|
90
|
+
*,
|
|
91
|
+
weighted: bool = False,
|
|
92
|
+
seed: int | random.Random | None = None,
|
|
93
|
+
) -> list[Any]:
|
|
94
|
+
"""Take a random walk of up to ``steps`` steps from ``start``.
|
|
95
|
+
|
|
96
|
+
Each step moves to a neighbour chosen uniformly at random, or with
|
|
97
|
+
probability proportional to edge weight when ``weighted=True``. The walk
|
|
98
|
+
ends early at a node with no outgoing edges. It returns the visited nodes,
|
|
99
|
+
``start`` included, so a full walk has ``steps + 1`` entries.
|
|
100
|
+
|
|
101
|
+
Random walks underlie PageRank, node2vec/DeepWalk embeddings, Monte Carlo
|
|
102
|
+
estimates of hitting times, and sampling from very large graphs.
|
|
103
|
+
|
|
104
|
+
>>> from graphwise import DiGraph
|
|
105
|
+
>>> random_walk(DiGraph([(1, 2), (2, 3)]), 1, steps=5, seed=0)
|
|
106
|
+
[1, 2, 3]
|
|
107
|
+
"""
|
|
108
|
+
if steps < 0:
|
|
109
|
+
raise ValueError("steps must be non-negative")
|
|
110
|
+
graph._check_node(start)
|
|
111
|
+
rng = seed if isinstance(seed, random.Random) else random.Random(seed)
|
|
112
|
+
adj = graph._adj
|
|
113
|
+
walk = [start]
|
|
114
|
+
node = start
|
|
115
|
+
for _ in range(steps):
|
|
116
|
+
nbrs = adj[node]
|
|
117
|
+
if not nbrs:
|
|
118
|
+
break
|
|
119
|
+
if weighted:
|
|
120
|
+
weights = list(nbrs.values())
|
|
121
|
+
if any(w < 0 for w in weights):
|
|
122
|
+
raise ValueError("weighted random walk requires non-negative weights")
|
|
123
|
+
if sum(weights) == 0:
|
|
124
|
+
break
|
|
125
|
+
node = rng.choices(list(nbrs), weights=weights)[0]
|
|
126
|
+
else:
|
|
127
|
+
node = rng.choice(list(nbrs))
|
|
128
|
+
walk.append(node)
|
|
129
|
+
return walk
|
graphwise/union_find.py
ADDED
|
@@ -0,0 +1,127 @@
|
|
|
1
|
+
"""Union-find (disjoint-set forest) for tracking connectivity as it changes.
|
|
2
|
+
|
|
3
|
+
Every element points to a parent, and each set is a tree whose root is the
|
|
4
|
+
set's representative. Two optimizations keep the trees almost flat:
|
|
5
|
+
|
|
6
|
+
* **Union by rank**: the shorter tree is attached under the taller one.
|
|
7
|
+
* **Path compression**: ``find`` re-points every node on the path it walks
|
|
8
|
+
straight at the root.
|
|
9
|
+
|
|
10
|
+
Together they give an amortized cost of O(α(n)) per operation. α is the
|
|
11
|
+
inverse Ackermann function, which is below 5 for any input that fits in the
|
|
12
|
+
universe, so each operation is constant time in practice.
|
|
13
|
+
|
|
14
|
+
Uses: Kruskal's MST, cycle detection, connected components on a stream of
|
|
15
|
+
edges, percolation, image segmentation, and account or entity merging.
|
|
16
|
+
|
|
17
|
+
References
|
|
18
|
+
----------
|
|
19
|
+
* Tarjan, R. E. (1975). Efficiency of a good but not linear set union algorithm.
|
|
20
|
+
*JACM* 22(2).
|
|
21
|
+
* https://en.wikipedia.org/wiki/Disjoint-set_data_structure
|
|
22
|
+
"""
|
|
23
|
+
|
|
24
|
+
from __future__ import annotations
|
|
25
|
+
|
|
26
|
+
from collections.abc import Hashable, Iterable, Iterator
|
|
27
|
+
from typing import Generic, TypeVar
|
|
28
|
+
|
|
29
|
+
__all__ = ["DisjointSet"]
|
|
30
|
+
|
|
31
|
+
T = TypeVar("T", bound=Hashable)
|
|
32
|
+
|
|
33
|
+
|
|
34
|
+
class DisjointSet(Generic[T]):
|
|
35
|
+
"""A collection of disjoint sets that supports *union* and *find*.
|
|
36
|
+
|
|
37
|
+
>>> ds = DisjointSet(["a", "b", "c"])
|
|
38
|
+
>>> ds.union("a", "b")
|
|
39
|
+
True
|
|
40
|
+
>>> ds.connected("a", "b"), ds.connected("a", "c")
|
|
41
|
+
(True, False)
|
|
42
|
+
>>> ds.n_sets
|
|
43
|
+
2
|
|
44
|
+
"""
|
|
45
|
+
|
|
46
|
+
def __init__(self, elements: Iterable[T] = ()) -> None:
|
|
47
|
+
self._parent: dict[T, T] = {}
|
|
48
|
+
self._rank: dict[T, int] = {}
|
|
49
|
+
self._size: dict[T, int] = {}
|
|
50
|
+
self._n_sets = 0
|
|
51
|
+
for x in elements:
|
|
52
|
+
self.make_set(x)
|
|
53
|
+
|
|
54
|
+
def make_set(self, x: T) -> None:
|
|
55
|
+
"""Add ``x`` as a new singleton set. An existing element is left alone."""
|
|
56
|
+
if x not in self._parent:
|
|
57
|
+
self._parent[x] = x
|
|
58
|
+
self._rank[x] = 0
|
|
59
|
+
self._size[x] = 1
|
|
60
|
+
self._n_sets += 1
|
|
61
|
+
|
|
62
|
+
def find(self, x: T) -> T:
|
|
63
|
+
"""Return the representative (root) of the set holding ``x``.
|
|
64
|
+
|
|
65
|
+
Raises ``KeyError`` if ``x`` was never added. This version is iterative,
|
|
66
|
+
so very deep trees cannot overflow the recursion limit.
|
|
67
|
+
"""
|
|
68
|
+
parent = self._parent
|
|
69
|
+
root = x
|
|
70
|
+
while parent[root] != root:
|
|
71
|
+
root = parent[root]
|
|
72
|
+
while parent[x] != root: # path compression
|
|
73
|
+
parent[x], x = root, parent[x]
|
|
74
|
+
return root
|
|
75
|
+
|
|
76
|
+
def union(self, x: T, y: T) -> bool:
|
|
77
|
+
"""Merge the sets holding ``x`` and ``y``. Missing elements are added.
|
|
78
|
+
|
|
79
|
+
Returns True if two sets were merged, or False if ``x`` and ``y`` were
|
|
80
|
+
already in the same set. For edges arriving in an undirected graph,
|
|
81
|
+
False means the new edge closes a cycle.
|
|
82
|
+
"""
|
|
83
|
+
self.make_set(x)
|
|
84
|
+
self.make_set(y)
|
|
85
|
+
rx, ry = self.find(x), self.find(y)
|
|
86
|
+
if rx == ry:
|
|
87
|
+
return False
|
|
88
|
+
if self._rank[rx] < self._rank[ry]:
|
|
89
|
+
rx, ry = ry, rx
|
|
90
|
+
self._parent[ry] = rx # attach the shorter tree under the taller one
|
|
91
|
+
self._size[rx] += self._size[ry]
|
|
92
|
+
if self._rank[rx] == self._rank[ry]:
|
|
93
|
+
self._rank[rx] += 1
|
|
94
|
+
self._n_sets -= 1
|
|
95
|
+
return True
|
|
96
|
+
|
|
97
|
+
def connected(self, x: T, y: T) -> bool:
|
|
98
|
+
"""Return True if ``x`` and ``y`` are in the same set."""
|
|
99
|
+
return self.find(x) == self.find(y)
|
|
100
|
+
|
|
101
|
+
def set_size(self, x: T) -> int:
|
|
102
|
+
"""Return the number of elements in the set holding ``x``."""
|
|
103
|
+
return self._size[self.find(x)]
|
|
104
|
+
|
|
105
|
+
@property
|
|
106
|
+
def n_sets(self) -> int:
|
|
107
|
+
"""The number of disjoint sets."""
|
|
108
|
+
return self._n_sets
|
|
109
|
+
|
|
110
|
+
def groups(self) -> list[set[T]]:
|
|
111
|
+
"""Return the sets, each as a Python ``set``."""
|
|
112
|
+
out: dict[T, set[T]] = {}
|
|
113
|
+
for x in self._parent:
|
|
114
|
+
out.setdefault(self.find(x), set()).add(x)
|
|
115
|
+
return list(out.values())
|
|
116
|
+
|
|
117
|
+
def __contains__(self, x: object) -> bool:
|
|
118
|
+
return x in self._parent
|
|
119
|
+
|
|
120
|
+
def __len__(self) -> int:
|
|
121
|
+
return len(self._parent)
|
|
122
|
+
|
|
123
|
+
def __iter__(self) -> Iterator[T]:
|
|
124
|
+
return iter(self._parent)
|
|
125
|
+
|
|
126
|
+
def __repr__(self) -> str:
|
|
127
|
+
return f"DisjointSet(elements={len(self)}, sets={self._n_sets})"
|
|
@@ -0,0 +1,247 @@
|
|
|
1
|
+
Metadata-Version: 2.5
|
|
2
|
+
Name: graphwise
|
|
3
|
+
Version: 0.1.0
|
|
4
|
+
Summary: Canonical graph algorithms in readable, tested, dependency-free Python, for studying them and for using them.
|
|
5
|
+
Project-URL: Homepage, https://github.com/carjam/graphwise
|
|
6
|
+
Project-URL: Source, https://github.com/carjam/graphwise
|
|
7
|
+
Project-URL: Issues, https://github.com/carjam/graphwise/issues
|
|
8
|
+
Author: James Carson
|
|
9
|
+
License-Expression: MIT
|
|
10
|
+
License-File: LICENSE
|
|
11
|
+
Keywords: algorithms,community-detection,data-structures,dijkstra,graph,graph-algorithms,louvain,max-flow,minimum-spanning-tree,network-analysis,pagerank,shortest-path,topological-sort,union-find
|
|
12
|
+
Classifier: Development Status :: 4 - Beta
|
|
13
|
+
Classifier: Intended Audience :: Developers
|
|
14
|
+
Classifier: Intended Audience :: Education
|
|
15
|
+
Classifier: Intended Audience :: Science/Research
|
|
16
|
+
Classifier: Operating System :: OS Independent
|
|
17
|
+
Classifier: Programming Language :: Python :: 3
|
|
18
|
+
Classifier: Programming Language :: Python :: 3 :: Only
|
|
19
|
+
Classifier: Programming Language :: Python :: 3.10
|
|
20
|
+
Classifier: Programming Language :: Python :: 3.11
|
|
21
|
+
Classifier: Programming Language :: Python :: 3.12
|
|
22
|
+
Classifier: Programming Language :: Python :: 3.13
|
|
23
|
+
Classifier: Programming Language :: Python :: 3.14
|
|
24
|
+
Classifier: Topic :: Scientific/Engineering :: Information Analysis
|
|
25
|
+
Classifier: Topic :: Scientific/Engineering :: Mathematics
|
|
26
|
+
Classifier: Topic :: Software Development :: Libraries :: Python Modules
|
|
27
|
+
Classifier: Typing :: Typed
|
|
28
|
+
Requires-Python: >=3.10
|
|
29
|
+
Provides-Extra: dev
|
|
30
|
+
Requires-Dist: build; extra == 'dev'
|
|
31
|
+
Requires-Dist: hypothesis>=6.100; extra == 'dev'
|
|
32
|
+
Requires-Dist: mypy>=1.10; extra == 'dev'
|
|
33
|
+
Requires-Dist: networkx>=3.2; extra == 'dev'
|
|
34
|
+
Requires-Dist: numpy; extra == 'dev'
|
|
35
|
+
Requires-Dist: pytest-cov>=5; extra == 'dev'
|
|
36
|
+
Requires-Dist: pytest>=8; extra == 'dev'
|
|
37
|
+
Requires-Dist: ruff>=0.6; extra == 'dev'
|
|
38
|
+
Requires-Dist: scipy; extra == 'dev'
|
|
39
|
+
Requires-Dist: twine; extra == 'dev'
|
|
40
|
+
Provides-Extra: test
|
|
41
|
+
Requires-Dist: hypothesis>=6.100; extra == 'test'
|
|
42
|
+
Requires-Dist: networkx>=3.2; extra == 'test'
|
|
43
|
+
Requires-Dist: numpy; extra == 'test'
|
|
44
|
+
Requires-Dist: pytest-cov>=5; extra == 'test'
|
|
45
|
+
Requires-Dist: pytest>=8; extra == 'test'
|
|
46
|
+
Requires-Dist: scipy; extra == 'test'
|
|
47
|
+
Description-Content-Type: text/markdown
|
|
48
|
+
|
|
49
|
+
# graphwise
|
|
50
|
+
|
|
51
|
+
**Canonical graph algorithms in readable, tested, dependency-free Python, for studying them and for using them.**
|
|
52
|
+
|
|
53
|
+
[](https://github.com/carjam/graphwise/actions/workflows/ci.yml)
|
|
54
|
+
[](https://github.com/carjam/graphwise/blob/main/LICENSE)
|
|
55
|
+

|
|
56
|
+

|
|
57
|
+
|
|
58
|
+
Dependency resolution, routing, fraud rings, arbitrage, network resilience,
|
|
59
|
+
recommendations: a surprising number of problems become easy once you see them
|
|
60
|
+
as a graph. graphwise collects about 40 of the classic algorithms behind those
|
|
61
|
+
problems in one small, typed package that you can both **read** and **use**.
|
|
62
|
+
|
|
63
|
+
- **To study:** each algorithm is a short, commented function. Its docstring
|
|
64
|
+
covers the core idea, why it works, its time complexity, and the original
|
|
65
|
+
paper. Each module opens with a guide to its family of algorithms (for
|
|
66
|
+
example, "which shortest-path algorithm should I use?").
|
|
67
|
+
- **To use:** one `pip install`, no dependencies, any hashable value as a node,
|
|
68
|
+
clear exceptions (`NegativeCycle`, `NotADAG`, `NoPath`, …), and inputs that
|
|
69
|
+
are never modified. Graphs with long paths are fine too: every DFS keeps its
|
|
70
|
+
own stack, so Python's recursion limit never applies.
|
|
71
|
+
- **Correct:** every algorithm is checked against [networkx](https://networkx.org)
|
|
72
|
+
on thousands of randomly generated graphs, with 100% branch coverage enforced
|
|
73
|
+
in CI. [How it's tested](#how-correctness-is-verified).
|
|
74
|
+
|
|
75
|
+
## Install
|
|
76
|
+
|
|
77
|
+
Requires Python 3.10 or newer.
|
|
78
|
+
|
|
79
|
+
```bash
|
|
80
|
+
pip install git+https://github.com/carjam/graphwise.git
|
|
81
|
+
```
|
|
82
|
+
|
|
83
|
+
> [!NOTE]
|
|
84
|
+
> The package is not on PyPI yet. Once it is, the command will be `pip install graphwise`.
|
|
85
|
+
|
|
86
|
+
## Quick start
|
|
87
|
+
|
|
88
|
+
```python
|
|
89
|
+
import graphwise as gw
|
|
90
|
+
|
|
91
|
+
roads = gw.Graph([
|
|
92
|
+
("home", "cafe", 4), ("home", "park", 1), ("park", "cafe", 2),
|
|
93
|
+
("cafe", "office", 5), ("park", "office", 9),
|
|
94
|
+
])
|
|
95
|
+
|
|
96
|
+
gw.shortest_path(roads, "home", "office")
|
|
97
|
+
# (8, ['home', 'park', 'cafe', 'office'])
|
|
98
|
+
|
|
99
|
+
gw.yen_k_shortest_paths(roads, "home", "office", k=3) # ranked alternatives
|
|
100
|
+
# [(8, ['home', 'park', 'cafe', 'office']), (9, ['home', 'cafe', 'office']), (10, ['home', 'park', 'office'])]
|
|
101
|
+
|
|
102
|
+
gw.kruskal_mst(roads) # cheapest way to connect everything
|
|
103
|
+
# [('home', 'park', 1), ('cafe', 'park', 2), ('cafe', 'office', 5)]
|
|
104
|
+
|
|
105
|
+
pipeline = gw.DiGraph([("fetch", "clean"), ("clean", "train"), ("clean", "report"), ("train", "report")])
|
|
106
|
+
gw.topological_generations(pipeline) # run order, grouped into parallel stages
|
|
107
|
+
# [['fetch'], ['clean'], ['train'], ['report']]
|
|
108
|
+
```
|
|
109
|
+
|
|
110
|
+
Every algorithm is a plain function that takes the graph as its first argument.
|
|
111
|
+
Edge weights default to `1`.
|
|
112
|
+
|
|
113
|
+
## Apply it: worked examples
|
|
114
|
+
|
|
115
|
+
Each script in [`examples/`](https://github.com/carjam/graphwise/tree/main/examples)
|
|
116
|
+
runs as-is (`python examples/<name>.py`), and the test suite runs all of them.
|
|
117
|
+
|
|
118
|
+
| Problem | Graph view | Algorithms |
|
|
119
|
+
|---|---|---|
|
|
120
|
+
| [Package build order](https://github.com/carjam/graphwise/blob/main/examples/dependency_resolution.py) | packages → "must come before" edges | topological sort, generations, cycle finding |
|
|
121
|
+
| [Currency arbitrage](https://github.com/carjam/graphwise/blob/main/examples/currency_arbitrage.py) | currencies, with `-log(rate)` weights | Bellman-Ford negative-cycle detection |
|
|
122
|
+
| [Fraud ring detection](https://github.com/carjam/graphwise/blob/main/examples/fraud_rings.py) | accounts and payments | Louvain, personalized PageRank, label propagation |
|
|
123
|
+
| [Network resilience](https://github.com/carjam/graphwise/blob/main/examples/network_resilience.py) | sites and link capacities | articulation points, bridges, min cut / max flow |
|
|
124
|
+
| [Route planning](https://github.com/carjam/graphwise/blob/main/examples/route_planning.py) | a grid map | A* with a Manhattan heuristic, Yen's alternatives |
|
|
125
|
+
|
|
126
|
+
Output of `python examples/network_resilience.py`:
|
|
127
|
+
|
|
128
|
+
```text
|
|
129
|
+
Single points of failure (sites): ['chi', 'den', 'la']
|
|
130
|
+
Single points of failure (links): [('la', 'phx'), ('chi', 'den')]
|
|
131
|
+
|
|
132
|
+
Max NYC -> SF throughput: 40 Gbps
|
|
133
|
+
Bottleneck separates ['chi', 'dc', 'nyc'] from ['den', 'la', 'phx', 'sf']
|
|
134
|
+
Links to upgrade: [('chi', 'den', 40)]
|
|
135
|
+
```
|
|
136
|
+
|
|
137
|
+
## Study it: the algorithms
|
|
138
|
+
|
|
139
|
+
The table lists each algorithm's complexity, for V nodes and E edges. Each
|
|
140
|
+
module's docstring explains the ideas behind its family of algorithms.
|
|
141
|
+
`help(gw.johnson)` and similar calls give you the details of any single one.
|
|
142
|
+
|
|
143
|
+
| Family | Function | Time | Notes |
|
|
144
|
+
|---|---|---|---|
|
|
145
|
+
| **Traversal** | `bfs`, `bfs_layers`, `dfs` | O(V + E) | the building blocks for everything else |
|
|
146
|
+
| | `random_walk` | O(steps) | uniform or weight-proportional, seedable |
|
|
147
|
+
| **DAGs** | `topological_sort` (Kahn / DFS) | O(V + E) | `topological_generations` gives parallel stages |
|
|
148
|
+
| | `is_dag`, `find_cycle` | O(V + E) | `find_cycle` returns the actual cycle |
|
|
149
|
+
| **Shortest paths** | `dijkstra` | O((V + E) log V) | non-negative weights |
|
|
150
|
+
| | `astar` | ≤ Dijkstra | any admissible heuristic, consistent or not |
|
|
151
|
+
| | `bellman_ford` | O(VE) | negative weights; raises `NegativeCycle` |
|
|
152
|
+
| | `floyd_warshall` | O(V³) | all pairs, dense graphs |
|
|
153
|
+
| | `johnson` | O(VE + V² log V) | all pairs, sparse graphs, negative weights |
|
|
154
|
+
| | `yen_k_shortest_paths` | O(kV · Dijkstra) | k best loopless paths |
|
|
155
|
+
| **Spanning trees** | `kruskal_mst`, `prim_mst` | O(E log V) | spanning *forest* if the graph is disconnected |
|
|
156
|
+
| **Connectivity** | `connected_components` | O(V + E) | weak components for a `DiGraph` |
|
|
157
|
+
| | `strongly_connected_components` | O(V + E) | Tarjan; `condensation` gives the DAG of SCCs |
|
|
158
|
+
| | `bridges`, `articulation_points` | O(V + E) | single points of failure |
|
|
159
|
+
| **Eulerian** | `eulerian_circuit`, `eulerian_path` | O(E) | Hierholzer, directed or undirected |
|
|
160
|
+
| **Centrality** | `degree_centrality` (+ in/out) | O(V + E) | |
|
|
161
|
+
| | `closeness_centrality`, `harmonic_centrality` | O(V · SSSP) | harmonic works on disconnected graphs |
|
|
162
|
+
| | `betweenness_centrality` | O(VE + V² log V) | Brandes; weighted or unweighted |
|
|
163
|
+
| | `pagerank` | O(iterations · E) | supports personalization (seeded PageRank) |
|
|
164
|
+
| **Community** | `clustering`, `average_clustering` | O(V · d²) | weighted (Onnela) or unweighted |
|
|
165
|
+
| | `approximate_average_clustering` | O(trials) | sampling estimate, for huge graphs |
|
|
166
|
+
| | `modularity` | O(V + E) | directed and undirected, with a resolution parameter |
|
|
167
|
+
| | `louvain` | ~O(E log V) | multi-level modularity optimisation |
|
|
168
|
+
| | `label_propagation`, `propagate_labels` | O(E) per pass | unsupervised / semi-supervised |
|
|
169
|
+
| **Flow** | `max_flow`, `minimum_cut` | O(V²E) | Dinic; any node labels, antiparallel edges allowed |
|
|
170
|
+
| **Union-find** | `DisjointSet` | O(α(n)) amortized | union by rank plus path compression |
|
|
171
|
+
|
|
172
|
+
All of these are importable from the top level (`gw.dijkstra`, `gw.louvain`,
|
|
173
|
+
and so on), and each lives in a module named for its family, such as
|
|
174
|
+
`graphwise.shortest_paths`.
|
|
175
|
+
|
|
176
|
+
## Conventions
|
|
177
|
+
|
|
178
|
+
- **Graphs.** `Graph` is undirected and `DiGraph` is directed. Both are
|
|
179
|
+
weighted, simple graphs stored as `{u: {v: weight}}`. Build one from
|
|
180
|
+
`(u, v)` or `(u, v, weight)` tuples. `g[u]` gives a read-only view of
|
|
181
|
+
`{neighbor: weight}`.
|
|
182
|
+
- **Single-source results** are `(dist, pred)` dicts. Unreachable nodes are
|
|
183
|
+
left out of both. Use `gw.reconstruct_path(pred, source, target)` to turn
|
|
184
|
+
`pred` into a path. **All-pairs results** are the same, as dicts of dicts.
|
|
185
|
+
- **Communities** come back as a `list[set]`.
|
|
186
|
+
- **Errors.** Every exception derives from `gw.GraphError`. `NodeNotFound` and
|
|
187
|
+
`EdgeNotFound` are also `KeyError`s.
|
|
188
|
+
- **Randomized algorithms** (`louvain`, `label_propagation`, `random_walk`,
|
|
189
|
+
approximate clustering) take a `seed=` for reproducible results.
|
|
190
|
+
|
|
191
|
+
## How correctness is verified
|
|
192
|
+
|
|
193
|
+
These algorithms began as research notes. When they were first tested, several
|
|
194
|
+
turned out to be wrong in quiet ways: Johnson returned bad distances, Tarjan's
|
|
195
|
+
SCC failed on about 7% of random graphs, and Yen's algorithm skipped valid
|
|
196
|
+
paths. The [CHANGELOG](https://github.com/carjam/graphwise/blob/main/CHANGELOG.md)
|
|
197
|
+
lists them all. That experience shaped how the package is tested now:
|
|
198
|
+
|
|
199
|
+
1. **Differential testing.** [Hypothesis](https://hypothesis.readthedocs.io)
|
|
200
|
+
generates random graphs: directed and undirected, with integer or string
|
|
201
|
+
labels, self-loops, negative weights, and disconnected pieces. graphwise's
|
|
202
|
+
output is compared with networkx's on each one.
|
|
203
|
+
2. **Invariant checks**, taken from the definitions, so a bug that both
|
|
204
|
+
libraries share would still be caught. Every topological order respects
|
|
205
|
+
every edge. Every Eulerian circuit uses each edge exactly once. Every flow
|
|
206
|
+
satisfies capacity and conservation. Every reported path really has the
|
|
207
|
+
reported length.
|
|
208
|
+
3. **Regression tests** for each bug found in the original code, and for edge
|
|
209
|
+
cases like 20,000-node paths.
|
|
210
|
+
4. **100% line and branch coverage**, `mypy --strict`, and `ruff`, all enforced
|
|
211
|
+
in CI on Python 3.10–3.14. The doctests in every docstring run too, so the
|
|
212
|
+
documentation can't drift from the code.
|
|
213
|
+
|
|
214
|
+
networkx is only a test dependency. graphwise itself depends on nothing.
|
|
215
|
+
|
|
216
|
+
## graphwise or networkx?
|
|
217
|
+
|
|
218
|
+
Use **networkx** if you need its breadth (hundreds of algorithms, graph
|
|
219
|
+
generators, file formats, drawing) or its maturity. Use **graphwise** if you
|
|
220
|
+
want to understand how the algorithms work, want something small enough to
|
|
221
|
+
read in an afternoon (around 1,300 statements), or need no dependencies at all.
|
|
222
|
+
Moving between them is straightforward, because where both libraries implement
|
|
223
|
+
a measure, graphwise's results match networkx's. Closeness and harmonic
|
|
224
|
+
centrality are the one exception: graphwise measures outward distance, so pass
|
|
225
|
+
`g.reverse()` to get networkx's inward numbers.
|
|
226
|
+
|
|
227
|
+
## Development
|
|
228
|
+
|
|
229
|
+
```bash
|
|
230
|
+
git clone https://github.com/carjam/graphwise.git
|
|
231
|
+
cd graphwise
|
|
232
|
+
python -m pip install -e ".[dev]"
|
|
233
|
+
|
|
234
|
+
python -m pytest --cov # tests, doctests and examples; fails below 100% coverage
|
|
235
|
+
ruff check src tests examples
|
|
236
|
+
mypy
|
|
237
|
+
```
|
|
238
|
+
|
|
239
|
+
Set `HYPOTHESIS_PROFILE=ci` for a more thorough randomized run (400 graphs per
|
|
240
|
+
property), or `quick` for a fast one. Issues and pull requests are welcome. A
|
|
241
|
+
new algorithm needs a docstring that explains the idea and gives its
|
|
242
|
+
complexity and reference, plus a test that checks it against networkx or a
|
|
243
|
+
definition.
|
|
244
|
+
|
|
245
|
+
## License
|
|
246
|
+
|
|
247
|
+
[MIT](https://github.com/carjam/graphwise/blob/main/LICENSE): free to use, modify and ship in commercial or open-source projects.
|
|
@@ -0,0 +1,18 @@
|
|
|
1
|
+
graphwise/__init__.py,sha256=EmgoDcwFjcBVmg5bQGY8xL4qOsifYCvrYgqzoXTvnOc,3550
|
|
2
|
+
graphwise/centrality.py,sha256=-pmq6l5GX8UAeU70x2vZkoUnaNsH63Pt8bhhr7V2NsU,11772
|
|
3
|
+
graphwise/community.py,sha256=OcKafCBAjvtsP3RtsVo1UWXvwMo3OX5G4QdcWfAyo8w,16187
|
|
4
|
+
graphwise/connectivity.py,sha256=jo4R_y9KvnOxdQxlMPoMdJvg_dRsllO0rI7agK1q9OU,8685
|
|
5
|
+
graphwise/dag.py,sha256=uZ3lNfzj5NsZeHwxg4l6dT8-JV9W3p4JQdQoYk7HE5c,5597
|
|
6
|
+
graphwise/eulerian.py,sha256=6Wnc2_rsgcVtYUupPDIxjKtIjO8DI87xvqLDKSc40ms,6513
|
|
7
|
+
graphwise/exceptions.py,sha256=COu68CXRRo61Dk5pYI5Q9Dd6wc958L-tnXhvXxlebNQ,1147
|
|
8
|
+
graphwise/flow.py,sha256=Z_XlblDEpC0QmhEC6KL3AfGKNWSyRuwpA8dnuu5mZoI,5980
|
|
9
|
+
graphwise/graph.py,sha256=qGX5fR64ks9lEiFEdFuKvwndJ9Dsh0nBefpGmD1A5FY,11152
|
|
10
|
+
graphwise/py.typed,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
|
|
11
|
+
graphwise/shortest_paths.py,sha256=yW_EQuCSUtyYEwnSSy7qpPkjvfk3zNF84jitZDAjvdQ,19501
|
|
12
|
+
graphwise/spanning_trees.py,sha256=whlu1XWAKuTA5SzcltUgtNK2QES8oTefCOSEBShryhY,4549
|
|
13
|
+
graphwise/traversal.py,sha256=dynmgHaTKUIcjKO0DVtopTWgDSGKSJT0SvTLRdMVVLM,4096
|
|
14
|
+
graphwise/union_find.py,sha256=Rd5_nwxf8X9AQ6EhavT5-Fz2XUopV8kOkjBlEqz_ZgE,4221
|
|
15
|
+
graphwise-0.1.0.dist-info/METADATA,sha256=3VPFMxhfPTVSc3y1RW9zUJR0IeF4LLBXJM4rFJoWhQA,12815
|
|
16
|
+
graphwise-0.1.0.dist-info/WHEEL,sha256=2iZrJkDIkeDh0k9SikKMqFuRP-ua6mb4Ir1AsER4BEw,87
|
|
17
|
+
graphwise-0.1.0.dist-info/licenses/LICENSE,sha256=Rd2OM0lVCi6ZxUVutuluOkvAA99NfPVW57j1cAVOZF8,1074
|
|
18
|
+
graphwise-0.1.0.dist-info/RECORD,,
|
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2021-2026 James Carson
|
|
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.
|