graphwise 0.1.0__tar.gz
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-0.1.0/.gitignore +129 -0
- graphwise-0.1.0/CHANGELOG.md +46 -0
- graphwise-0.1.0/LICENSE +21 -0
- graphwise-0.1.0/PKG-INFO +247 -0
- graphwise-0.1.0/README.md +199 -0
- graphwise-0.1.0/examples/currency_arbitrage.py +32 -0
- graphwise-0.1.0/examples/dependency_resolution.py +33 -0
- graphwise-0.1.0/examples/fraud_rings.py +49 -0
- graphwise-0.1.0/examples/network_resilience.py +32 -0
- graphwise-0.1.0/examples/route_planning.py +43 -0
- graphwise-0.1.0/pyproject.toml +89 -0
- graphwise-0.1.0/src/graphwise/__init__.py +151 -0
- graphwise-0.1.0/src/graphwise/centrality.py +314 -0
- graphwise-0.1.0/src/graphwise/community.py +422 -0
- graphwise-0.1.0/src/graphwise/connectivity.py +245 -0
- graphwise-0.1.0/src/graphwise/dag.py +160 -0
- graphwise-0.1.0/src/graphwise/eulerian.py +170 -0
- graphwise-0.1.0/src/graphwise/exceptions.py +47 -0
- graphwise-0.1.0/src/graphwise/flow.py +155 -0
- graphwise-0.1.0/src/graphwise/graph.py +321 -0
- graphwise-0.1.0/src/graphwise/py.typed +0 -0
- graphwise-0.1.0/src/graphwise/shortest_paths.py +502 -0
- graphwise-0.1.0/src/graphwise/spanning_trees.py +122 -0
- graphwise-0.1.0/src/graphwise/traversal.py +129 -0
- graphwise-0.1.0/src/graphwise/union_find.py +127 -0
- graphwise-0.1.0/tests/helpers.py +80 -0
- graphwise-0.1.0/tests/test_centrality.py +103 -0
- graphwise-0.1.0/tests/test_community.py +178 -0
- graphwise-0.1.0/tests/test_connectivity.py +85 -0
- graphwise-0.1.0/tests/test_dag.py +80 -0
- graphwise-0.1.0/tests/test_eulerian.py +104 -0
- graphwise-0.1.0/tests/test_examples.py +28 -0
- graphwise-0.1.0/tests/test_flow.py +82 -0
- graphwise-0.1.0/tests/test_graph.py +170 -0
- graphwise-0.1.0/tests/test_shortest_paths.py +285 -0
- graphwise-0.1.0/tests/test_spanning_trees.py +58 -0
- graphwise-0.1.0/tests/test_traversal.py +81 -0
- graphwise-0.1.0/tests/test_union_find.py +78 -0
|
@@ -0,0 +1,129 @@
|
|
|
1
|
+
# Byte-compiled / optimized / DLL files
|
|
2
|
+
__pycache__/
|
|
3
|
+
*.py[cod]
|
|
4
|
+
*$py.class
|
|
5
|
+
|
|
6
|
+
# C extensions
|
|
7
|
+
*.so
|
|
8
|
+
|
|
9
|
+
# Distribution / packaging
|
|
10
|
+
.Python
|
|
11
|
+
build/
|
|
12
|
+
develop-eggs/
|
|
13
|
+
dist/
|
|
14
|
+
downloads/
|
|
15
|
+
eggs/
|
|
16
|
+
.eggs/
|
|
17
|
+
lib/
|
|
18
|
+
lib64/
|
|
19
|
+
parts/
|
|
20
|
+
sdist/
|
|
21
|
+
var/
|
|
22
|
+
wheels/
|
|
23
|
+
pip-wheel-metadata/
|
|
24
|
+
share/python-wheels/
|
|
25
|
+
*.egg-info/
|
|
26
|
+
.installed.cfg
|
|
27
|
+
*.egg
|
|
28
|
+
MANIFEST
|
|
29
|
+
|
|
30
|
+
# PyInstaller
|
|
31
|
+
# Usually these files are written by a python script from a template
|
|
32
|
+
# before PyInstaller builds the exe, so as to inject date/other infos into it.
|
|
33
|
+
*.manifest
|
|
34
|
+
*.spec
|
|
35
|
+
|
|
36
|
+
# Installer logs
|
|
37
|
+
pip-log.txt
|
|
38
|
+
pip-delete-this-directory.txt
|
|
39
|
+
|
|
40
|
+
# Unit test / coverage reports
|
|
41
|
+
htmlcov/
|
|
42
|
+
.tox/
|
|
43
|
+
.nox/
|
|
44
|
+
.coverage
|
|
45
|
+
.coverage.*
|
|
46
|
+
.cache
|
|
47
|
+
nosetests.xml
|
|
48
|
+
coverage.xml
|
|
49
|
+
*.cover
|
|
50
|
+
*.py,cover
|
|
51
|
+
.hypothesis/
|
|
52
|
+
.pytest_cache/
|
|
53
|
+
|
|
54
|
+
# Translations
|
|
55
|
+
*.mo
|
|
56
|
+
*.pot
|
|
57
|
+
|
|
58
|
+
# Django stuff:
|
|
59
|
+
*.log
|
|
60
|
+
local_settings.py
|
|
61
|
+
db.sqlite3
|
|
62
|
+
db.sqlite3-journal
|
|
63
|
+
|
|
64
|
+
# Flask stuff:
|
|
65
|
+
instance/
|
|
66
|
+
.webassets-cache
|
|
67
|
+
|
|
68
|
+
# Scrapy stuff:
|
|
69
|
+
.scrapy
|
|
70
|
+
|
|
71
|
+
# Sphinx documentation
|
|
72
|
+
docs/_build/
|
|
73
|
+
|
|
74
|
+
# PyBuilder
|
|
75
|
+
target/
|
|
76
|
+
|
|
77
|
+
# Jupyter Notebook
|
|
78
|
+
.ipynb_checkpoints
|
|
79
|
+
|
|
80
|
+
# IPython
|
|
81
|
+
profile_default/
|
|
82
|
+
ipython_config.py
|
|
83
|
+
|
|
84
|
+
# pyenv
|
|
85
|
+
.python-version
|
|
86
|
+
|
|
87
|
+
# pipenv
|
|
88
|
+
# According to pypa/pipenv#598, it is recommended to include Pipfile.lock in version control.
|
|
89
|
+
# However, in case of collaboration, if having platform-specific dependencies or dependencies
|
|
90
|
+
# having no cross-platform support, pipenv may install dependencies that don't work, or not
|
|
91
|
+
# install all needed dependencies.
|
|
92
|
+
#Pipfile.lock
|
|
93
|
+
|
|
94
|
+
# PEP 582; used by e.g. github.com/David-OConnor/pyflow
|
|
95
|
+
__pypackages__/
|
|
96
|
+
|
|
97
|
+
# Celery stuff
|
|
98
|
+
celerybeat-schedule
|
|
99
|
+
celerybeat.pid
|
|
100
|
+
|
|
101
|
+
# SageMath parsed files
|
|
102
|
+
*.sage.py
|
|
103
|
+
|
|
104
|
+
# Environments
|
|
105
|
+
.env
|
|
106
|
+
.venv
|
|
107
|
+
env/
|
|
108
|
+
venv/
|
|
109
|
+
ENV/
|
|
110
|
+
env.bak/
|
|
111
|
+
venv.bak/
|
|
112
|
+
|
|
113
|
+
# Spyder project settings
|
|
114
|
+
.spyderproject
|
|
115
|
+
.spyproject
|
|
116
|
+
|
|
117
|
+
# Rope project settings
|
|
118
|
+
.ropeproject
|
|
119
|
+
|
|
120
|
+
# mkdocs documentation
|
|
121
|
+
/site
|
|
122
|
+
|
|
123
|
+
# mypy
|
|
124
|
+
.mypy_cache/
|
|
125
|
+
.dmypy.json
|
|
126
|
+
dmypy.json
|
|
127
|
+
|
|
128
|
+
# Pyre type checker
|
|
129
|
+
.pyre/
|
|
@@ -0,0 +1,46 @@
|
|
|
1
|
+
# Changelog
|
|
2
|
+
|
|
3
|
+
All notable changes to this project are documented here. The format follows
|
|
4
|
+
[Keep a Changelog](https://keepachangelog.com/en/1.1.0/), and the project uses
|
|
5
|
+
[Semantic Versioning](https://semver.org/).
|
|
6
|
+
|
|
7
|
+
## [0.1.0] - unreleased
|
|
8
|
+
|
|
9
|
+
The first packaged release. It replaces the original research scripts
|
|
10
|
+
(`DirectedGraph.py`, `UndirectedGraph.py`, `unionFind.py`) with the
|
|
11
|
+
importable `graphwise` package.
|
|
12
|
+
|
|
13
|
+
### Changed
|
|
14
|
+
- Relicensed from GPL-3.0 to MIT, so the library can be used in any project.
|
|
15
|
+
|
|
16
|
+
### Added
|
|
17
|
+
- `Graph` and `DiGraph`: weighted adjacency-map graphs with any hashable node type.
|
|
18
|
+
- Traversal: `bfs`, `bfs_layers`, `dfs`, `random_walk`.
|
|
19
|
+
- DAGs: `topological_sort` (Kahn and DFS), `topological_generations`, `is_dag`, `find_cycle`.
|
|
20
|
+
- Shortest paths: `dijkstra`, `astar`, `bellman_ford`, `floyd_warshall`, `johnson`,
|
|
21
|
+
`yen_k_shortest_paths`, `shortest_path`.
|
|
22
|
+
- Spanning trees: `kruskal_mst`, `prim_mst`.
|
|
23
|
+
- Connectivity: `connected_components`, `strongly_connected_components` (Tarjan),
|
|
24
|
+
`condensation`, `bridges`, `articulation_points`.
|
|
25
|
+
- Eulerian circuits and paths (Hierholzer).
|
|
26
|
+
- Centrality: degree, closeness, harmonic, betweenness (Brandes), PageRank (including personalized).
|
|
27
|
+
- Community: clustering coefficients, modularity, label propagation (plain and
|
|
28
|
+
semi-supervised), Louvain.
|
|
29
|
+
- Flow: `max_flow` and `minimum_cut` (Dinic).
|
|
30
|
+
- A test suite that checks every algorithm against networkx on randomly
|
|
31
|
+
generated graphs with Hypothesis. It enforces 100% branch coverage.
|
|
32
|
+
|
|
33
|
+
### Fixed (compared with the original scripts)
|
|
34
|
+
- Johnson APSP returned wrong distances, collided with a real node labelled `0`,
|
|
35
|
+
skipped reweighting zero-weight edges, and returned after its first loop iteration.
|
|
36
|
+
- Tarjan SCC used DFS depth instead of discovery time, and got about 7% of
|
|
37
|
+
random graphs wrong.
|
|
38
|
+
- Yen's k-shortest paths tried to delete every edge in the graph (while iterating over it), not just the
|
|
39
|
+
edges at the root-path nodes, so it missed valid paths.
|
|
40
|
+
- Prim's MST (undirected) could overwrite a vertex's parent after the vertex
|
|
41
|
+
had joined the tree.
|
|
42
|
+
- Kruskal raised `IndexError` on disconnected graphs.
|
|
43
|
+
- Bridges and articulation points only searched the component that contains node `0`.
|
|
44
|
+
- Dinic and the Tarjan algorithms only accepted integer nodes `0..n-1`.
|
|
45
|
+
- Louvain was a stub, and PageRank depended on networkx and raised `NameError` on bad input.
|
|
46
|
+
- Recursive DFS hit Python's recursion limit on graphs with long paths.
|
graphwise-0.1.0/LICENSE
ADDED
|
@@ -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.
|
graphwise-0.1.0/PKG-INFO
ADDED
|
@@ -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,199 @@
|
|
|
1
|
+
# graphwise
|
|
2
|
+
|
|
3
|
+
**Canonical graph algorithms in readable, tested, dependency-free Python, for studying them and for using them.**
|
|
4
|
+
|
|
5
|
+
[](https://github.com/carjam/graphwise/actions/workflows/ci.yml)
|
|
6
|
+
[](https://github.com/carjam/graphwise/blob/main/LICENSE)
|
|
7
|
+

|
|
8
|
+

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