Creating CSGraph from Edge List
- Define an edge list that represents the connectivity of the graph.
- Convert the edge list to a sparse matrix representation (e.g., COO).
- Use the csgraph_from_dense function to convert the sparse matrix to a graph representation
- The graph is directed.
Python3
import numpy as np from scipy.sparse import coo_matrix from scipy.sparse.csgraph import csgraph_from_dense # creating the edge list edgeList = coo_matrix(( 3 , 3 ), dtype = np.int8).toarray() # converting the edge list to graph graph = csgraph_from_dense(edgeList) print (graph.toarray()) |
Output:
[[0. 0. 0.]
[0. 0. 0.]
[0. 0. 0.]]
SciPy CSGraph – Compressed Sparse Graph
Graphs are powerful mathematical structures used to represent relationships between entities in various fields, including computer science, social networks, transportation systems, and more. Analyzing and computing graphs is a fundamental task in many applications, but it can be challenging, especially when dealing with large graphs with sparse connectivity. Fortunately, the scipy.sparse.csgraph subpackage in the SciPy library offers a comprehensive set of tools and algorithms specifically designed for efficient graph analysis using sparse matrix representations. Sparse matrices are matrices where the majority of elements are zero, making them ideal for representing and manipulating large graphs with sparse connectivity.
Note: Before going further strongly recommended to know how to create a sparse matrix in Python (Refer to this article How to Create a Sparse Matrix in Python).
Key Functionalities of SciPy CSGraph
The scipy.sparse.csgraph subpackage offers a wide range of functionalities and algorithms for efficient graph analysis. Let’s delve into its key features:
- Shortest Path Algorithms
- Dijkstra’s Algorithm: Find the shortest path between nodes using the shortest_path function.
- Bellman-Ford Algorithm: Compute the shortest path considering negative edge weights with bellman_ford.
- Floyd-Warshall Algorithm: Determine the shortest path between all pairs of nodes using floyd_warshall.
- Connected Components
- connected_components: Identify the connected components in a graph, providing the number of components and labels for each node.
- connected_components_dist: Compute the connected components considering edge weights.
- Minimum Spanning Tree
- minimum_spanning_tree: Calculate the minimum spanning tree of a graph, finding the subset of edges with the minimum total weight.
- minimum_spanning_tree_csr: Compute the minimum spanning tree for graphs represented as Compressed Sparse Row (CSR) matrices.
- Strongly Connected Components
- strongly_connected_components: Identify strongly connected components in a directed graph.
- strongly_connected_components_csr: Compute strongly connected components for CSR matrix representation.
Contact Us