Skip to content

Commit

Permalink
Add example for cycle detection (networkx#6560)
Browse files Browse the repository at this point in the history
* Fix negative edge cycle function raising exception for empty graph and added relevant test function

* Unresolved change

* Added example script to visualize GOT network

* Added example script to visualize cycle detection

* Deleted got.py

* Minor tweaks to example.

* Update examples/algorithms/plot_cycle_detection.py

---------

Co-authored-by: Ross Barnowski <rossbar@caltech.edu>
Co-authored-by: Dan Schult <dschult@colgate.edu>
  • Loading branch information
3 people authored and cvanelteren committed Apr 22, 2024
1 parent c349f30 commit 7f44eb6
Showing 1 changed file with 29 additions and 0 deletions.
29 changes: 29 additions & 0 deletions examples/algorithms/plot_cycle_detection.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,29 @@
"""
===============
Cycle Detection
===============
This example demonstrates the use of ``nx.find_cycle`` to find a single,
arbitrary cycle in a graph.
Other functions like ``nx.simple_cycles`` and ``nx.cycle_basis`` can be used to
find all cycles or a cycle basis.
"""
import networkx as nx
import matplotlib.pyplot as plt

# Create a simple directed graph with a cycle
G = nx.DiGraph([(1, 2), (2, 3), (3, 4), (4, 2), (3, 5), (3, 2), (1, 5)])

# Draw the graph
pos = nx.spring_layout(G, seed=8020)
nx.draw(G, pos, with_labels=True)

# The `orientation` parameter can be used to determine how directed edges are
# treated and the reporting of edge direction in the cycle
cycle = nx.find_cycle(G, orientation="original")
print(cycle)

# Highlight the cycle in red
nx.draw_networkx_edges(G, pos, edgelist=cycle, edge_color="r", width=2)
plt.show()

0 comments on commit 7f44eb6

Please sign in to comment.