Algorithms#

Every algorithm is also available as ag.alg.<name>.

Traversal#

bfs_order

Nodes reachable from source in breadth-first order (source first).

bfs_edges

Edges of the breadth-first search tree rooted at source, in discovery order.

bfs_layers

Nodes grouped by hop distance from sources.

bfs_tree

Breadth-first search tree rooted at source, as a DiGraph.

dfs_preorder

Nodes in depth-first preorder (a node before its descendants).

dfs_postorder

Nodes in depth-first postorder (a node after all its descendants).

dfs_edges

Tree edges (parent, child) of the depth-first search, in discovery order.

dfs_tree

Depth-first search tree (forest when source=None) as a DiGraph.

descendants

Every node reachable from node, excluding node itself.

ancestors

Every node from which node is reachable, excluding node itself.

Shortest paths#

shortest_path

A shortest path from source to target, or to every reachable node.

shortest_path_length

Length of a shortest path (hops, or total weight); same arguments as shortest_path().

dijkstra

Dijkstra's algorithm: distances and shortest-path predecessors from source.

bellman_ford

Bellman–Ford shortest paths from source; negative weights allowed.

astar_path

A* search for a shortest path from source to target.

all_shortest_paths

Every shortest path from source to target (a lazy iterator).

all_pairs_shortest_path_length

Distances between every pair of mutually reachable nodes, as {u: NodeMap{v: d}}.

floyd_warshall

All-pairs distances by Floyd–Warshall, vectorised over numpy.

has_path

True when target is reachable from source (every node reaches itself).

all_simple_paths

Every simple path (no repeated node) from source to target, lazily.

k_shortest_paths

The k shortest loopless paths from source to target (Yen's algorithm).

Connectivity#

connected_components

Connected components of an undirected graph, largest first.

number_connected_components

How many connected components an undirected graph has (0 for the empty graph).

is_connected

True when an undirected graph has exactly one connected component.

node_connected_component

The set of nodes in node's connected component (including node).

strongly_connected_components

Strongly connected components of a directed graph, largest first.

weakly_connected_components

Components of a directed graph when arc directions are ignored, largest first.

number_strongly_connected_components

How many strongly connected components a directed graph has.

number_weakly_connected_components

How many weakly connected components a directed graph has.

is_strongly_connected

True when every node reaches every other node (False for the empty graph).

is_weakly_connected

True when the graph is connected once arc directions are ignored (False if empty).

condensation

The DAG obtained by contracting each strongly connected component to one node.

articulation_points

Cut vertices of an undirected graph (removal disconnects their component), in graph order.

bridges

Bridges of an undirected graph (edges whose removal disconnects), in edge order.

biconnected_components

Maximal biconnected subgraphs of an undirected graph, as node sets, largest first.

is_biconnected

True when the graph is connected and has no articulation point.

DAGs and cycles#

is_dag

True for a directed graph without directed cycles (undirected graphs: False).

topological_sort

Nodes ordered so that every arc points forward.

all_topological_sorts

Every topological order of g, generated lazily by backtracking.

find_cycle

Some cycle of g as a closed node list [a, b, …, a], or None.

simple_cycles

Every simple cycle of g, each once, as a closed node list [a, …, a].

dag_longest_path

A heaviest path of a DAG, as a node list.

dag_longest_path_length

Length of dag_longest_path() (number of edges when weight is None; 0 if empty).

dag_levels

Longest-path level of every node: sources are 0 and every arc climbs at least one level.

CriticalPath

Result of critical_path() (activity-on-node CPM).

critical_path

Critical-path method (CPM) with activities on the nodes.

transitive_closure

Graph with an arc u → v for every directed path u ⇝ v.

transitive_reduction

The smallest DAG with the same reachability as the acyclic graph g.

lowest_common_ancestors

All lowest common ancestors of a and b in a DAG.

dag_width

Size of a largest antichain (set of pairwise unreachable nodes) of a DAG.

maximum_antichain

A largest set of pairwise incomparable nodes of a DAG (its size is dag_width()).

minimum_chain_partition

Fewest chains covering every node of a DAG exactly once (Dilworth decomposition).

Centrality#

degree_centrality

Degree divided by n - 1 (a self-loop adds 2, as in Graph.degree()).

in_degree_centrality

In-degree divided by n - 1 (directed graphs only).

out_degree_centrality

Out-degree divided by n - 1 (directed graphs only).

closeness_centrality

Closeness (r - 1) / Σ d(u, v) over the r nodes that reach v.

harmonic_centrality

Harmonic centrality Σ_{u ≠ v} 1 / d(u, v) (unnormalised, like networkx).

betweenness_centrality

Shortest-path betweenness (Brandes' algorithm, O(n·m); O(n·m + n² log n) weighted).

edge_betweenness_centrality

Betweenness of every edge: the share of shortest paths running through it.

eigenvector_centrality

Eigenvector centrality (left Perron vector, unit Euclidean norm).

katz_centrality

Katz centrality x = α Aᵀx + β by fixed-point iteration (as networkx).

pagerank

PageRank by vectorised power iteration (O(m) per step).

hits

HITS hub and authority scores (hubs, authorities).

centralities

Several centralities in one call: {kind: NodeMap}.

Structure#

density

Edges present over edges possible: 2m / n(n-1) (undirected) or m / n(n-1).

degree_histogram

hist[k] = number of nodes of degree k, for k = 0 … max degree.

degree_distribution

{degree: number of nodes} for the degrees that occur, ascending.

average_degree

Mean of Graph.degree() (2m / n; in + out for directed graphs), 0 for the null graph.

reciprocity

Share of arcs whose reverse arc also exists (directed graphs; self-loops never count).

triangles

Number of triangles through each node (undirected graphs; self-loops ignored).

clustering

Local clustering coefficient of every node.

average_clustering

Mean of clustering(); with count_zeros=False zero-valued nodes are skipped.

transitivity

Global clustering 3 × triangles / connected triples (undirected; self-loops ignored).

square_clustering

Squares clustering C4(v) (Lind et al.): share of possible squares through v.

degree_assortativity

Degree assortativity: Pearson correlation of the degrees at either end of each edge.

attribute_assortativity

Newman's assortativity for a categorical node attribute (missing values form a category).

numeric_assortativity

Pearson correlation of a numeric node attribute across edges (NaN when undefined).

eccentricity

Greatest distance from each node (outgoing distances for directed graphs).

diameter

Largest eccentricity (NotConnected if the graph is not (strongly) connected).

radius

Smallest eccentricity (NotConnected if the graph is not (strongly) connected).

center

Nodes whose eccentricity equals the radius, in graph order.

periphery

Nodes whose eccentricity equals the diameter, in graph order.

average_shortest_path_length

Mean distance over all ordered pairs of distinct nodes (0.0 for a single node).

wiener_index

Sum of distances over all (unordered, or ordered if directed) node pairs.

global_efficiency

Average inverse distance Σ 1/d(u, v) / n(n-1) (undirected; 0 for n < 2).

local_efficiency

Mean over nodes of the global efficiency of the subgraph induced by their neighbors.

core_number

k-core number of every node (Batagelj–Zaversnik bucket algorithm, O(n + m)).

k_core

Subgraph induced by the nodes of core number ≥ k (None: the innermost core).

onion_layers

Onion decomposition layer of every node (Hébert-Dufresne et al.; undirected).

rich_club_coefficient

Rich-club coefficient φ(k) = 2 E_k / N_k (N_k - 1) among the nodes of degree > k.

is_tree

True for a connected forest.

is_forest

True when the (underlying undirected) graph has no cycle: every component has size - 1 edges.

is_regular

True when all degrees agree (in- and out-degrees separately for directed graphs).

s_metric

Σ deg(u)·deg(v) over the edges (Li et al.).

summary

Cheap headline statistics; never raises.

Communities#

modularity

Modularity of a partition (networkx's definition, directed graphs included).

partition_quality

{"coverage", "performance", "modularity"} of a partition.

community_labels

NodeMap node → community index, where 0 is the largest community.

louvain_communities

Louvain community detection (Blondel et al. 2008) with node aggregation between levels.

louvain_hierarchy

The Louvain dendrogram: the partition reached after every level, finest first.

greedy_modularity_communities

Greedy agglomerative modularity maximisation (Clauset–Newman–Moore).

label_propagation_communities

Asynchronous label propagation (Raghavan, Albert & Kumara 2007).

asyn_fluid_communities

Fluid communities (Parés et al. 2017): k communities compete by density.

girvan_newman

Divisive communities (Girvan & Newman 2002): yield a finer partition at each split.

Flow#

FlowResult

A maximum flow: its value and flow[u][v] on every edge (0 where unused).

CutResult

A minimum s–t cut: its capacity, both node sides and the edges crossing it.

maximum_flow

Maximum s``→``t flow by Dinic's algorithm (blocking flows on BFS level graphs).

minimum_cut

Minimum s–t cut (max-flow min-cut theorem); same arguments as maximum_flow().

Spanning trees#

minimum_spanning_tree

Minimum spanning tree of an undirected graph, as a new Graph.

maximum_spanning_tree

Maximum spanning tree (forest) of an undirected graph; see minimum_spanning_tree().

minimum_spanning_edges

Edges (u, v, attrs) of a minimum spanning forest.

maximum_spanning_edges

Edges (u, v, attrs) of a maximum spanning forest (see minimum_spanning_edges()).

Matching#

hopcroft_karp

Maximum-cardinality matching of a bipartite graph (Hopcroft–Karp, O(m·√n)).

bipartite_maximum_matching

Maximum-cardinality matching of a bipartite graph (Hopcroft–Karp, O(m·√n)).

maximal_matching

A maximal matching (no edge can be added), greedily in edge order.

is_matching

True when matching (a dict {u: v} or a collection of edges) is a matching of g.

is_maximal_matching

True when matching is a matching that no edge of g can extend.

is_perfect_matching

True when matching is a matching covering every node of g.

max_weight_matching

Maximum-weight matching of a general graph (Edmonds' blossom algorithm, exact).

min_weight_matching

Lightest matching among those of maximum cardinality.

Coloring#

greedy_color

A proper vertex coloring by the greedy method: each node takes the smallest free color.

is_bipartite

True when the nodes split into two sides with every edge crossing (directions ignored).

bipartite_sets

The two sides (top, bottom) of a bipartite graph.

Matrices and spectra#

adjacency_matrix

Dense adjacency matrix A[i, j] = weight of edge nodes[i] → nodes[j].

degree_vector

Row sums of the (symmetrised, for directed graphs) adjacency matrix.

laplacian_matrix

Graph Laplacian L = D - A (or I - D^-1/2 A D^-1/2 when normalized).

incidence_matrix

(n_nodes, n_edges) incidence matrix; oriented puts -1 at the tail, +1 at the head.

adjacency_spectrum

Eigenvalues of the adjacency matrix (real & sorted for undirected graphs, complex otherwise).

laplacian_spectrum

Ascending eigenvalues of the (symmetrised) Laplacian.

algebraic_connectivity

Second-smallest Laplacian eigenvalue (Fiedler value); 0 iff the graph is disconnected.