find_negative_cycle(G, source, weight='weight')
Bellman-Ford is used to find shortest_paths. That algorithm stops if there exists a negative cycle. This algorithm picks up from there and returns the found negative cycle.
The cycle consists of a list of nodes in the cycle order. The last node equals the first to make it a cycle. You can look up the edge weights in the original graph. In the case of multigraphs the relevant edge is the minimal weight edge between the nodes in the 2-tuple.
If the graph has no negative cycle, a NetworkXError is raised.
The search for the negative cycle will start from this node.
If this is a string, then edge weights will be accessed via the edge attribute with this key (that is, the weight of the edge joining u
to :None:None:`v`
will be G.edges[u, v][weight]
). If no such edge attribute exists, the weight of the edge is assumed to be one.
If this is a function, the weight of an edge is the value returned by the function. The function must accept exactly three positional arguments: the two endpoints of an edge and the dictionary of edge attributes for that edge. The function must return a number.
If no negative cycle is found.
A list of nodes in the order of the cycle found. The last node equals the first to indicate a cycle.
Returns a cycle with negative total weight if it exists.
>>> G = nx.DiGraph()See :
... G.add_weighted_edges_from([(0, 1, 2), (1, 2, 2), (2, 0, 1), (1, 4, 2), (4, 0, -5)])
... nx.find_negative_cycle(G, 0) [4, 0, 1, 4]
The following pages refer to to this document either explicitly or contain code examples using this.
networkx.algorithms.shortest_paths.weighted.bellman_ford_predecessor_and_distance
networkx.algorithms.shortest_paths.weighted.find_negative_cycle
Hover to see nodes names; edges to Self not shown, Caped at 50 nodes.
Using a canvas is more power efficient and can get hundred of nodes ; but does not allow hyperlinks; , arrows or text (beyond on hover)
SVG is more flexible but power hungry; and does not scale well to 50 + nodes.
All aboves nodes referred to, (or are referred from) current nodes; Edges from Self to other have been omitted (or all nodes would be connected to the central node "self" which is not useful). Nodes are colored by the library they belong to, and scaled with the number of references pointing them