Unexpected values in NetworkX to_numpy_array output for parallel edges
0 reputation · 16 Nov 2023, 04:23 UTC
0 reputation · 16 Nov 2023, 04:23 UTC
When converting a NetworkX MultiGraph or MultiDiGraph that contains parallel edges to a NumPy array using to_numpy_array with a weight attribute, the resulting matrix may show values that do not match any single edge weight.
The function’s documentation does not state how it combines the weights of parallel edges, so users cannot determine whether the values represent a sum, maximum, first‑encountered weight, or another aggregation.
What aggregation rule does to_numpy_array currently apply to parallel edges?
Is this rule documented or made configurable through a parameter?
Should downstream numeric analyses assume the current behavior, or should users verify the result by alternative means?
31775 reputation · 16 Nov 2023, 11:41 UTC
to_numpy_array sums the weights of parallel edges by default when a weight attribute is provided for MultiGraph or MultiDiGraph.multigraph_weight parameter accepts a callable (sum, min, max, or a custom function) to control aggregation. The default is sum. This parameter appears in the function signature and docstring but is easy to miss in narrative tutorials.multigraph_weight to make intent clear and reproducible.For a MultiGraph with two parallel edges between nodes 0 and 1 carrying weights 2 and 5:
import networkx as nx
import numpy as np
G = nx.MultiGraph()
G.add_edge(0, 1, weight=2)
G.add_edge(0, 1, weight=5)
# Default (sum)
A = nx.to_numpy_array(G, weight='weight')
print(A[0, 1]) # 7.0
# Explicit max
A_max = nx.to_numpy_array(G, weight='weight', multigraph_weight=max)
print(A_max[0, 1]) # 5.0
# Explicit min
A_min = nx.to_numpy_array(G, weight='weight', multigraph_weight=min)
print(A_min[0, 1]) # 2.0
The same logic applies to MultiDiGraph (directed parallel edges are aggregated per ordered node pair). For Graph/DiGraph (no parallel edges), weight simply retrieves the single edge's attribute value.
MultiGraph with two parallel edges of known distinct weights.to_numpy_array(G, weight='weight') and confirm the matrix entry equals the sum.multigraph_weight=max and multigraph_weight=min to verify the parameter works.nx.__version__ (requires ≥2.5 for multigraph_weight).multigraph_weight and always sum; code relying on the default may behave differently across environments.1 unless overridden via the weight parameter's default argument.Always specify multigraph_weight explicitly in production code (e.g., multigraph_weight=sum for the documented default). Add a unit test that validates the aggregation against a small fixture graph to guard against version changes.
Use comments to ask for clarification. Post a solution as an answer.
No question comments on this page.