On Thu, Dec 13, 2012 at 9:54 PM, <
se...@bromberger.com> wrote:
> Consider the following graph:
>>>> g = nx.Graph()
>>>> g.add_edges_from(((1,2),(2,3),(2,4),(3,5),(4,5),(4,6),(5,6)))
>
> "Graph to depth 3 from node 1" should include the following paths:
>
> depth 1: 1-2
> depth 2: 1-2-3, 1-2-4
> depth 3: 1-2-3-5, 1-2-4-5
>
> I can't get there from single_source_shortest_path, since it doesn't provide
> multiple equal-length paths for loops:
>>>> nx.single_source_shortest_path(g,1,cutoff=3)
> {1: [1],
> 2: [1, 2],
> 3: [1, 2, 3],
> 4: [1, 2, 4],
> 5: [1, 2, 3, 5],
> 6: [1, 2, 4, 6]}
>
> (note: I need 5: [1,2,4,5] in there as well)
>
>>>>nx.single_source_shortest_path_length(g,1,cutoff=3)
> {1: 0, 2: 1, 3: 2, 4: 2, 5: 3, 6: 3}
>
> I haven't yet found an elegant way to get a subgraph of a graph from an
> arbitrary node out to a given depth. I've done it with the following code,
> but I'm hoping I've overlooked something native to networkx:
>
> def graphtodepth(g,root,depth):
> neighbor_set = set()
> traversed = set()
> rootset = set([root])
> while (depth >= 0) and (rootset):
> newrootset = set()
> for d in rootset:
> traversed.add(d)
> neighbor_set.add(d)
> neighbors = g.neighbors(d)
> newrootset = newrootset.union(set(neighbors)) - traversed
> neighbor_set = neighbor_set.union(neighbors)
> rootset = newrootset
> depth -= 1
> return g.subgraph(list(neighbor_set))
>
> Is there a better/more elegant way of doing this?
Maybe you can use nx.ego_graph() with radius=3?
In [1]: import networkx as nx
In [2]: >>> g = nx.Graph()
In [3]: >>> g.add_edges_from(((1,2),(2,3),(2,4),(3,5),(4,5),(4,6),(5,6)))
In [4]: nx.ego_graph(g,1,radius=3).edges()
Out[4]: [(1, 2), (2, 3), (2, 4), (3, 5), (4, 5), (4, 6), (5, 6)]
In [5]: nx.ego_graph(g,1,radius=2).edges()
Out[5]: [(1, 2), (2, 3), (2, 4)]
Aric