Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to compute 'nearby' nodes with networkx

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.

like image 784
tehwalrus Avatar asked Jun 25 '13 15:06

tehwalrus


People also ask

How do I find my neighbors nodes?

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.

How do I find the number of nodes in NetworkX?

Returns the number of nodes in the graph.

How do you get all nodes on a graph in NetworkX?

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.

What is Nbunch in NetworkX?

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.


1 Answers

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.

like image 154
valrus Avatar answered Sep 21 '22 20:09

valrus