skm_tools.neighbors

Neighbourhoods of nodes of interest.

Functions

neighborhood_nodes(g, nodes[, depth, direction])

Nodes within depth steps of nodes.

get_neighborhood(g, nodes[, depth, direction, ...])

Subgraph of g around nodes (a copy).

Module Contents

skm_tools.neighbors.neighborhood_nodes(g, nodes, depth=1, direction='both')

Nodes within depth steps of nodes.

Parameters:
  • g (networkx.Graph) – Graph to search.

  • nodes (node or iterable of nodes) – Start node(s). Nodes not in g are ignored, with a warning.

  • depth (int or None) – Number of steps to expand: a positive integer (default 1: first neighbours), or None for no limit (everything reachable).

  • direction ({"both", "out", "in"}) – For directed graphs: follow edges in both directions (default, as an undirected graph), only downstream (successors), or only upstream (predecessors). Ignored for undirected graphs.

Returns:

Node -> its distance (number of steps) from the closest start node, for the start nodes (distance 0) and every node reached.

Return type:

dict

Examples

>>> import networkx as nx
>>> g = nx.DiGraph([("A", "B"), ("B", "C"), ("D", "A")])
>>> neighborhood_nodes(g, "A", depth=2, direction="out")
{'A': 0, 'B': 1, 'C': 2}
skm_tools.neighbors.get_neighborhood(g, nodes, depth=1, direction='both', induced=True, distance_attr='distance')

Subgraph of g around nodes (a copy).

Parameters:
  • g (networkx.Graph) – Graph to search.

  • nodes (node or iterable of nodes) – Start node(s). Nodes not in g are ignored, with a warning.

  • depth (int or None) – Number of steps to expand (default 1: first neighbours; None: no limit).

  • direction ({"both", "out", "in"}) – For directed graphs: follow edges in both directions (default), only downstream, or only upstream. See neighborhood_nodes().

  • induced (bool) – If True (default), node-induced: every edge of g between the nodes found. If False, only the edges followed while expanding (each node reached through the edges from the previous step), so e.g. two second neighbours that happen to interact aren’t linked.

  • distance_attr (str or None) – Node attribute for each node’s number of steps from the closest start node (default "distance"; None: don’t add it).

Returns:

Same type as g, with node and edge attributes, and the distances (see distance_attr).

Return type:

networkx.Graph

Examples

>>> import networkx as nx
>>> g = nx.DiGraph([("A", "B"), ("B", "C"), ("C", "D")])
>>> sorted(get_neighborhood(g, "B").nodes())
['A', 'B', 'C']