pysdic.fem.compute_neighborhood#

compute_neighborhood(graph, *, max_distance=1, self_neighborhood=True)[source]#

Compute the neighborhood of each node of an adjacency graph, i.e. the nodes within a given distance from each node.

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.

  • max_distance (Integral, optional (default: 1)) – The maximum distance of the nodes in the neighborhood. With 1, only the directly adjacent nodes are included.

  • self_neighborhood (bool, optional (default: True)) – If True, the neighborhood of each node includes the node itself.

Returns:

neighborhood – A symmetric boolean sparse matrix of shape \((N, N)\), where neighborhood[i, j] is True if node \(j\) is in the neighborhood of node \(i\). The neighborhood of node \(i\) is neighborhood[i].indices (sorted).

Return type:

scipy.sparse.csr_matrix

Notes

The neighborhood of node \(i\) contains all the nodes \(j\) such that \(\text{dist}(i, j) \leq d\) with \(d\) the max_distance. It is computed with boolean sparse products as the reachability matrix \((I + A)^{d}\), where \(A\) is the adjacency matrix of the graph.

  • For \(d = 0\), the neighborhood of each node is the node itself (or empty if self_neighborhood is False).

  • For \(d = 1\), the neighborhood is \(I + A\) (or \(A\) if self_neighborhood is False).

See also

pysdic.fem.bfs_neighborhood

Neighborhood of a single node.

pysdic.fem.compute_vertices_neighborhood

Neighborhood of each vertex of a mesh.

pysdic.fem.compute_elements_neighborhood

Neighborhood of each element of a mesh.

Examples

Create a simple disconnected graph of 7 nodes and compute the neighborhood of each node within a distance of 2.

../../_images/graph_bfs.png

Disconnected graph with 7 nodes for BFS example. Neighborhood of node 0 with max_distance=2 includes nodes 0, 1, 2 and 3.#

 1import numpy
 2from pysdic.fem import compute_neighborhood
 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
 9neighborhood = compute_neighborhood(graph, max_distance=2)
10
11print(f"neighborhood (shape={neighborhood.shape})")
12print(f"neighborhood of node 0: {neighborhood[0].indices}")
neighborhood (shape=(7, 7))
neighborhood of node 0: [0 1 2 3]