Graph Features#
Hiveplotlib can compute node- and edge-level graph metrics and attach the results as columns on the underlying
NodeCollection and Edges data. This makes graph metrics like degree,
betweenness centrality, or community labels more easily available as a partition variable or sorting variables for hive
plots.
The most common way to compute graph features is via the node_graph_metrics and edge_graph_metrics parameters on
initialization of the HivePlot and HivePlotMatrix classes (including
the matrix convenience constructors). After construction, graph metrics can also be computed and attached via
each class’s compute_graph_metrics method (hiveplotlib.HivePlot.compute_graph_metrics() on a HivePlot,
hiveplotlib.HivePlotMatrix.compute_graph_metrics() on a HivePlotMatrix).
The metric tables below catalog the available graph metrics by string name.
For direct use outside these classes, the lower-level hiveplotlib.graph_features.compute_graph_metrics()
function is documented under the “Graph Features Module Reference” section at the bottom of the page.
Node Metric Table#
- hiveplotlib.graph_features.GRAPH_NODE_METRICS: dict[str, Callable[[...], dict[Hashable, Any]]]#
Formally-supported node metric wrappers, keyed by string name.
These are the valid string keys for
node_metricsincompute_graph_metrics()andnode_graph_metricsinhiveplotlib.HivePlotinitialization.
Metric Key |
Description |
Hiveplotlib Wrapper |
|---|---|---|
Degree and Degree Centrality |
||
|
Return the average degree of each node’s neighbors. Accepts kwargs. |
|
|
Return the number of edges connected to each node. No kwargs accepted. |
|
|
Return the degree centrality of each node. No kwargs accepted. |
|
|
Return the number of incoming edges to each node. Requires a directed graph. No kwargs accepted. |
|
|
Return the in-degree centrality of each node. Requires a directed graph. No kwargs accepted. |
|
|
Return the number of outgoing edges from each node. Requires a directed graph. No kwargs accepted. |
|
|
Return the out-degree centrality of each node. Requires a directed graph. No kwargs accepted. |
|
Distance and Shortest-Path Centrality |
||
|
Return the betweenness centrality of each node. Accepts kwargs. |
|
|
Return the closeness centrality of each node. Accepts kwargs. |
|
|
Return the eccentricity of each node. Accepts kwargs. |
|
|
Return the harmonic centrality of each node. Accepts kwargs. |
|
|
Return the load centrality of each node. Accepts kwargs. |
|
Link Analysis |
||
|
Return the eigenvector centrality of each node. Not supported on multigraphs. Accepts kwargs. |
|
|
Return the eigenvector centrality of each node, computed via numpy / scipy. Not supported on multigraphs. Accepts kwargs. |
|
|
Return the HITS authority score of each node. Accepts kwargs. |
|
|
Return the HITS hub score of each node. Accepts kwargs. |
|
|
Return the PageRank of each node. Accepts kwargs. |
|
Clustering and Cores |
||
|
Return the clustering coefficient of each node. Not supported on multigraphs. Accepts kwargs. |
|
|
Return the core number of each node. Not supported on multigraphs. No kwargs accepted. |
|
|
Return the onion-decomposition layer of each node. Requires an undirected, non-multigraph graph. No kwargs accepted. |
|
|
Return the square clustering coefficient of each node. Accepts kwargs. |
|
|
Return the number of triangles that each node is part of. Requires an undirected graph. Accepts kwargs. |
|
Structural Position |
||
|
Return a per-node boolean flag indicating articulation points. Requires an undirected graph. No kwargs accepted. |
|
|
Return the closeness vitality of each node. Accepts kwargs. |
|
|
Return Burt’s constraint of each node. Accepts kwargs. |
|
|
Return the effective size of each node’s ego network. Accepts kwargs. |
|
|
Return a per-node boolean flag indicating isolated nodes. No kwargs accepted. |
|
|
Return the local reciprocity of each node in a directed graph. Requires a directed graph. No kwargs accepted. |
|
DAG |
||
|
Return the topological-generation index of each node in a DAG. Requires a directed acyclic graph (DAG). No kwargs accepted. |
|
Community Detection and Connected Components |
||
|
Return the connected-component label of each node. Requires an undirected graph. No kwargs accepted. |
|
|
Return the greedy-modularity community label of each node. Accepts kwargs. |
|
|
Return the label-propagation community label of each node. Requires an undirected graph. No kwargs accepted. |
|
|
Return the Louvain community label of each node. Accepts kwargs. |
|
|
Return the strongly-connected-component label of each node. Requires a directed graph. No kwargs accepted. |
|
|
Return the weakly-connected-component label of each node. Requires a directed graph. No kwargs accepted. |
|
Edge Metric Table#
- hiveplotlib.graph_features.GRAPH_EDGE_METRICS: dict[str, Callable[[...], dict[Tuple[Hashable, ...], Any]]]#
Formally-supported edge metric wrappers, keyed by string name.
These are the valid string keys for
edge_metricsincompute_graph_metrics()andedge_graph_metricsinhiveplotlib.HivePlotinitialization.
Metric Key |
Description |
Hiveplotlib Wrapper |
|---|---|---|
Edge Centralities |
||
|
Return a per-edge boolean flag indicating bridges. Requires an undirected graph. No kwargs accepted. |
|
|
Return the betweenness centrality of each edge. Accepts kwargs. |
|
|
Return the load centrality of each edge. Accepts kwargs. |
|
Edge Link Prediction |
||
|
Return the Adamic-Adar index of each edge. Requires an undirected, non-multigraph graph. Accepts kwargs. |
|
|
Return the common-neighbor centrality (CCPA) score of each edge. Requires an undirected, non-multigraph graph. Accepts kwargs. |
|
|
Return the Jaccard coefficient of each edge’s endpoint neighborhoods. Requires an undirected, non-multigraph graph. Accepts kwargs. |
|
|
Return the preferential-attachment score of each edge. Requires an undirected, non-multigraph graph. Accepts kwargs. |
|
|
Return the resource-allocation index of each edge. Requires an undirected, non-multigraph graph. Accepts kwargs. |
|
Node Metrics#
Wrappers for networkx node-metric algorithms.
Each function takes a networkx graph and returns a mapping of node ID to a metric value. New wrappers added here
should also be registered in hiveplotlib.graph_features.GRAPH_NODE_METRICS so they become available by string
name on hiveplotlib.graph_features.compute_graph_metrics() and
hiveplotlib.HivePlot initialization.
- hiveplotlib.graph_features.networkx.node_metrics.articulation_points(graph: Graph, backend: str | None = None) dict[Hashable, bool]#
Return a per-node boolean flag indicating articulation points.
Wraps
networkx.algorithms.components.articulation_points(). The only accepted keyword argument is the dispatchbackend. NetworkX returns an iterator of articulation-point nodes; this wrapper projects that set onto adict[node, bool]so it fits the dispatcher’s one-column-per-key contract (Truefor articulation points,Falsefor everyone else).An articulation point is a node whose removal would disconnect the graph (i.e. a cut vertex). They are “bottleneck” nodes in the connectivity sense, often interesting to highlight in network exploration. The node-side analog of
bridges().Requires an undirected graph (
networkx.Graphornetworkx.MultiGraph);networkx.DiGraphandnetworkx.MultiDiGraphare not supported by the underlying networkx implementation.- Parameters:
graph – undirected
networkxgraph.backend – name of an installed
networkxdispatchable backend on which to compute the metric, orNone(default) for default networkx.
- Returns:
mapping of node ID to
Trueif the node is an articulation point,Falseotherwise.- Raises:
ValueError – if
graphis directed.
- hiveplotlib.graph_features.networkx.node_metrics.average_neighbor_degree(graph: Graph, **kwargs) dict[Hashable, float]#
Return the average degree of each node’s neighbors.
Wraps
networkx.algorithms.assortativity.average_neighbor_degree().Accepts the underlying networkx kwargs:
source,target,nodes,weight.High values mark nodes connected mostly to high-degree hubs; low values mark nodes connected mostly to low-degree peripherals. Aggregated across the graph, this is the basis for the degree-assortativity coefficient.
- Parameters:
graph –
networkxgraph.kwargs – forwarded to
networkx.algorithms.assortativity.average_neighbor_degree().
- Returns:
mapping of node ID to the average degree of its neighbors.
- hiveplotlib.graph_features.networkx.node_metrics.betweenness_centrality(graph: Graph, **kwargs) dict[Hashable, float]#
Return the betweenness centrality of each node.
Wraps
networkx.algorithms.centrality.betweenness_centrality().Accepts the underlying networkx kwargs:
k,normalized,weight,endpoints,seed.Betweenness counts the fraction of shortest paths between other node pairs that pass through each node. High values flag bottleneck or broker nodes that sit on many routes through the network.
- Parameters:
graph –
networkxgraph.kwargs – forwarded to
networkx.algorithms.centrality.betweenness_centrality().
- Returns:
mapping of node ID to betweenness centrality.
- hiveplotlib.graph_features.networkx.node_metrics.closeness_centrality(graph: Graph, **kwargs) dict[Hashable, float]#
Return the closeness centrality of each node.
Wraps
networkx.algorithms.centrality.closeness_centrality().Accepts the underlying networkx kwargs:
u,distance,wf_improved.Closeness is the reciprocal of the average shortest-path distance from a node to every other reachable node; high values flag nodes that can reach the rest of the network quickly. Not well-defined on disconnected graphs (see
harmonic_centrality()for the disconnected-graph-friendly variant).- Parameters:
graph –
networkxgraph.kwargs – forwarded to
networkx.algorithms.centrality.closeness_centrality().
- Returns:
mapping of node ID to closeness centrality.
- hiveplotlib.graph_features.networkx.node_metrics.closeness_vitality(graph: Graph, **kwargs) dict[Hashable, float]#
Return the closeness vitality of each node.
Wraps
networkx.algorithms.vitality.closeness_vitality().Accepts the underlying networkx kwargs:
node,weight,wiener_index.Closeness vitality is the change in the graph’s Wiener index when a node is removed; it measures how much overall pairwise reachability would degrade without that node.
- Parameters:
graph –
networkxgraph.kwargs – forwarded to
networkx.algorithms.vitality.closeness_vitality().
- Returns:
mapping of node ID to closeness vitality.
- hiveplotlib.graph_features.networkx.node_metrics.clustering(graph: Graph, **kwargs) dict[Hashable, float]#
Return the clustering coefficient of each node.
Wraps
networkx.algorithms.cluster.clustering().Accepts the underlying networkx kwargs:
nodes,weight.Clustering coefficient is the fraction of a node’s neighbor pairs that are themselves connected, measuring how tightly knit each node’s local neighborhood is. High clustering indicates a node embedded in a triangle-rich region; low clustering indicates a node bridging otherwise-unconnected neighbors.
Requires a non-multigraph (
networkx.Graphornetworkx.DiGraph);networkx.MultiGraphandnetworkx.MultiDiGraphare not supported by the underlying networkx implementation.- Parameters:
graph –
networkxgraph (not a multigraph).kwargs – forwarded to
networkx.algorithms.cluster.clustering().
- Returns:
mapping of node ID to clustering coefficient.
- Raises:
ValueError – if
graphis a multigraph.
- hiveplotlib.graph_features.networkx.node_metrics.connected_components(graph: Graph, backend: str | None = None) dict[Hashable, int]#
Return the connected-component label of each node.
Wraps
networkx.algorithms.components.connected_components(). The only accepted keyword argument is the dispatchbackend. NetworkX returns a generator of node-sets (one per connected component); this wrapper projects each node onto an integer component label.A connected component is a maximal subgraph in which every node can reach every other node via undirected paths; equivalently, a “connected piece” of the graph. Component labels are assigned by descending component size (ties broken by smallest node id within each component), so label
0is the largest component, label1is the second-largest, and so on. This ordering is stable across runs and versions, so a “color the giant component” workflow can rely on label0.Requires an undirected graph (
networkx.Graphornetworkx.MultiGraph);networkx.DiGraphandnetworkx.MultiDiGraphare not supported by the underlying networkx implementation. For directed graphs, seestrongly_connected_components()andweakly_connected_components().- Parameters:
graph – undirected
networkxgraph.backend – name of an installed
networkxdispatchable backend on which to compute the metric, orNone(default) for default networkx.
- Returns:
mapping of node ID to integer component label (label
0is the largest component).- Raises:
ValueError – if
graphis directed.
- hiveplotlib.graph_features.networkx.node_metrics.constraint(graph: Graph, **kwargs) dict[Hashable, float]#
Return Burt’s constraint of each node.
Wraps
networkx.algorithms.structuralholes.constraint().Accepts the underlying networkx kwargs:
nodes,weight.Burt’s constraint measures the extent to which a node’s connections are concentrated in a single dense cluster; high constraint indicates a node trapped in a tightly-knit group, low constraint indicates a node spanning structural holes between otherwise-disconnected regions.
- Parameters:
graph –
networkxgraph.kwargs – forwarded to
networkx.algorithms.structuralholes.constraint().
- Returns:
mapping of node ID to Burt’s constraint.
- hiveplotlib.graph_features.networkx.node_metrics.core_number(graph: Graph, backend: str | None = None) dict[Hashable, int]#
Return the core number of each node.
Wraps
networkx.algorithms.core.core_number(). The only accepted keyword argument is the dispatchbackend.A node’s core number is the largest
ksuch that the node belongs to a k-core (a subgraph in which every node has degree at leastk). Higher core numbers identify nodes deeply embedded in a densely connected region; for a finer-grained layered view that refines this within each shell, seeonion_layers().Requires a non-multigraph (
networkx.Graphornetworkx.DiGraph);networkx.MultiGraphandnetworkx.MultiDiGraphare not supported by the underlying networkx implementation.- Parameters:
graph –
networkxgraph (not a multigraph).backend – name of an installed
networkxdispatchable backend on which to compute the metric, orNone(default) for default networkx.
- Returns:
mapping of node ID to its core number.
- Raises:
ValueError – if
graphis a multigraph.
- hiveplotlib.graph_features.networkx.node_metrics.degree(graph: Graph) dict[Hashable, int]#
Return the number of edges connected to each node.
Wraps
networkx.Graph.degree. No keyword arguments are accepted. As a direct structural read of the graph (a method call, not a dispatchablenetworkxfunction), backend dispatch (graph_metric_backend) does not apply to this metric.Degree is the simplest centrality measure: a count of each node’s incident edges. Higher degree means more direct connections, making it the natural first lens for spotting hubs.
- Parameters:
graph –
networkxgraph.- Returns:
mapping of node ID to the number of connected edges.
- hiveplotlib.graph_features.networkx.node_metrics.degree_centrality(graph: Graph, backend: str | None = None) dict[Hashable, float]#
Return the degree centrality of each node.
Wraps
networkx.algorithms.centrality.degree_centrality(). The only accepted keyword argument is the dispatchbackend.Degree centrality is the fraction of nodes a given node is connected to.
- Parameters:
graph –
networkxgraph.backend – name of an installed
networkxdispatchable backend on which to compute the metric, orNone(default) for default networkx.
- Returns:
mapping of node ID to degree centrality.
- hiveplotlib.graph_features.networkx.node_metrics.eccentricity(graph: Graph, **kwargs) dict[Hashable, int]#
Return the eccentricity of each node.
Wraps
networkx.algorithms.distance_measures.eccentricity().Accepts the underlying networkx kwargs:
v,sp,weight.Eccentricity is the longest shortest-path distance from a node to any other node; nodes with low eccentricity sit near the graph’s center, while nodes with high eccentricity sit on its periphery. The underlying networkx implementation requires the graph to be connected (or, for directed graphs, strongly connected); disconnected graphs raise
networkx.NetworkXError.- Parameters:
graph –
networkxgraph.kwargs – forwarded to
networkx.algorithms.distance_measures.eccentricity().
- Returns:
mapping of node ID to eccentricity.
- hiveplotlib.graph_features.networkx.node_metrics.effective_size(graph: Graph, **kwargs) dict[Hashable, float]#
Return the effective size of each node’s ego network.
Wraps
networkx.algorithms.structuralholes.effective_size().Accepts the underlying networkx kwargs:
nodes,weight.Effective size is Burt’s measure of non-redundancy: a node’s degree minus the average degree of its neighbors within its ego network. Larger values indicate a node whose neighbors are themselves loosely connected, signaling brokerage over structural holes.
- Parameters:
graph –
networkxgraph.kwargs – forwarded to
networkx.algorithms.structuralholes.effective_size().
- Returns:
mapping of node ID to effective size.
- hiveplotlib.graph_features.networkx.node_metrics.eigenvector_centrality(graph: Graph, **kwargs) dict[Hashable, float]#
Return the eigenvector centrality of each node.
Wraps
networkx.algorithms.centrality.eigenvector_centrality().Accepts the underlying networkx kwargs:
max_iter,tol,nstart,weight.Each node’s score is proportional to the sum of its neighbors’ scores, so being connected to high-scoring nodes counts more than being connected to many low-scoring ones. This is the conceptual ancestor of PageRank and rewards influence through influential company rather than raw connection count.
Requires a non-multigraph (
networkx.Graphornetworkx.DiGraph);networkx.MultiGraphandnetworkx.MultiDiGraphare not supported by the underlying networkx implementation.- Parameters:
graph –
networkxgraph (not a multigraph).kwargs – forwarded to
networkx.algorithms.centrality.eigenvector_centrality().
- Returns:
mapping of node ID to eigenvector centrality.
- Raises:
ValueError – if
graphis a multigraph.
- hiveplotlib.graph_features.networkx.node_metrics.eigenvector_centrality_numpy(graph: Graph, **kwargs) dict[Hashable, float]#
Return the eigenvector centrality of each node, computed via numpy / scipy.
Wraps
networkx.algorithms.centrality.eigenvector_centrality_numpy().Accepts the underlying networkx kwargs:
weight,max_iter,tol.A direct-eigensolve alternative to
eigenvector_centrality(): the numpy backend uses scipy’s sparse eigensolver instead of power iteration, so it is more reliable on graphs where the iterative solver fails to converge (in exchange for a heavier dependency footprint via scipy).Requires a non-multigraph (
networkx.Graphornetworkx.DiGraph);networkx.MultiGraphandnetworkx.MultiDiGraphcollapse parallel-edge weights into a single adjacency entry in the underlyingnx.to_scipy_sparse_arraycall, so the wrapper rejects them rather than returning silently-different-than-expected values. The siblingeigenvector_centrality()carries the same restriction; flatten the multigraph (e.g. rebuild viahiveplotlib.converters.nodes_edges_to_networkx()withmultigraph=False) before computing eigenvector centrality.- Parameters:
graph –
networkxgraph (not a multigraph).kwargs – forwarded to
networkx.algorithms.centrality.eigenvector_centrality_numpy().
- Returns:
mapping of node ID to eigenvector centrality.
- Raises:
ValueError – if
graphis a multigraph.
- hiveplotlib.graph_features.networkx.node_metrics.greedy_modularity_communities(graph: Graph, **kwargs) dict[Hashable, int]#
Return the greedy-modularity community label of each node.
Wraps
networkx.algorithms.community.modularity_max.greedy_modularity_communities().Accepts the underlying networkx kwargs:
weight,resolution,cutoff,best_n.Greedy modularity (Clauset-Newman-Moore) iteratively merges the pair of communities that most increases modularity, producing a partition of the graph into communities. NetworkX returns the partition as a list of frozensets; this wrapper projects each node onto an integer community label.
Community labels are assigned by descending community size (ties broken by smallest node id within each community), so label
0is the largest community, label1is the second-largest, and so on. This ordering is stable across runs and versions, so a “color the giant community” workflow can rely on label0.- Parameters:
graph –
networkxgraph.kwargs – forwarded to
networkx.algorithms.community.modularity_max.greedy_modularity_communities().
- Returns:
mapping of node ID to integer community label (label
0is the largest community).
- hiveplotlib.graph_features.networkx.node_metrics.harmonic_centrality(graph: Graph, **kwargs) dict[Hashable, float]#
Return the harmonic centrality of each node.
Wraps
networkx.algorithms.centrality.harmonic_centrality().Accepts the underlying networkx kwargs:
nbunch,distance,sources.Harmonic centrality sums the reciprocals of the shortest-path distances from each node to all other nodes, so unreachable nodes contribute zero rather than infinity. This makes it well-defined on disconnected graphs, where closeness centrality is not.
- Parameters:
graph –
networkxgraph.kwargs – forwarded to
networkx.algorithms.centrality.harmonic_centrality().
- Returns:
mapping of node ID to harmonic centrality.
- hiveplotlib.graph_features.networkx.node_metrics.hits_authorities(graph: Graph, **kwargs) dict[Hashable, float]#
Return the HITS authority score of each node.
Wraps the second element returned by
networkx.algorithms.link_analysis.hits_alg.hits().Accepts the underlying networkx kwargs:
max_iter,tol,nstart,normalized.A node’s HITS authority score is high when many high-hub nodes point to it; the hub / authority split rewards nodes that act as important “content” (high authority score) versus nodes that act as good “indexes” of important content (high hub score, see
hits_hubs()).Requesting both
hits_hubs()andhits_authorities()in one call tohiveplotlib.graph_features.compute_graph_metrics()runs the underlyingnetworkx.algorithms.link_analysis.hits_alg.hits()iteration twice (no shared cache).- Parameters:
graph –
networkxgraph.kwargs – forwarded to
networkx.algorithms.link_analysis.hits_alg.hits().
- Returns:
mapping of node ID to HITS authority score.
- hiveplotlib.graph_features.networkx.node_metrics.hits_hubs(graph: Graph, **kwargs) dict[Hashable, float]#
Return the HITS hub score of each node.
Wraps the first element returned by
networkx.algorithms.link_analysis.hits_alg.hits().Accepts the underlying networkx kwargs:
max_iter,tol,nstart,normalized.A node’s HITS hub score is high when it points to many high-authority nodes; the hub / authority split rewards nodes that act as good “indexes” of important content (high hub score) versus nodes that act as important “content” themselves (high authority score, see
hits_authorities()).Requesting both
hits_hubs()andhits_authorities()in one call tohiveplotlib.graph_features.compute_graph_metrics()runs the underlyingnetworkx.algorithms.link_analysis.hits_alg.hits()iteration twice (no shared cache).- Parameters:
graph –
networkxgraph.kwargs – forwarded to
networkx.algorithms.link_analysis.hits_alg.hits().
- Returns:
mapping of node ID to HITS hub score.
- hiveplotlib.graph_features.networkx.node_metrics.in_degree(graph: Graph) dict[Hashable, int]#
Return the number of incoming edges to each node.
Wraps
networkx.DiGraph.in_degree. No keyword arguments are accepted. As a direct structural read of the graph (a method call, not a dispatchablenetworkxfunction), backend dispatch (graph_metric_backend) does not apply to this metric.In-degree counts inbound edges, distinguishing nodes that act as sinks or popular targets from nodes that mostly originate connections.
Requires a directed graph (
networkx.DiGraphornetworkx.MultiDiGraph).- Parameters:
graph – directed
networkxgraph.- Returns:
mapping of node ID to the number of incoming edges.
- Raises:
ValueError – if
graphis undirected.
- hiveplotlib.graph_features.networkx.node_metrics.in_degree_centrality(graph: Graph, backend: str | None = None) dict[Hashable, float]#
Return the in-degree centrality of each node.
Wraps
networkx.algorithms.centrality.in_degree_centrality(). The only accepted keyword argument is the dispatchbackend.In-degree centrality is the fraction of other nodes pointing to a given node, the directed-graph analog of
degree_centrality()restricted to incoming edges.Requires a directed graph (
networkx.DiGraphornetworkx.MultiDiGraph).- Parameters:
graph – directed
networkxgraph.backend – name of an installed
networkxdispatchable backend on which to compute the metric, orNone(default) for default networkx.
- Returns:
mapping of node ID to in-degree centrality.
- Raises:
ValueError – if
graphis undirected.
- hiveplotlib.graph_features.networkx.node_metrics.isolates(graph: Graph, backend: str | None = None) dict[Hashable, bool]#
Return a per-node boolean flag indicating isolated nodes.
Wraps
networkx.algorithms.isolate.isolates(). The only accepted keyword argument is the dispatchbackend. NetworkX returns an iterator of isolated nodes; this wrapper projects that set onto adict[node, bool]so it fits the dispatcher’s one-column-per-key contract (Truefor isolated nodes,Falsefor everyone else).An isolated node is a node with no incident edges. They typically reflect missing data or genuinely disconnected entities and are useful to flag before laying out a hive plot.
- Parameters:
graph –
networkxgraph.backend – name of an installed
networkxdispatchable backend on which to compute the metric, orNone(default) for default networkx.
- Returns:
mapping of node ID to
Trueif the node is isolated,Falseotherwise.
- hiveplotlib.graph_features.networkx.node_metrics.label_propagation_communities(graph: Graph, backend: str | None = None) dict[Hashable, int]#
Return the label-propagation community label of each node.
Wraps
networkx.algorithms.community.label_propagation.label_propagation_communities(). The only accepted keyword argument is the dispatchbackend.Label propagation is a fast, near-linear-time community-detection algorithm in which each node iteratively adopts the most common label among its neighbors. NetworkX returns the partition as a generator of node-sets; this wrapper projects each node onto an integer community label.
Community labels are assigned by descending community size (ties broken by smallest node id within each community), so label
0is the largest community, label1is the second-largest, and so on. This ordering is stable across runs and versions, so a “color the giant community” workflow can rely on label0.Requires an undirected graph (
networkx.Graphornetworkx.MultiGraph);networkx.DiGraphandnetworkx.MultiDiGraphare not supported by the underlying networkx implementation.- Parameters:
graph – undirected
networkxgraph.backend – name of an installed
networkxdispatchable backend on which to compute the metric, orNone(default) for default networkx.
- Returns:
mapping of node ID to integer community label (label
0is the largest community).- Raises:
ValueError – if
graphis directed.
- hiveplotlib.graph_features.networkx.node_metrics.load_centrality(graph: Graph, **kwargs) dict[Hashable, float]#
Return the load centrality of each node.
Wraps
networkx.algorithms.centrality.load_centrality().Accepts the underlying networkx kwargs:
v,cutoff,normalized,weight.Load centrality measures the fraction of shortest-path “load” that flows through each node under a stress-based routing model; it is a close cousin of betweenness centrality and often correlates strongly with it.
- Parameters:
graph –
networkxgraph.kwargs – forwarded to
networkx.algorithms.centrality.load_centrality().
- Returns:
mapping of node ID to load centrality.
- hiveplotlib.graph_features.networkx.node_metrics.louvain_communities(graph: Graph, **kwargs) dict[Hashable, int]#
Return the Louvain community label of each node.
Wraps
networkx.algorithms.community.louvain.louvain_communities().Accepts the underlying networkx kwargs:
weight,resolution,threshold,max_level,seed.Louvain is a stochastic, modularity-maximizing community-detection algorithm. NetworkX returns the partition as a list of node-sets; this wrapper projects each node onto an integer community label. Pass
seed=...for reproducible results.Community labels are assigned by descending community size (ties broken by smallest node id within each community), so label
0is the largest community, label1is the second-largest, and so on. This ordering is stable across runs and versions, so a “color the giant community” workflow can rely on label0.- Parameters:
graph –
networkxgraph.kwargs – forwarded to
networkx.algorithms.community.louvain.louvain_communities().
- Returns:
mapping of node ID to integer community label (label
0is the largest community).
- hiveplotlib.graph_features.networkx.node_metrics.onion_layers(graph: Graph, backend: str | None = None) dict[Hashable, int]#
Return the onion-decomposition layer of each node.
Wraps
networkx.algorithms.core.onion_layers(). The only accepted keyword argument is the dispatchbackend.The onion decomposition refines the k-core decomposition by iteratively peeling nodes within each k-core shell. Each node receives an integer layer index; nodes peeled first sit in the lowest layers.
Requires an undirected, non-multigraph (
networkx.Graph);networkx.DiGraph,networkx.MultiGraph, andnetworkx.MultiDiGraphare not supported by the underlying networkx implementation.- Parameters:
graph – undirected, non-multigraph
networkxgraph.backend – name of an installed
networkxdispatchable backend on which to compute the metric, orNone(default) for default networkx.
- Returns:
mapping of node ID to its onion-decomposition layer.
- Raises:
ValueError – if
graphis directed or a multigraph.
- hiveplotlib.graph_features.networkx.node_metrics.out_degree(graph: Graph) dict[Hashable, int]#
Return the number of outgoing edges from each node.
Wraps
networkx.DiGraph.out_degree. No keyword arguments are accepted. As a direct structural read of the graph (a method call, not a dispatchablenetworkxfunction), backend dispatch (graph_metric_backend) does not apply to this metric.Out-degree counts outbound edges, distinguishing nodes that act as sources or active broadcasters from nodes that mostly receive connections.
Requires a directed graph (
networkx.DiGraphornetworkx.MultiDiGraph).- Parameters:
graph – directed
networkxgraph.- Returns:
mapping of node ID to the number of outgoing edges.
- Raises:
ValueError – if
graphis undirected.
- hiveplotlib.graph_features.networkx.node_metrics.out_degree_centrality(graph: Graph, backend: str | None = None) dict[Hashable, float]#
Return the out-degree centrality of each node.
Wraps
networkx.algorithms.centrality.out_degree_centrality(). The only accepted keyword argument is the dispatchbackend.Out-degree centrality is the fraction of other nodes a given node points to, the directed-graph analog of
degree_centrality()restricted to outgoing edges.Requires a directed graph (
networkx.DiGraphornetworkx.MultiDiGraph).- Parameters:
graph – directed
networkxgraph.backend – name of an installed
networkxdispatchable backend on which to compute the metric, orNone(default) for default networkx.
- Returns:
mapping of node ID to out-degree centrality.
- Raises:
ValueError – if
graphis undirected.
- hiveplotlib.graph_features.networkx.node_metrics.pagerank(graph: Graph, **kwargs) dict[Hashable, float]#
Return the PageRank of each node.
Wraps
networkx.algorithms.link_analysis.pagerank_alg.pagerank().Accepts the underlying networkx kwargs:
alpha,personalization,max_iter,tol,nstart,weight,dangling.PageRank models a random walker that follows edges with probability
alphaand teleports to a random node otherwise; each node’s score is the stationary probability of the walker landing there. Originally designed to rank web pages, it generalizes the eigenvector-centrality idea to handle dangling nodes and disconnected components.- Parameters:
graph –
networkxgraph.kwargs – forwarded to
networkx.algorithms.link_analysis.pagerank_alg.pagerank().
- Returns:
mapping of node ID to PageRank score.
- hiveplotlib.graph_features.networkx.node_metrics.reciprocity(graph: Graph, backend: str | None = None) dict[Hashable, float]#
Return the local reciprocity of each node in a directed graph.
Wraps
networkx.algorithms.reciprocity.reciprocity(). The only accepted keyword argument is the dispatchbackend; the wrapper always passesnodes=graph.nodesso the underlying function returns a per-node dict rather than the graph-level scalar it returns when called withoutnodes.Reciprocity is the fraction of a node’s directed edges that have a matching reverse edge; high reciprocity indicates a node embedded in mutual exchanges, low reciprocity indicates a node mostly sending or mostly receiving.
Requires a directed graph (
networkx.DiGraphornetworkx.MultiDiGraph).- Parameters:
graph – directed
networkxgraph.backend – name of an installed
networkxdispatchable backend on which to compute the metric, orNone(default) for default networkx.
- Returns:
mapping of node ID to local reciprocity.
- Raises:
ValueError – if
graphis undirected.
- hiveplotlib.graph_features.networkx.node_metrics.square_clustering(graph: Graph, **kwargs) dict[Hashable, float]#
Return the square clustering coefficient of each node.
Wraps
networkx.algorithms.cluster.square_clustering().Accepts the underlying networkx kwarg:
nodes.Square clustering counts the fraction of pairs of a node’s neighbors that share another common neighbor (forming a 4-cycle), making it the bipartite-friendly analog of the standard (triangle-based) clustering coefficient.
- Parameters:
graph –
networkxgraph.kwargs – forwarded to
networkx.algorithms.cluster.square_clustering().
- Returns:
mapping of node ID to square clustering coefficient.
- hiveplotlib.graph_features.networkx.node_metrics.strongly_connected_components(graph: Graph, backend: str | None = None) dict[Hashable, int]#
Return the strongly-connected-component label of each node.
Wraps
networkx.algorithms.components.strongly_connected_components(). The only accepted keyword argument is the dispatchbackend. NetworkX returns a generator of node-sets (one per strongly connected component); this wrapper projects each node onto an integer component label.A strongly connected component is a maximal subgraph in which every node can reach every other node by following directed edges in both directions; that is, for any pair of nodes
(u, v)there exists a directed path fromutovand a directed path fromvtou. Contrast withweakly_connected_components(), which only requires the nodes to be connected once edge directions are dropped.Component labels are assigned by descending component size (ties broken by smallest node id within each component), so label
0is the largest component, label1is the second-largest, and so on. This ordering is stable across runs and versions.Requires a directed graph (
networkx.DiGraphornetworkx.MultiDiGraph).- Parameters:
graph – directed
networkxgraph.backend – name of an installed
networkxdispatchable backend on which to compute the metric, orNone(default) for default networkx.
- Returns:
mapping of node ID to integer strongly-connected-component label (label
0is the largest).- Raises:
ValueError – if
graphis undirected.
- hiveplotlib.graph_features.networkx.node_metrics.topological_generations(graph: Graph, backend: str | None = None) dict[Hashable, int]#
Return the topological-generation index of each node in a DAG.
Wraps
networkx.algorithms.dag.topological_generations(). The only accepted keyword argument is the dispatchbackend. NetworkX returns a generator of node-sets (one per topological layer); this wrapper assigns each node its layer index as an int so the dispatcher’s one-column-per-key contract holds.Generation 0 contains all source nodes (nodes with no incoming edges); generation 1 contains nodes whose only predecessors are in generation 0; and so on. This is the natural “level” of a node in a directed acyclic graph, useful as a sorting variable for hierarchical layouts.
Requires a directed acyclic graph (
networkx.DiGraphornetworkx.MultiDiGraph); anetworkx.NetworkXUnfeasibleis raised by the underlying networkx implementation ifgraphis directed but contains a cycle.- Parameters:
graph – directed acyclic
networkxgraph.backend – name of an installed
networkxdispatchable backend on which to compute the metric, orNone(default) for default networkx.
- Returns:
mapping of node ID to its integer generation index.
- Raises:
ValueError – if
graphis undirected.networkx.NetworkXUnfeasible – if
graphcontains a cycle (raised by the underlying networkx implementation).
- hiveplotlib.graph_features.networkx.node_metrics.triangles(graph: Graph, **kwargs) dict[Hashable, int]#
Return the number of triangles that each node is part of.
Wraps
networkx.algorithms.cluster.triangles().Accepts the underlying networkx kwarg:
nodes.Counts the number of triangles (closed three-node cycles) each node participates in. Triangles are the simplest measure of local transitivity, signaling tightly-knit neighborhoods where a node’s contacts are also each other’s contacts.
Requires an undirected graph (
networkx.Graphornetworkx.MultiGraph);networkx.DiGraphandnetworkx.MultiDiGraphare not supported by the underlying networkx implementation.- Parameters:
graph – undirected
networkxgraph.kwargs – forwarded to
networkx.algorithms.cluster.triangles().
- Returns:
mapping of node ID to triangle count.
- Raises:
ValueError – if
graphis directed.
- hiveplotlib.graph_features.networkx.node_metrics.weakly_connected_components(graph: Graph, backend: str | None = None) dict[Hashable, int]#
Return the weakly-connected-component label of each node.
Wraps
networkx.algorithms.components.weakly_connected_components(). The only accepted keyword argument is the dispatchbackend. NetworkX returns a generator of node-sets (one per weakly connected component); this wrapper projects each node onto an integer component label.A weakly connected component of a directed graph is the same thing as a connected component of the graph with edge directions ignored. The two functions are split because
connected_components()only accepts undirected input andweakly_connected_components()only accepts directed input; otherwise they compute the same partition. Two nodes can land in the same weakly connected component without any directed path between them, as long as some chain of edges links them when direction is set aside. Contrast withstrongly_connected_components(), which requires a directed path between every pair of nodes in both directions.Component labels are assigned by descending component size (ties broken by smallest node id within each component), so label
0is the largest component, label1is the second-largest, and so on. This ordering is stable across runs and versions.Requires a directed graph (
networkx.DiGraphornetworkx.MultiDiGraph).- Parameters:
graph – directed
networkxgraph.backend – name of an installed
networkxdispatchable backend on which to compute the metric, orNone(default) for default networkx.
- Returns:
mapping of node ID to integer weakly-connected-component label (label
0is the largest).- Raises:
ValueError – if
graphis undirected.
Edge Metrics#
Wrappers for networkx edge-metric algorithms.
Each function takes a networkx graph and returns a mapping of edge tuple to a metric value. New wrappers added here
should also be registered in hiveplotlib.graph_features.GRAPH_EDGE_METRICS so they become available by string
name on hiveplotlib.graph_features.compute_graph_metrics() and
hiveplotlib.HivePlot initialization.
- hiveplotlib.graph_features.networkx.edge_metrics.adamic_adar_index(graph: Graph, **kwargs) dict[Tuple[Hashable, ...], float]#
Return the Adamic-Adar index of each edge.
Wraps
networkx.algorithms.link_prediction.adamic_adar_index().Accepts the underlying networkx kwarg:
ebunch.Adamic-Adar sums
1 / log(degree(w))over the common neighborswof each endpoint pair; rare neighbors (low-degree hubs are penalized) contribute more than common ones. The score grows with shared structural connectivity and is one of the strongest classical link-prediction baselines.By default this wrapper applies the NetworkX link-prediction score to every existing edge in
graph(ebunch=graph.edges()), letting you size or color edges by the predictor. NetworkX intends these scores for non-edges by default (the canonical use is “predict where edges should be”); pass an explicitebunch=...to score a different edge set.Requires an undirected, non-multigraph (
networkx.Graph);networkx.DiGraph,networkx.MultiGraph, andnetworkx.MultiDiGraphare not supported by the underlying networkx implementation.- Parameters:
graph – undirected, non-multigraph
networkxgraph.kwargs – forwarded to
networkx.algorithms.link_prediction.adamic_adar_index(); the wrapper defaultsebunchtograph.edges()when not provided.
- Returns:
mapping of edge tuple
(u, v)to Adamic-Adar index.- Raises:
ValueError – if
graphis directed or a multigraph.
- hiveplotlib.graph_features.networkx.edge_metrics.bridges(graph: Graph, backend: str | None = None) dict[Tuple[Hashable, ...], bool]#
Return a per-edge boolean flag indicating bridges.
Wraps
networkx.algorithms.bridges.bridges(). The only accepted keyword argument is the dispatchbackend. NetworkX returns an iterator of bridge edges; this wrapper projects that set onto adict[edge_tuple, bool]so it fits the dispatcher’s one-column-per-edge contract (Truefor bridges,Falsefor everyone else).A bridge is an edge whose removal would disconnect the graph (i.e. a cut edge). They are “bottleneck” edges in the connectivity sense, the edge-side analog of articulation points and often interesting to highlight in network exploration.
Requires an undirected graph (
networkx.Graphornetworkx.MultiGraph);networkx.DiGraphandnetworkx.MultiDiGraphare not supported by the underlying networkx implementation.- Parameters:
graph – undirected
networkxgraph.backend – name of an installed
networkxdispatchable backend on which to compute the metric, orNone(default) for default networkx.
- Returns:
mapping of edge tuple to
Trueif the edge is a bridge,Falseotherwise.- Raises:
ValueError – if
graphis directed.
- hiveplotlib.graph_features.networkx.edge_metrics.common_neighbor_centrality(graph: Graph, **kwargs) dict[Tuple[Hashable, ...], float]#
Return the common-neighbor centrality (CCPA) score of each edge.
Wraps
networkx.algorithms.link_prediction.common_neighbor_centrality().Accepts the underlying networkx kwargs:
ebunch,alpha.Common-neighbor centrality (also known as the CCPA score) combines a common-neighbor count with the inverse shortest-path distance between the two endpoints, weighted by a tunable
alphaparameter. It typically outperforms the classical common-neighbor and shortest-path baselines on link-prediction benchmarks. The underlyingnetworkx.algorithms.link_prediction.common_neighbor_centrality()defaults toalpha=0.8; pass an explicitalpha=to override.By default this wrapper applies the NetworkX link-prediction score to every existing edge in
graph(ebunch=graph.edges()), letting you size or color edges by the predictor. NetworkX intends these scores for non-edges by default (the canonical use is “predict where edges should be”); pass an explicitebunch=...to score a different edge set.Requires an undirected, non-multigraph (
networkx.Graph);networkx.DiGraph,networkx.MultiGraph, andnetworkx.MultiDiGraphare not supported by the underlying networkx implementation.- Parameters:
graph – undirected, non-multigraph
networkxgraph.kwargs – forwarded to
networkx.algorithms.link_prediction.common_neighbor_centrality(); the wrapper defaultsebunchtograph.edges()when not provided.
- Returns:
mapping of edge tuple
(u, v)to common-neighbor centrality (CCPA) score.- Raises:
ValueError – if
graphis directed or a multigraph.
- hiveplotlib.graph_features.networkx.edge_metrics.edge_betweenness_centrality(graph: Graph, **kwargs) dict[Tuple[Hashable, ...], float]#
Return the betweenness centrality of each edge.
Wraps
networkx.algorithms.centrality.edge_betweenness_centrality().Accepts the underlying networkx kwargs:
k,normalized,weight,seed.Edge betweenness counts the fraction of shortest paths between node pairs that traverse each edge; high values flag edges that act as bridges between otherwise-loosely-connected regions of the graph. The edge-side analog of
betweenness_centrality().- Parameters:
graph –
networkxgraph.kwargs – forwarded to
networkx.algorithms.centrality.edge_betweenness_centrality().
- Returns:
mapping of edge tuple (
(u, v)or(u, v, key)for multigraphs) to betweenness centrality.
- hiveplotlib.graph_features.networkx.edge_metrics.edge_load_centrality(graph: Graph, **kwargs) dict[Tuple[Hashable, ...], float]#
Return the load centrality of each edge.
Wraps
networkx.algorithms.centrality.edge_load_centrality().Accepts the underlying networkx kwarg:
cutoff.Edge load centrality measures the fraction of shortest-path “load” that flows along each edge under a stress-based routing model; it is a close cousin of edge betweenness and often correlates strongly with it. The edge-side analog of
load_centrality().- Parameters:
graph –
networkxgraph.kwargs – forwarded to
networkx.algorithms.centrality.edge_load_centrality().
- Returns:
mapping of edge tuple to load centrality.
- hiveplotlib.graph_features.networkx.edge_metrics.jaccard_coefficient(graph: Graph, **kwargs) dict[Tuple[Hashable, ...], float]#
Return the Jaccard coefficient of each edge’s endpoint neighborhoods.
Wraps
networkx.algorithms.link_prediction.jaccard_coefficient().Accepts the underlying networkx kwarg:
ebunch.Jaccard coefficient is the size of the intersection of two nodes’ neighbor sets divided by the size of their union; values lie in
[0, 1]. High values indicate two nodes that share most of their neighbors (a likely-link signal in network science); low values indicate two nodes with disjoint neighborhoods.By default this wrapper applies the NetworkX link-prediction score to every existing edge in
graph(ebunch=graph.edges()), letting you size or color edges by the predictor. NetworkX intends these scores for non-edges by default (the canonical use is “predict where edges should be”); pass an explicitebunch=...to score a different edge set.Requires an undirected, non-multigraph (
networkx.Graph);networkx.DiGraph,networkx.MultiGraph, andnetworkx.MultiDiGraphare not supported by the underlying networkx implementation.- Parameters:
graph – undirected, non-multigraph
networkxgraph.kwargs – forwarded to
networkx.algorithms.link_prediction.jaccard_coefficient(); the wrapper defaultsebunchtograph.edges()when not provided.
- Returns:
mapping of edge tuple
(u, v)to Jaccard coefficient.- Raises:
ValueError – if
graphis directed or a multigraph.
- hiveplotlib.graph_features.networkx.edge_metrics.preferential_attachment(graph: Graph, **kwargs) dict[Tuple[Hashable, ...], float]#
Return the preferential-attachment score of each edge.
Wraps
networkx.algorithms.link_prediction.preferential_attachment().Accepts the underlying networkx kwarg:
ebunch.Preferential-attachment score is the product of the two endpoints’ degrees, modeling the rich-get-richer dynamic where high-degree nodes accumulate even more connections over time. Values are unbounded above and grow with the degrees of the endpoints.
By default this wrapper applies the NetworkX link-prediction score to every existing edge in
graph(ebunch=graph.edges()), letting you size or color edges by the predictor. NetworkX intends these scores for non-edges by default (the canonical use is “predict where edges should be”); pass an explicitebunch=...to score a different edge set.Requires an undirected, non-multigraph (
networkx.Graph);networkx.DiGraph,networkx.MultiGraph, andnetworkx.MultiDiGraphare not supported by the underlying networkx implementation.- Parameters:
graph – undirected, non-multigraph
networkxgraph.kwargs – forwarded to
networkx.algorithms.link_prediction.preferential_attachment(); the wrapper defaultsebunchtograph.edges()when not provided.
- Returns:
mapping of edge tuple
(u, v)to preferential-attachment score.- Raises:
ValueError – if
graphis directed or a multigraph.
- hiveplotlib.graph_features.networkx.edge_metrics.resource_allocation_index(graph: Graph, **kwargs) dict[Tuple[Hashable, ...], float]#
Return the resource-allocation index of each edge.
Wraps
networkx.algorithms.link_prediction.resource_allocation_index().Accepts the underlying networkx kwarg:
ebunch.Resource-allocation index sums
1 / degree(w)over the common neighborswof each endpoint pair; it is a close cousin of Adamic-Adar that penalizes high-degree common neighbors more aggressively. Often competitive with Adamic-Adar on classical link-prediction benchmarks.By default this wrapper applies the NetworkX link-prediction score to every existing edge in
graph(ebunch=graph.edges()), letting you size or color edges by the predictor. NetworkX intends these scores for non-edges by default (the canonical use is “predict where edges should be”); pass an explicitebunch=...to score a different edge set.Requires an undirected, non-multigraph (
networkx.Graph);networkx.DiGraph,networkx.MultiGraph, andnetworkx.MultiDiGraphare not supported by the underlying networkx implementation.- Parameters:
graph – undirected, non-multigraph
networkxgraph.kwargs – forwarded to
networkx.algorithms.link_prediction.resource_allocation_index(); the wrapper defaultsebunchtograph.edges()when not provided.
- Returns:
mapping of edge tuple
(u, v)to resource-allocation index.- Raises:
ValueError – if
graphis directed or a multigraph.
Graph Features Module Reference#
Graph-feature computation utilities for augmenting Hiveplotlib data structures.
This module exposes wrappers around networkx node- and edge-metric algorithms (in
hiveplotlib.graph_features.networkx.node_metrics and
hiveplotlib.graph_features.networkx.edge_metrics), the master
dicts that register them (GRAPH_NODE_METRICS, GRAPH_EDGE_METRICS), and the public
compute_graph_metrics() entry point for attaching computed metrics as columns on
hiveplotlib.NodeCollection and hiveplotlib.Edges instances.
How to extend:
Add a wrapper function (
new_function(graph: nx.Graph, **kwargs), inclusion ofkwargsoptional) tohiveplotlib.graph_features.networkx.node_metricsorhiveplotlib.graph_features.networkx.edge_metrics.Wire up backend dispatch (
graph_metric_backend) according to the wrapper’s shape:Bare wrapper (no
**kwargs) around a dispatchablenetworkxfunction: add abackend: Optional[str] = Noneparameter, forwarded to thenetworkxcall via_backend_kwargs()(inhiveplotlib.graph_features.networkx._helpers).Wrapper forwarding
**kwargsto a dispatchablenetworkxfunction: nothing extra needed; a resolvedbackendrides along with the other kwargs.Direct structural read of the graph (a method call, not a dispatchable
networkxfunction): add the metric name to_NON_DISPATCHABLE_METRICSin this module so backend requests are handled up front (a global backend silently skips it; an explicit per-metric"backend"entry is rejected with an actionable message) instead of failing mid-loop.
Add it to the appropriate dict (
GRAPH_NODE_METRICSorGRAPH_EDGE_METRICS).
New functions added to one of the dicts are picked up by the parametrized metric tests automatically, including
backend forwarding: _DISPATCHABLE_BARE_NODE_METRICS in tests/graph_features_test.py is derived from
GRAPH_NODE_METRICS by signature introspection, and a consistency test checks each registered wrapper’s
signature against _NON_DISPATCHABLE_METRICS.
- hiveplotlib.graph_features.compute_graph_metrics(graph: Graph, *, node_metrics: str | Sequence[str] | None = None, edge_metrics: str | Sequence[str] | None = None, node_metric_kwargs: dict[str, dict] | None = None, edge_metric_kwargs: dict[str, dict] | None = None, graph_metric_backend: str | None = None, node_metric_rename: dict[str, str] | None = None, edge_metric_rename: dict[str, str] | None = None, target_nodes: NodeCollection | None = None, target_edges: Edges | None = None, source_attribute_name: str = '_hiveplotlib_source', _from_hive_plot: bool = False) Tuple[NodeCollection | None, Edges | None]#
Compute graph metrics from Networkx graph.
The metrics are attached as columns to new
hiveplotlib.NodeCollectionandhiveplotlib.Edgesinstances.Metric names are validated against
GRAPH_NODE_METRICSandGRAPH_EDGE_METRICS. Per-metric**kwargsmay be forwarded vianode_metric_kwargs/edge_metric_kwargs(keyed by metric name). Per-metric column-name overrides may be supplied vianode_metric_rename/edge_metric_rename(also keyed by metric name) to resolve collisions with columns that already exist on the targets.Collision handling: if a resolved column name (after applying any rename) already exists in the target’s underlying DataFrame(s), a
ValueErroris raised pointing the user toward the rename keyword. No silent overwrite, no auto-suffix.If
target_edgeshas multiple tags, each edge-metric column is attached to every tag’s DataFrame.The original
target_nodesandtarget_edgesare not mutated; this function returns fresh instances built from.copy().graph,target_nodes, andtarget_edgesmust describe the same network: graph node IDs must match values in thetarget_nodesunique-ID column, and graph edges must correspond to rows intarget_edges. Consistency is not validated; mismatches will silently produceNaNvalues in the attached columns. The simplest way to guarantee consistency is to buildgraphfromtarget_nodesandtarget_edgesviahiveplotlib.converters.nodes_edges_to_networkx().Note
If the supplied
graphmerged parallel or reciprocal edges (e.g. a simplenetworkx.Graph/networkx.DiGraph, where duplicate or reciprocal(a, b)/(b, a)rows collapse last-write-wins), a metric given an edgeweightreflects only the surviving edge’s weight. This is harmless for unweighted or structural metrics. Supplying a multigraph keeps both edges only for metrics that accept multigraphs; metrics that require a simple graph (e.g.onion_layers) reject the multigraph, so for those, pre-aggregate the reciprocal weights into a single edge before building the graph.- ..note::
This function does not infer graph type: it validates the requested metric set against the already-built
graphyou pass and leaves you in control of that graph. Graph-type inference (e.g. quietly building an undirected graph when you request onlytriangles) is ahiveplotlib.HivePlot/hiveplotlib.HivePlotMatrixconstruction-time convenience, since those classes build the internal graph for you. Calling this function directly means picking the right graph type yourself.
- Parameters:
graph –
networkxgraph from which to compute metrics.node_metrics – a single node-metric string name or a sequence of names to compute. Each must be a key in
GRAPH_NODE_METRICS. DefaultNoneskips node-metric computation.edge_metrics – a single edge-metric string name or a sequence of names to compute. Each must be a key in
GRAPH_EDGE_METRICS. DefaultNoneskips edge-metric computation.node_metric_kwargs – per-metric
**kwargsforwarded to the underlying wrapper, keyed by metric name."backend"is a reserved key: instead of being forwarded to the wrapper, it overridesgraph_metric_backendfor that one metric (and"backend": Noneopts the metric back to default networkx under a globalgraph_metric_backend). Other keys are limited to what each wrapper’s docstring enumerates;degree,in_degree, andout_degreeaccept no keyword arguments at all and will raiseTypeErrorif any other key is supplied for them.edge_metric_kwargs – same as
node_metric_kwargsbut for edge metrics, including the reserved"backend"key.graph_metric_backend – name of a
networkxdispatchable backend (e.g."parallel", registered by thenx-parallelpackage) on which to compute the requested metrics, requiringnetworkx>=3.2. DefaultNonecomputes everything on default networkx. Backends register under names that differ from their pip package names (nx-parallelregisters as"parallel",nx-cugraphas"cugraph"). A metric the backend does not implement falls back to default networkx.degree,in_degree, andout_degreeare direct structural reads of the graph, so backend dispatch does not apply to them (silently skipped, with identical results).node_metric_rename – per-metric override mapping from metric name to target column name on the resulting
hiveplotlib.NodeCollection.edge_metric_rename – same as
node_metric_renamebut for edge metrics.target_nodes – existing
hiveplotlib.NodeCollectionwhose copy is returned with the requested node metrics attached. Required whennode_metricsis provided.target_edges – existing
hiveplotlib.Edgeswhose copy is returned with the requested edge metrics attached to every tag. Required whenedge_metricsis provided.source_attribute_name – edge-attribute name under which to find the
(tag, row_index)source-row identifier whengraphis a multigraph andedge_metricsare requested. Default"_hiveplotlib_source"matches the value thathiveplotlib.converters.nodes_edges_to_networkx()writes when its ownsource_attribute_nameis enabled. Multigraph edge-metric computation requires this annotation to line up metrics for repeated edge rows back to individual rows; without it, aNotImplementedErroris raised. Ignored whengraphis a simple graph (the(from, to)pair alone is unique)._from_hive_plot – internal use only. Set automatically by
hiveplotlib.HivePlot/hiveplotlib.HivePlotMatrixto switch the graph-type conflict error-message resolution text to reference the differentgraph_directed/graph_multigraphkwargs they expose. Direct callers should leave this at its default.
- Returns:
a 2-tuple
(new_nodes, new_edges).new_nodesis a freshhiveplotlib.NodeCollectionifnode_metricswas provided, elseNone.new_edgesis a freshhiveplotlib.Edgesifedge_metricswas provided, elseNone.- Raises:
ValueError – if
node_metricsis provided withouttarget_nodesor ifedge_metricsis provided withouttarget_edges.ValueError – if any requested metric name is not in the master dict.
ValueError – if the combined node + edge requested set holds a directedness standoff, where one requested metric needs a directed graph and another needs an undirected graph (the two share the one internal graph, so the conflict is caught across the node/edge boundary too). Raised up front, before any metric runs, so nothing is computed and thrown away. The resolution is to split into two calls, each built against its OWN graph of the satisfying type (a directed graph for the directed-required metrics, an undirected graph for the others), then chain the returned nodes/edges. A different metric list against the same graph is not enough.
ValueError – if the already-built
graphis a multigraph and a requested metric rejects multigraphs. Raised up front, before any metric runs, so nothing is computed and thrown away. Rebuild the source graph as a non-multigraph (e.g.multigraph=Falsewhen building it) to compute that metric.ValueError – if a resolved column name collides with an existing column on the target.
TypeError – if
node_metric_kwargssupplies any key other than the reserved"backend"fordegree,in_degree, orout_degree, which accept no keyword arguments.InvalidGraphMetricBackendError – if any requested backend name (
graph_metric_backendor a per-metric"backend"entry) is not an installednetworkxdispatchable backend, if a per-metric"backend"entry targetsdegree/in_degree/out_degree(direct structural reads; backend dispatch does not apply), or if a backend is requested on anetworkxversion without the dispatch machinery (networkx<3.2). Raised up front, before any metric runs. Explicit per-metric"backend": Noneopt-outs are always valid.NotImplementedError – if
edge_metricsare requested on a multigraph whose edges lack thesource_attribute_nameannotation. Build the multigraph viahiveplotlib.converters.nodes_edges_to_networkx()withsource_attribute_nameset to enable per-row metric mapping even with repeats.