What I'm looking for here may well be a built-in function in networkx
, and have a mathematical name - if so, I'd like to know what it is! it is very difficult to Google for, it seems.
Given a graph G
and a starting node i
, I'd like to find the subgraph of all the nodes "within P
edges" from i
- that is, those that are connected to i
by a path of less than P
edges.
My draft implementation for this is:
import networkx as nx
N = 30
G = nx.Graph()
# populate the graph...
G.add_cycle(range(N))
# the starting node:
i = 15
# the 'distance' limit:
P = 4
neighborhood = [i]
new_neighbors = [i]
depth = 0
while depth < P:
new_neighbors = list(set(sum([
[k for k in G[j].keys() if k not in neighborhood]
for j in new_neighbors], [])))
neighborhood.extend(new_neighbors)
depth += 1
Gneighbors = G.subgraph(neighborhood)
This code works, by the way, so I don't need help with the implementation. I would simply like to know if this has a name, and whether it is provided by the networkx
library.
It is very useful when your code is crashing and you want to see why - you can render just the "locality/region" of the graph near the problem node.
Use the len() and list() functions together with the . neighbors() method to calculate the total number of neighbors that node n in graph G has. If the number of neighbors of node n is equal to m , add n to the set nodes using the . add() method.
Returns the number of nodes in the graph.
We can use shortest_path() to find all of the nodes reachable from a given node. Alternatively, there is also descendants() that returns all nodes reachable from a given node (though the document specified input G as directed acyclic graph.
nbunch. An nbunch is a single node, container of nodes or None (representing all nodes). It can be a list, set, graph, etc.. To filter an nbunch so that only nodes actually in G appear, use G.
Two years late, but I was looking for this same thing and found a built-in that I think will get the subgraph you want: ego_graph
. The function signature and documentation:
ego_graph(G, n, radius=1, center=True, undirected=False, distance=None)
Returns induced subgraph of neighbors centered at node n within a given radius.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With