ego.py 1.8 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465
  1. """
  2. Ego graph.
  3. """
  4. __all__ = ["ego_graph"]
  5. import networkx as nx
  6. @nx._dispatch
  7. def ego_graph(G, n, radius=1, center=True, undirected=False, distance=None):
  8. """Returns induced subgraph of neighbors centered at node n within
  9. a given radius.
  10. Parameters
  11. ----------
  12. G : graph
  13. A NetworkX Graph or DiGraph
  14. n : node
  15. A single node
  16. radius : number, optional
  17. Include all neighbors of distance<=radius from n.
  18. center : bool, optional
  19. If False, do not include center node in graph
  20. undirected : bool, optional
  21. If True use both in- and out-neighbors of directed graphs.
  22. distance : key, optional
  23. Use specified edge data key as distance. For example, setting
  24. distance='weight' will use the edge weight to measure the
  25. distance from the node n.
  26. Notes
  27. -----
  28. For directed graphs D this produces the "out" neighborhood
  29. or successors. If you want the neighborhood of predecessors
  30. first reverse the graph with D.reverse(). If you want both
  31. directions use the keyword argument undirected=True.
  32. Node, edge, and graph attributes are copied to the returned subgraph.
  33. """
  34. if undirected:
  35. if distance is not None:
  36. sp, _ = nx.single_source_dijkstra(
  37. G.to_undirected(), n, cutoff=radius, weight=distance
  38. )
  39. else:
  40. sp = dict(
  41. nx.single_source_shortest_path_length(
  42. G.to_undirected(), n, cutoff=radius
  43. )
  44. )
  45. else:
  46. if distance is not None:
  47. sp, _ = nx.single_source_dijkstra(G, n, cutoff=radius, weight=distance)
  48. else:
  49. sp = dict(nx.single_source_shortest_path_length(G, n, cutoff=radius))
  50. H = G.subgraph(sp).copy()
  51. if not center:
  52. H.remove_node(n)
  53. return H