Weighted shortest path limits: handling missing weights and negative edges in NetworkX
0 reputation · 16 Oct 2021, 04:48 UTC
When using NetworkX’s weighted shortest‑path functions, the caller must decide which algorithm to invoke and how to treat edges that lack the requested weight attribute. Dijkstra‑based routines (e.g., dijkstra_path) assume all weights are non‑negative and will silently produce incorrect results if a negative weight is present. Bellman‑Ford routines (e.g., bellman_ford_path) correctly handle negative weights and raise NetworkXUnbounded when a reachable negative cycle exists, but they are not selected automatically. For multigraphs the library collapses parallel edges to the minimum weight of the requested attribute, and edges missing that attribute default to a weight of 1, which can turn an intended weighted graph into an unweighted one without notice.
Given these behaviors, the designer must weigh the trade‑offs between explicit caller control and possible automatic safeguards.
Should NetworkX raise an error when any edge lacks the requested weight attribute? Should it automatically switch to Bellman‑Ford when a negative weight is detected? Should it document and enforce a explicit default‑weight policy for missing attributes and parallel edges?