skm_tools.paths

Shortest paths between nodes of interest.

Attributes

logger

Functions

get_paths(g, sources, targets[, directed, ...])

Shortest paths from each source to each target.

path_edges(g, paths)

The edges of g along each path.

path_subgraph(g, paths)

Edge-induced subgraph of g made of the edges along paths (a copy).

Module Contents

skm_tools.paths.logger
skm_tools.paths.get_paths(g, sources, targets, directed=True, all_shortest=True, shortest_overall=False, max_paths=None)

Shortest paths from each source to each target.

Parameters:
  • g (networkx.Graph) – Graph to search, any networkx graph type. Edge weights are not used: a path’s length is its number of edges.

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

  • targets (node or iterable of nodes) – End node(s) of the paths. Nodes not in g are skipped, with a warning.

  • directed (bool) – Follow edge direction (default). If False, search the undirected view of g. Ignored if g is undirected.

  • all_shortest (bool) – Return all shortest paths between each source and target (default), or only one of them.

  • shortest_overall (bool) – If True, for each target keep only the paths that are as short as the shortest path from any of the sources (so a target reached in 2 steps from one source and 4 from another only keeps the 2-step paths). Default False: keep the shortest paths from every source.

  • max_paths (int, optional) – Stop after this many paths, with a warning (default: no limit). The number of shortest paths can grow very fast in dense networks.

Returns:

Paths as lists of nodes, from source to target, by target and then by source (in the given order). Source/target pairs without a path are skipped. A node that is both a source and a target gives no path.

Return type:

list of list

Examples

>>> import networkx as nx
>>> g = nx.DiGraph([("A", "B"), ("B", "C"), ("A", "D"), ("D", "C")])
>>> sorted(get_paths(g, "A", "C"))
[['A', 'B', 'C'], ['A', 'D', 'C']]
skm_tools.paths.path_edges(g, paths)

The edges of g along each path.

Parameters:
Returns:

Unique edges, in path order: (u, v), or (u, v, key) for every parallel edge if g is a multigraph. For an undirected search on a directed graph (get_paths(..., directed=False)), a step u-v gives whichever of (u, v) and (v, u) exist in g.

Return type:

list of tuple

Examples

>>> import networkx as nx
>>> g = nx.DiGraph([("A", "B"), ("B", "C")])
>>> path_edges(g, [["A", "B", "C"]])
[('A', 'B'), ('B', 'C')]
skm_tools.paths.path_subgraph(g, paths)

Edge-induced subgraph of g made of the edges along paths (a copy).

Parameters:
Returns:

Same type as g, with only the nodes and edges on the paths (and their attributes).

Return type:

networkx.Graph