pysdic.fem.bfs_distance#
- bfs_distance(graph, start, *, max_distance=None)[source]#
Compute the shortest path distances from a starting node to all the nodes of an adjacency graph.
Note
The search is performed with
scipy.sparse.csgraph.dijkstraon the unweighted graph, which is equivalent to a breadth-first search (BFS).Warning
No tests are performed to check if the input graph is valid (e.g., if the graph is not symmetric, …). The behavior of the function is undefined if the input graph is not valid.
- Parameters:
graph (Union[ArrayLike, scipy.sparse.spmatrix]) – The adjacency graph as a square matrix of shape \((N, N)\) (sparse or dense), where a non-zero entry at \((i, j)\) means that nodes \(i\) and \(j\) are neighbors. See
pysdic.fem.assemble_vertices_adjacency_graph()andpysdic.fem.assemble_elements_adjacency_graph().start (Integral) – The index of the starting node.
max_distance (Optional[Integral], optional (default:
None)) – The maximum distance of the search. If None, all the reachable nodes are considered. Otherwise, the nodes farther thanmax_distanceget a distance of -1.
- Returns:
distances – An integer array of shape \((N,)\) containing the shortest path distances from
startto all the nodes of the graph (-1 for unreachable nodes).- Return type:
Notes
The distance from node \(A\) to node \(T\) is defined as follows:
\(\text{dist}(A, T) = 0\) if node \(T\) is the same as node \(A\).
\(\text{dist}(A, T) = 1\) if node \(T\) is a neighbor of node \(A\).
\(\text{dist}(A, T) = d \geq 1\) if the shortest path from node \(A\) to node \(T\) has length \(d\).
\(\text{dist}(A, T) = -1\) if node \(T\) is not reachable from node \(A\), or not reachable within the specified
max_distance.
See also
pysdic.fem.bfs_neighborhoodNeighborhood of a single node within a given distance.
pysdic.fem.compute_distance_matrixDistances between all the pairs of nodes of a graph.
Examples
Create a simple disconnected graph of 7 nodes and compute the shortest path distances from node 0 to all the other nodes.
Disconnected graph with 7 nodes for BFS example. Distance from node 0 to node 4 is 3 (0 -> 2 -> 3 -> 4).#
1import numpy 2from pysdic.fem import bfs_distance 3 4edges = numpy.array([[0, 1], [0, 2], [1, 2], [2, 3], [3, 4], [5, 6]]) 5graph = numpy.zeros((7, 7), dtype=bool) 6graph[edges[:, 0], edges[:, 1]] = True 7graph[edges[:, 1], edges[:, 0]] = True 8 9distances = bfs_distance(graph, start=0) 10print(distances)
[ 0 1 1 2 3 -1 -1]