⚡️ Speed up method DiGraph.subgraph by 54%#109
Open
codeflash-ai[bot] wants to merge 1 commit intomainfrom
Open
⚡️ Speed up method DiGraph.subgraph by 54%#109codeflash-ai[bot] wants to merge 1 commit intomainfrom
DiGraph.subgraph by 54%#109codeflash-ai[bot] wants to merge 1 commit intomainfrom
Conversation
The optimized code achieves a **54% speedup** through two key optimizations: ## 1. Avoiding Unnecessary Copy in `__init__` (`copy=False`) The original code calls `sparse.csr_matrix(adj_matrix, dtype=dtype)`, which by default creates a copy of the input data. The optimization adds `copy=False` to avoid this unnecessary allocation when `adj_matrix` is already a compatible sparse matrix. This reduces memory allocation overhead during graph construction. ## 2. Replacing `np.ix_()` with Direct Slicing in `subgraph` The original uses `self.csgraph[np.ix_(nodes, nodes)]` to extract a subgraph, which creates intermediate index arrays for fancy indexing. The optimized version: - Converts `nodes` to a numpy array once: `nodes = np.asarray(nodes)` - Uses chained slicing: `self.csgraph[nodes][:, nodes]` This approach is faster because: - **`np.ix_()`** constructs broadcasting-compatible index arrays, adding overhead - **Direct slicing** `[nodes][:, nodes]` performs row selection then column selection sequentially, which is more efficient for CSR matrices (row-major format) - For sparse matrices, row slicing is particularly fast in CSR format ## Impact on Test Cases The optimization excels with: - **Large subgraphs**: 358-416% speedup for 250+ node extractions (`test_large_scale_subgraph_preserves_sparsity_and_counts`, `test_subgraph_performance_large_extraction`) - **Sparse graphs**: 66-127% speedup on chain-structured graphs where CSR format shines - **Random node selections**: 224% speedup on random graphs due to reduced indexing overhead - **Small subgraphs**: 10-16% consistent improvement across basic cases The optimizations are particularly effective when `subgraph()` is called repeatedly or on large graphs, making them valuable for algorithms that perform frequent graph decompositions or analyses on substructures.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
📄 54% (0.54x) speedup for
DiGraph.subgraphinquantecon/_graph_tools.py⏱️ Runtime :
15.4 milliseconds→10.0 milliseconds(best of89runs)📝 Explanation and details
The optimized code achieves a 54% speedup through two key optimizations:
1. Avoiding Unnecessary Copy in
__init__(copy=False)The original code calls
sparse.csr_matrix(adj_matrix, dtype=dtype), which by default creates a copy of the input data. The optimization addscopy=Falseto avoid this unnecessary allocation whenadj_matrixis already a compatible sparse matrix. This reduces memory allocation overhead during graph construction.2. Replacing
np.ix_()with Direct Slicing insubgraphThe original uses
self.csgraph[np.ix_(nodes, nodes)]to extract a subgraph, which creates intermediate index arrays for fancy indexing. The optimized version:nodesto a numpy array once:nodes = np.asarray(nodes)self.csgraph[nodes][:, nodes]This approach is faster because:
np.ix_()constructs broadcasting-compatible index arrays, adding overhead[nodes][:, nodes]performs row selection then column selection sequentially, which is more efficient for CSR matrices (row-major format)Impact on Test Cases
The optimization excels with:
test_large_scale_subgraph_preserves_sparsity_and_counts,test_subgraph_performance_large_extraction)The optimizations are particularly effective when
subgraph()is called repeatedly or on large graphs, making them valuable for algorithms that perform frequent graph decompositions or analyses on substructures.✅ Correctness verification report:
⚙️ Click to see Existing Unit Tests
test_graph_tools.py::test_node_labels_subgraphtest_graph_tools.py::test_subgraphtest_graph_tools.py::test_subgraph_weighted🌀 Click to see Generated Regression Tests
To edit these changes
git checkout codeflash/optimize-DiGraph.subgraph-mkp3k41xand push.