Efficient directed graph algorithms for network optimization in Python
digraphx is a Python library that provides high-performance implementations of directed graph algorithms, optimized for large-scale network optimization problems. It extends NetworkX with specialized data structures and algorithms for negative cycle detection, cycle ratio optimization, and parametric network analysis.
Note that digraphx does not directly handle multi-edges (same as networkx)
TinyDiGraph with memory-efficient MapAdapter backendUse digraphx when:
Use standard NetworkX when:
pip install digraphx
git clone https://github.com/luk036/digraphx.git
cd digraphx
pip install -e .
from digraphx import NegCycleFinder
# Create a directed graph with a negative cycle
digraph = {
'a': {'b': 7, 'c': 5},
'b': {'a': 0, 'c': 3},
'c': {'a': 2, 'b': 1}
}
# Initialize distances
dist = {node: 0 for node in digraph}
# Find negative cycles using Howard's algorithm
finder = NegCycleFinder(digraph)
for cycle in finder.howard(dist, lambda edge: edge):
print(f"Found negative cycle: {cycle}")
from digraphx import MinCycleRatioSolver
from digraphx import DiGraphAdapter
from fractions import Fraction
# Create a graph with cost and time attributes
graph = DiGraphAdapter()
graph.add_edge('a', 'b', cost=5, time=1)
graph.add_edge('b', 'c', cost=3, time=1)
graph.add_edge('c', 'a', cost=-2, time=1)
# Solve for minimum cycle ratio
solver = MinCycleRatioSolver(graph)
dist = {node: Fraction(0) for node in graph}
ratio, cycle = solver.run(dist, Fraction(10))
print(f"Minimum cycle ratio: {ratio}")
from digraphx import TinyDiGraph
# Create a graph optimized for 1000 nodes
graph = TinyDiGraph()
graph.init_nodes(1000)
# Add edges efficiently
for i in range(1000):
for j in range(i+1, min(i+10, 1000)):
graph.add_edge(i, j, weight=i+j)
# Access graph properties
print(f"Nodes: {graph.number_of_nodes()}")
print(f"Edges: {graph.number_of_edges()}")
Full API documentation is available at https://digraphx.readthedocs.io/
Run’s test suite:
# Run all tests
pytest
# Run specific test file
pytest tests/test_tiny_digraph.py
# Run with coverage
pytest --cov=digraphx --cov-report=html
# Install development dependencies
pip install -e ".[testing]"
# Run linting
pre-commit run --all-files
# Format code
black src/digraphx tests
isort src/digraphx tests
# Build package
tox -e build
Contributions are welcome! Please ensure:
This project is licensed under the MIT License - see the LICENSE.txt file for details.
Built on top of NetworkX Uses PyScaffold for project structure
If you use digraphx in your research, please cite:
@software{digraphx,
title = {digraphx: Directed Graph X in Python},
author = {Luk, Wai-Shing},
url = {https://github.com/luk036/digraphx},
year = {2026}
}