### Basic rustworkx Usage Example Source: https://github.com/qiskit/rustworkx/blob/main/docs/source/install.rst Demonstrates how to create a graph, add nodes and edges, and calculate the shortest path using Dijkstra's algorithm. Ensure rustworkx is installed before running. ```python import rustworkx as rx graph = rx.PyGraph() # Each time add node is called, it returns a new node index a = graph.add_node("A") b = graph.add_node("B") c = graph.add_node("C") # add_edges_from takes tuples of node indices and weights, # and returns edge indices graph.add_edges_from([(a, b, 1.5), (a, c, 5.0), (b, c, 2.5)]) # Returns the path A -> B -> C rx.dijkstra_shortest_paths(graph, a, c, weight_fn=float) ``` -------------------------------- ### Manually install setuptools-rust Source: https://github.com/qiskit/rustworkx/blob/main/docs/source/install.rst If you encounter errors related to 'setuptools-rust' when building from source, you may need to install it manually or upgrade pip. This command installs setuptools-rust. ```bash pip install setuptools-rust ``` -------------------------------- ### Install Rustworkx with Pip Source: https://github.com/qiskit/rustworkx/blob/main/README.md Installs a precompiled version of rustworkx on supported platforms. This is the simplest installation method. ```bash pip install rustworkx ``` -------------------------------- ### Install Nox for Testing Source: https://github.com/qiskit/rustworkx/blob/main/CONTRIBUTING.md Install Nox with the 'uv' extra for managing virtual environments and dependencies during testing. ```bash pip install -U "nox[uv]" ``` -------------------------------- ### Install Reno for Release Notes Source: https://github.com/qiskit/rustworkx/blob/main/CONTRIBUTING.md Install the reno tool, which is used for managing release notes, using pip. ```bash pip install -U reno ``` -------------------------------- ### Install rustworkx from Source with Path Source: https://github.com/qiskit/rustworkx/blob/main/README.md Alternatively, install rustworkx from source by specifying the repository root path. This is useful if you are not in the root directory. ```bash pip install $PATH_TO_REPO_ROOT ``` -------------------------------- ### Example Release Note Structure Source: https://github.com/qiskit/rustworkx/blob/main/CONTRIBUTING.md An example of a release note file written in YAML format. It includes sections for features and deprecations, demonstrating how to describe changes and provide code examples. ```yaml features: - | Added a new function, :func:`~rustworkx.foo` that adds support for doing something to :class:`~rustworkx.PyDiGraph` objects. - | The :class:`~rustworkx.PyDiGraph` class has a new method :meth:`~rustworkx.PyDiGraph.foo`. This is the equivalent of calling the :func:`~rustworkx.foo` function to do something to your :class:`~rustworkx.PyDiGraph` object, but provides the convenience of running it natively on an object. For example:: from rustworkx import PyDiGraph g = PyDiGraph. g.foo() deprecations: - | The ``rustworkx.bar`` function has been deprecated and will be removed in a future release. It has been superseded by the :meth:`~rustworkx.PyDiGraph.foo` method and :func:`~rustworkx.foo` function which provides similar functionality but with more accurate results and better performance. You should update your calls ``rustworkx.bar()`` calls to use ``rustworkx.foo()`` instead. ``` -------------------------------- ### Install cargo-fuzz Source: https://github.com/qiskit/rustworkx/blob/main/CONTRIBUTING.md Install the cargo-fuzz tool for fuzz testing rustworkx. ```bash cargo install cargo-fuzz ``` -------------------------------- ### Install rustworkx from Source Source: https://github.com/qiskit/rustworkx/blob/main/README.md Install rustworkx into your Python environment using pip after cloning the repository. Ensure you are in the repository's root directory. ```bash pip install . ``` -------------------------------- ### Install Rustworkx with Graphviz Support Source: https://github.com/qiskit/rustworkx/blob/main/README.md Installs rustworkx along with optional dependencies for the `rustworkx.visualization.graphviz_drawer` function, which requires Pillow and Graphviz. ```bash pip install 'rustworkx[graphviz]' ``` -------------------------------- ### Install Rustworkx with All Optional Dependencies Source: https://github.com/qiskit/rustworkx/blob/main/README.md Installs rustworkx with all available optional Python dependencies, including those for visualization modules. ```bash pip install 'rustworkx[all]' ``` -------------------------------- ### Install Rustworkx with Matplotlib Support Source: https://github.com/qiskit/rustworkx/blob/main/README.md Installs rustworkx along with optional dependencies for the `rustworkx.visualization.mpl_draw` function, which requires matplotlib. ```bash pip install 'rustworkx[mpl]' ``` -------------------------------- ### Graph Attributes Example Source: https://github.com/qiskit/rustworkx/blob/main/docs/source/tutorial/introduction.rst Illustrates setting and modifying graph attributes using a dictionary or a custom class. ```python graph = rx.PyGraph(attrs=dict(day="Friday")) graph.attrs['day'] = "Monday" ``` ```python class Day: def __init__(self, day): self.day = day graph = rx.PyGraph(attrs=Day("Friday")) graph.attrs = Day("Monday") ``` -------------------------------- ### Build Documentation with Nox Source: https://github.com/qiskit/rustworkx/blob/main/CONTRIBUTING.md Build the project's HTML documentation using Nox. This command compiles Rustworkx, installs Python dependencies, and generates documentation in an isolated environment. ```bash nox -e docs ``` -------------------------------- ### Install rustworkx with Conda Source: https://github.com/qiskit/rustworkx/blob/main/README.md Use this command to install rustworkx from the conda-forge channel. This is useful for users within the conda ecosystem. ```bash conda install -c conda-forge rustworkx ``` -------------------------------- ### Create and Draw a Directed Path Graph Source: https://github.com/qiskit/rustworkx/blob/main/docs/source/tutorial/dags.rst Creates a 5-node directed path graph and visualizes it using matplotlib. This serves as a basic example of a directed graph. ```python import rustworkx as rx from rustworkx.visualization import mpl_draw path_graph = rx.generators.directed_path_graph(5) mpl_draw(path_graph) ``` -------------------------------- ### Serialize and Deserialize Graphs using JSON and GraphML Source: https://context7.com/qiskit/rustworkx/llms.txt Demonstrates how to serialize graphs to and deserialize from node-link JSON format, and how to read/write graphs using the GraphML XML format. Includes examples for both directed and undirected graphs. ```python import rustworkx as rx import json, tempfile, os g = rx.PyGraph() g.add_nodes_from(["alice", "bob", "carol"]) g.add_edges_from([(0, 1, "friends"), (1, 2, "colleagues")]) # Serialize to node-link JSON string json_str = rx.node_link_json(g, node_attrs=lambda n: {"name": n}, edge_attrs=lambda e: {"rel": e}) data = json.loads(json_str) print(data["nodes"]) # [{"id":0,"name":"alice"}, ...] # Deserialize from JSON string g2 = rx.parse_node_link_json(json_str, node_attrs=lambda d: d["name"], edge_attrs=lambda d: d["rel"]) print(g2.nodes()) # Save/load via file with tempfile.NamedTemporaryFile(suffix=".json", delete=False, mode="w") as f: f.write(json_str) json_path = f.name g3 = rx.from_node_link_json_file(json_path, node_attrs=lambda d: d["name"], edge_attrs=lambda d: d["rel"]) os.unlink(json_path) # GraphML serialization dg = rx.PyDiGraph() dg.add_nodes_from([{"label": "A"}, {"label": "B"}]) dg.add_edge(0, 1, {"weight": 1.5}) with tempfile.NamedTemporaryFile(suffix=".graphml", delete=False) as f: gml_path = f.name rx.write_graphml(dg, gml_path, node_attrs=lambda n: {"label": n["label"]}, edge_attrs=lambda e: {"weight": str(e["weight"])}) # Read back graphs = rx.read_graphml(gml_path) os.unlink(gml_path) print(graphs[0].nodes()) ``` -------------------------------- ### Create and Draw a Directed Cycle Graph Source: https://github.com/qiskit/rustworkx/blob/main/docs/source/tutorial/dags.rst Generates a directed cycle graph and visualizes it. This example illustrates a graph containing a cycle, which is not acyclic. ```python cycle_graph = rx.generators.directed_cycle_graph(5) mpl_draw(cycle_graph) ``` -------------------------------- ### Build rustworkx in Develop Mode Source: https://github.com/qiskit/rustworkx/blob/main/README.md Set the SETUPTOOLS_RUST_CARGO_PROFILE environment variable to 'dev' to build and install rustworkx in debug mode with optimizations disabled and debuginfo included. This is helpful for debugging. ```bash export SETUPTOOLS_RUST_CARGO_PROFILE="dev" pip install . ``` -------------------------------- ### Calculating All-Pairs Shortest Paths with Edge Weights in NetworkX Source: https://github.com/qiskit/rustworkx/blob/main/docs/source/networkx.rst Example of using NetworkX's floyd_warshall_numpy function with edge weights specified by an attribute name. ```python import networkx as nx graph = nx.MultiDiGraph() graph.add_edges_from([(0, 1, {'weight': 1}), (0, 2, {'weight': 2}), (1, 3, {'weight': 2}), (3, 0, {'weight': 3})]) dist_matrix = nx.floyd_warshall_numpy(graph, weight='weight') ``` -------------------------------- ### Generate Random Graphs using Classic Models Source: https://context7.com/qiskit/rustworkx/llms.txt Provides examples for generating random graphs using the Erdős–Rényi (G(n,p) and G(n,m)), Barabási–Albert preferential attachment, stochastic block model, random bipartite, and random geometric graph models. ```python import rustworkx as rx # Erdős–Rényi G(n,p): each edge included independently with probability p gnp_undi = rx.undirected_gnp_random_graph(n=100, p=0.05, seed=0) gnp_di = rx.directed_gnp_random_graph(n=50, p=0.1, seed=0) # G(n,m): exactly m edges chosen uniformly at random gnm = rx.undirected_gnm_random_graph(n=20, m=30, seed=0) # Barabási–Albert preferential attachment ba = rx.barabasi_albert_graph(n=100, m=3, seed=42) print(f"BA graph: {len(ba)} nodes, {ba.num_edges()} edges") # Stochastic block model: community structure blocks = [10, 10, 10] prob_mat = [[0.9, 0.1, 0.1], [0.1, 0.9, 0.1], [0.1, 0.1, 0.9]] sbm = rx.undirected_sbm_random_graph(blocks, prob_mat, seed=0) # Random bipartite graph bip = rx.undirected_random_bipartite_graph(10, 10, p=0.4, seed=0) # Random geometric graph (nodes in unit square, edges by proximity) geo = rx.random_geometric_graph(n=50, radius=0.25, seed=7) ``` -------------------------------- ### Generate Various Graph Types in Rustworkx Source: https://context7.com/qiskit/rustworkx/llms.txt Demonstrates the generation of specific graph structures like generalized Petersen graphs, lollipop graphs, full r-ary trees, and the classic karate club graph. Also includes examples of random graph generators. ```python petersen = rx.generators.generalized_petersen_graph(5, 2) lollipop = rx.generators.lollipop_graph(4, 3) tree = rx.generators.full_rary_tree(branching=3, num_nodes=13) karate = rx.generators.karate_club_graph() print(f"Karate club: {len(karate)} nodes, {karate.num_edges()} edges") gnp = rx.undirected_gnp_random_graph(n=20, p=0.3, seed=42) ba = rx.barabasi_albert_graph(n=50, m=2, seed=42) # preferential attachment geo = rx.random_geometric_graph(n=30, radius=0.3, seed=42) ``` -------------------------------- ### Render Graphs with Graphviz Source: https://context7.com/qiskit/rustworkx/llms.txt Render graphs using Graphviz. This requires Graphviz and Pillow to be installed. You can customize node and edge attributes using provided functions. ```python import rustworkx as rx from rustworkx.visualization import graphviz_draw heavy = rx.generators.heavy_hex_graph(5) for node in heavy.node_indices(): heavy[node] = node # set payload to index for labeling def node_style(node): return { "label": str(node), "style": "filled", "fillcolor": "lightblue" if node % 2 == 0 else "lightyellow", "shape": "circle", } def edge_style(edge): return {"color": "gray"} img = graphviz_draw(heavy, node_attr_fn=node_style, edge_attr_fn=edge_style, method="neato") # img is a PIL Image object img.save("heavy_hex.png") ``` -------------------------------- ### Build Documentation Faster with Nox Source: https://github.com/qiskit/rustworkx/blob/main/CONTRIBUTING.md Build the documentation using Nox and leverage all available CPUs for a faster build process. The output will be in `docs/build/html`. ```bash nox -e docs -- -j auto ``` -------------------------------- ### Build and Open rustworkx-core Documentation Source: https://github.com/qiskit/rustworkx/blob/main/CONTRIBUTING.md Generate documentation for rustworkx-core and automatically open it in your default web browser. This is a convenient way to preview the documentation locally. ```bash cargo doc -p rustworkx-core --open ``` -------------------------------- ### Create and Populate a PyGraph Source: https://github.com/qiskit/rustworkx/blob/main/docs/source/tutorial/introduction.rst Demonstrates creating a PyGraph, adding nodes and edges with custom data objects, and populating index attributes. ```python import rustworkx as rx class GraphNode: def __init__(self, value): self.value = value self.index = None def __repr__(self): return f"GraphNode: {self.value} @ index: {self.index}" class GraphEdge: def __init__(self, value): self.value = value self.index = None def __repr__(self): return f"GraphEdge: {self.value} @ index: {self.index}" graph = rx.PyGraph() graph.add_nodes_from([GraphNode(i) for i in range(5)]) graph.add_edges_from([(i, i + 1, GraphEdge(i)) for i in range(4)]) # Populate index attribute in GraphNode objects for index in graph.node_indices(): graph[index].index = index # Populate index attribute in GraphEdge objects for index, data in graph.edge_index_map().items(): data[2].index = index print("Nodes:") for node in graph.nodes(): print(node) print("Edges:") for edge in graph.edges(): print(edge) ``` -------------------------------- ### InvalidMapping Source: https://github.com/qiskit/rustworkx/blob/main/docs/source/api/exceptions.rst Raised when an invalid mapping is provided, for example, when mapping nodes to values. ```APIDOC ## rustworkx.InvalidMapping ### Description This exception indicates that a mapping provided to a function is invalid. This commonly occurs when mapping nodes to specific values or attributes, and the mapping does not conform to expected structures or constraints. ### Usage Catch this exception to validate and correct mapping inputs. ```python try: # Use a mapping in a graph operation result = graph.map_nodes(mapping) except rustworkx.InvalidMapping: print("The provided node mapping is invalid.") ``` ``` -------------------------------- ### Create a New Release Note with Reno Source: https://github.com/qiskit/rustworkx/blob/main/CONTRIBUTING.md Generate a new release note file using the 'reno new' command. Replace 'short-description-string' with a brief, space-free description of the changes. ```bash reno new short-description-string ``` -------------------------------- ### BFS Search (Graph) Source: https://github.com/qiskit/rustworkx/blob/main/docs/source/sources.txt Performs a Breadth-First Search starting from a given node. ```APIDOC ## graph_bfs_search ### Description Perform a Breadth-First Search starting from a given node. ### Method `rustworkx.graph_bfs_search(graph, start_node, depth_limit=None)` ### Parameters - **graph** (Graph) - The input graph. - **start_node** (node) - The node to start the BFS from. - **depth_limit** (int, optional) - The maximum depth to search. If None, search all reachable nodes. ### Returns - **list** - A list of nodes visited in BFS order. ``` -------------------------------- ### Digraph BFS Search Source: https://github.com/qiskit/rustworkx/blob/main/docs/source/sources.txt Performs a Breadth-First Search starting from a given node in a directed graph. ```APIDOC ## digraph_bfs_search ### Description Perform a Breadth-First Search starting from a given node in a directed graph. ### Method `rustworkx.digraph_bfs_search(graph, start_node, depth_limit=None)` ### Parameters - **graph** (DiGraph) - The input directed graph. - **start_node** (node) - The node to start the BFS from. - **depth_limit** (int, optional) - The maximum depth to search. If None, search all reachable nodes. ### Returns - **list** - A list of nodes visited in BFS order. ``` -------------------------------- ### Format Rust Code with rustfmt Source: https://github.com/qiskit/rustworkx/blob/main/CONTRIBUTING.md Run this command to automatically format your Rust code to match the project's style guidelines. CI jobs check for adherence to this style. ```bash cargo fmt ``` -------------------------------- ### Import rustworkx Source: https://github.com/qiskit/rustworkx/blob/main/docs/source/tutorial/introduction.rst Import the rustworkx library and alias it as 'rx' for convenience. This is a common convention. ```python import rustworkx as rx ``` -------------------------------- ### Get node and edge indices Source: https://github.com/qiskit/rustworkx/blob/main/docs/source/tutorial/introduction.rst Retrieve lists of all node indices and edge indices currently in the graph. These indices are used to reference graph elements. ```python node_indices = G.node_indices() edge_indices = G.edge_indices() print(node_indices) print(edge_indices) ``` -------------------------------- ### Upgrade pip Source: https://github.com/qiskit/rustworkx/blob/main/docs/source/install.rst If you encounter errors related to 'setuptools-rust' when building from source, you may need to upgrade pip. This command upgrades pip to the latest version. ```bash pip install -U pip ``` -------------------------------- ### Generate Specific Release Notes Source: https://github.com/qiskit/rustworkx/blob/main/CONTRIBUTING.md View release notes for a specific version after it has been tagged. This command helps in checking individual release notes. ```bash reno report --version 0.8.0 ``` -------------------------------- ### Render Graphs with Matplotlib Source: https://context7.com/qiskit/rustworkx/llms.txt Render graphs using Matplotlib. You can customize node colors, sizes, and use different layout algorithms for visualization. Ensure Matplotlib is installed. ```python import rustworkx as rx from rustworkx.visualization import mpl_draw import matplotlib.pyplot as plt g = rx.generators.generalized_petersen_graph(5, 2) # --- matplotlib rendering --- fig, axes = plt.subplots(1, 2, figsize=(12, 5)) # Default spring layout mpl_draw(g, with_labels=True, ax=axes[0]) # Custom colors and sizes node_colors = ["red" if i < 5 else "blue" for i in g.node_indices()] mpl_draw(g, node_color=node_colors, node_size=500, pos=rx.circular_layout(g), with_labels=True, ax=axes[1]) plt.tight_layout() plt.show() ``` -------------------------------- ### Read Graph from Edge List File Source: https://github.com/qiskit/rustworkx/blob/main/docs/source/tutorial/introduction.rst Demonstrates creating a graph by reading an edge list from a temporary file. ```python import tempfile with tempfile.NamedTemporaryFile('wt') as fd: path = fd.name fd.write('0 1\n') fd.write('0 2\n') fd.write('0 3\n') fd.write('1 2\n') fd.write('2 3\n') fd.flush() graph = rx.PyGraph.read_edge_list(path) mpl_draw(graph) ``` -------------------------------- ### Get Edge Index Map Source: https://github.com/qiskit/rustworkx/blob/main/docs/source/tutorial/introduction.rst Obtain a mapping of all edge indices to their corresponding endpoints and data payloads. This is a helper method as edges do not implement the mapping protocol directly. ```python print(G.edge_index_map()) ``` -------------------------------- ### Clone rustworkx Repository Source: https://github.com/qiskit/rustworkx/blob/main/README.md Clone the rustworkx project locally to begin building from source. This is the first step in the source build process. ```bash git clone https://github.com/Qiskit/rustworkx.git ``` -------------------------------- ### ProductNodeMap Source: https://github.com/qiskit/rustworkx/blob/main/docs/source/api/custom_return_types.rst A mapping for product nodes. ```APIDOC ## ProductNodeMap ### Description A mapping for product nodes. ### Usage This is a return type and not directly callable. ``` -------------------------------- ### Release Note Linking to GitHub Issues Source: https://github.com/qiskit/rustworkx/blob/main/CONTRIBUTING.md Example of how to link to a GitHub issue within a release note. Use an inline link format where the issue number is the link text. ```yaml fixes: - | Fixes a race condition in the function ``foo()``. Refer to `#12345 `__ for more details. ``` -------------------------------- ### A* Heuristic Search Source: https://context7.com/qiskit/rustworkx/llms.txt Finds the shortest path from a source to a goal using a user-supplied heuristic function to guide the search. The heuristic must be admissible (never overestimate the cost to the goal). ```python import rustworkx as rx import math # Build a 2D grid graph with positions g = rx.PyGraph() positions = {} for row in range(4): for col in range(4): idx = g.add_node((row, col)) positions[idx] = (row, col) if col > 0: g.add_edge(idx - 1, idx, 1.0) if row > 0: g.add_edge(idx - 4, idx, 1.0) start = 0 # (0,0) goal_pos = (3, 3) def goal_fn(node): return node == goal_pos def edge_cost_fn(weight): return weight def heuristic(node): return math.sqrt((node[0] - goal_pos[0])**2 + (node[1] - goal_pos[1])**2) path = rx.astar_shortest_path(g, start, goal_fn, edge_cost_fn, heuristic) print(list(path)) # node indices along the shortest path ``` -------------------------------- ### Initializing PyGraph from Weighted Edge List (3-Tuples) Source: https://github.com/qiskit/rustworkx/blob/main/docs/source/networkx.rst When initializing with weights, Rustworkx expects a list of 3-tuples (source, target, weight), differing from NetworkX's flexibility. ```python import rustworkx as rx graph = rx.PyGraph() graph.extend_from_edge_list([(0, 1, 2), (1, 0, 1)]) ``` -------------------------------- ### Build Fuzz Targets Source: https://github.com/qiskit/rustworkx/blob/main/CONTRIBUTING.md Build the fuzzing targets for rustworkx using Cargo. ```bash cargo fuzz build ``` -------------------------------- ### Convert NetworkX Graphs to Rustworkx Source: https://context7.com/qiskit/rustworkx/llms.txt Convert NetworkX graphs (Graph, DiGraph, MultiGraph, MultiDiGraph) to their rustworkx equivalents. This function preserves node and edge attributes by default. Requires NetworkX to be installed. ```python import rustworkx as rx # Requires networkx to be installed: pip install networkx import networkx as nx # Build a NetworkX graph nx_g = nx.karate_club_graph() # Convert to rustworkx PyGraph (preserves node/edge attributes) rx_g = rx.networkx_converter(nx_g) print(type(rx_g)) # print(len(rx_g)) # 34 nodes print(rx_g.num_edges()) # 78 edges # With keep_attributes=True (default), node data is a dict of NX attributes print(rx_g[0]) # {"club": "Mr. Hi"} or similar # Directed graph nx_dg = nx.DiGraph() nx_dg.add_edges_from([(0,1,{"weight":2}),(1,2,{"weight":3})]) rx_dg = rx.networkx_converter(nx_dg) print(type(rx_dg)) # # Run rustworkx algorithms on converted graph centrality = rx.betweenness_centrality(rx_g, normalized=True) top = max(centrality.items(), key=lambda x: x[1]) print(f"Highest betweenness node: {top[0]}, score: {top[1]:.4f}") ``` -------------------------------- ### Rustworkx Source Tree Overview Source: https://github.com/qiskit/rustworkx/blob/main/CONTRIBUTING.md Provides a high-level view of the Rustworkx source code structure, highlighting key directories and files. ```text ├── src/ │ ├── lib.rs │ ├── tiny.rs │ ├── large/ │ │ ├── mod.rs │ │ ├── pure_rust_code.rs │ │ └── more_pure_rust_code.rs ``` -------------------------------- ### List Available Fuzz Targets Source: https://github.com/qiskit/rustworkx/blob/main/CONTRIBUTING.md List all available fuzzing targets that can be run with cargo-fuzz. ```bash cargo fuzz list ``` -------------------------------- ### Build rustworkx-core Documentation with Cargo Source: https://github.com/qiskit/rustworkx/blob/main/CONTRIBUTING.md Generate documentation for the rustworkx-core component using Cargo. The compiled documentation will be located in `target/doc/rustworkx_core`. ```bash cargo doc -p rustworkx-core ``` -------------------------------- ### Calculating All-Pairs Shortest Paths with Edge Weights in rustworkx (Direct Weight Payload) Source: https://github.com/qiskit/rustworkx/blob/main/docs/source/networkx.rst Shows a concise way to use rustworkx's digraph_floyd_warshall_numpy when the edge payload is the weight itself. ```python import rustworkx as rx graph = rx.PyDiGraph() graph.extend_from_weighted_edge_list( [(0, 1, 1), (0, 2, 2), (1, 3, 2), (3, 0, 3)]) dist_matrix = rx.digraph_floyd_warshall_numpy(graph, weight_fn=lambda edge: edge) ``` -------------------------------- ### Initializing PyGraph from Edge List (Tuples) Source: https://github.com/qiskit/rustworkx/blob/main/docs/source/networkx.rst Rustworkx requires a list of 2-tuples for initializing a graph from an edge list, whereas NetworkX can accept an iterator. ```python import rustworkx as rx graph = rx.PyGraph() graph.extend_from_edge_list([(0, 1), (1, 0)]) ``` -------------------------------- ### Calculate Shortest Path in Undirected Graph Source: https://github.com/qiskit/rustworkx/blob/main/README.md Illustrates how to create an undirected graph, add nodes and edges, and then calculate the shortest path between two nodes using Dijkstra's algorithm. Ensure the graph is initialized as `rustworkx.PyGraph()` for undirected graphs. ```python import rustworkx # Rustworkx's undirected graph type. graph = rustworkx.PyGraph() # Each time add node is called, it returns a new node index a = graph.add_node("A") b = graph.add_node("B") c = graph.add_node("C") # add_edges_from takes tuples of node indices and weights, # and returns edge indices graph.add_edges_from([(a, b, 1.5), (a, c, 5.0), (b, c, 2.5)]) # Returns the path A -> B -> C rustworkx.dijkstra_shortest_paths(graph, a, c, weight_fn=float) ``` -------------------------------- ### Run Subset of Tests with Nox Source: https://github.com/qiskit/rustworkx/blob/main/CONTRIBUTING.md Execute a subset of tests by providing a selection regex to Nox. Arguments for the test runner are passed after '--'. ```bash nox -e test -- dag ``` -------------------------------- ### Declaring and Importing New Modules in lib.rs Source: https://github.com/qiskit/rustworkx/blob/main/CONTRIBUTING.md Shows how to declare a new Rust module and import its contents into `lib.rs` for Python export. ```rust mod your_module; use your_module::*; ``` -------------------------------- ### Perform Graph Algebra Operations Source: https://context7.com/qiskit/rustworkx/llms.txt Illustrates graph operations including union, Cartesian product, tensor product, and complement. Also shows how to compute minimum spanning trees and Steiner trees on weighted graphs. ```python import rustworkx as rx g1 = rx.PyGraph() g1.extend_from_edge_list([(0,1),(1,2)]) g2 = rx.PyGraph() g2.extend_from_edge_list([(0,1),(1,2),(2,0)]) # Union: combine two graphs (nodes/edges optionally merged if equal weights) union_g = rx.union(g1, g2, merge_nodes=False, merge_edges=False) print(len(union_g), union_g.num_edges()) # 6 nodes, 5 edges # Cartesian product: G□H # Returns (product_graph, ProductNodeMap) product, node_map = rx.cartesian_product(g1, g2) print(len(product)) # 3 × 3 = 9 nodes # Tensor product: G × H tensor, tensor_map = rx.tensor_product(g1, g2) # Complement: edges become non-edges and vice versa comp = rx.complement(g1) # Minimum spanning tree (undirected) weighted = rx.PyGraph() weighted.extend_from_weighted_edge_list([ (0, 1, 4.0), (0, 2, 1.0), (1, 2, 2.0), (1, 3, 5.0), (2, 3, 8.0) ]) mst = rx.minimum_spanning_tree(weighted, weight_fn=float) print(mst.num_edges()) # 3 (n-1 edges for a spanning tree) mst_edges = rx.minimum_spanning_edges(weighted, weight_fn=float) print(list(mst_edges)) # [(src, tgt, weight), ...] # Steiner tree: minimum subtree spanning required nodes terminals = [0, 1, 3] stree = rx.steiner_tree(weighted, terminals, weight_fn=float) ``` -------------------------------- ### Exporting Python Functions in lib.rs Source: https://github.com/qiskit/rustworkx/blob/main/CONTRIBUTING.md Demonstrates how to export newly defined Rust functions to Python using `m.add_wrapped`. ```rust m.add_wrapped(wrap_pyfunction!(your_new_function))?; ``` -------------------------------- ### Adding Nodes and Edges in NetworkX Source: https://github.com/qiskit/rustworkx/blob/main/docs/source/networkx.rst Demonstrates how to add nodes and edges to a NetworkX MultiDiGraph using node names directly. ```python import networkx as nx graph = nx.MultiDiGraph() graph.add_node('my_node_a') graph.add_node('my_node_b') graph.add_edge('my_node_a', 'my_node_b') ``` -------------------------------- ### Test Type Annotations with Nox Source: https://github.com/qiskit/rustworkx/blob/main/CONTRIBUTING.md Run Nox to test the Python type annotations. This ensures that stub files (`.pyi`) correctly reflect the function signatures and types used in the library. ```bash nox -e stubs ``` -------------------------------- ### Run rustworkx-core Tests Source: https://github.com/qiskit/rustworkx/blob/main/CONTRIBUTING.md Execute all tests for the rustworkx-core workspace using Cargo. ```bash cargo test --workspace ``` -------------------------------- ### BFSVisitor Source: https://github.com/qiskit/rustworkx/blob/main/docs/source/sources.txt Provides a visitor pattern for Breadth-First Search (BFS) traversal of a graph. It allows users to hook into different stages of the traversal, such as visiting edges and vertices, and to control the search flow. ```APIDOC ## BFSVisitor ### Description A visitor class for Breadth-First Search (BFS) graph traversal. This class provides methods that are called at various points during the BFS algorithm, allowing for custom actions or modifications to the search process. ### Methods - **`tree_edge(u, v)`**: Called when an edge `(u, v)` is traversed as a tree edge. - **`non_tree_edge(u, v)`**: Called when an edge `(u, v)` is traversed as a non-tree edge. - **`gray_target_edge(u, v)`**: Called when an edge `(u, v)` is traversed where `v` is a gray node (currently being visited). - **`finish_vertex(v)`**: Called after all edges incident to vertex `v` have been explored. ### Usage To use `BFSVisitor`, you typically subclass it and override the methods you need to customize. Then, you pass an instance of your subclass to a BFS-related function (e.g., `rustworkx.bfs_visitor`). ``` -------------------------------- ### Custom BFS Visitor in Rustworkx Source: https://context7.com/qiskit/rustworkx/llms.txt Demonstrates how to create a custom visitor for BFS traversal to count visited nodes. Requires defining a class inheriting from visit.BFSVisitor. ```python class CountingBFSVisitor(visit.BFSVisitor): def __init__(self): self.count = 0 def discover_vertex(self, v): self.count += 1 visitor = CountingBFSVisitor() rx.bfs_search(g, [0], visitor) print(f"Visited {visitor.count} nodes") ``` -------------------------------- ### Generate Graphs using Generators and Operations Source: https://github.com/qiskit/rustworkx/blob/main/docs/source/tutorial/introduction.rst Shows how to create complex graphs using built-in generators like lollipop_graph and mesh_graph, and operations like cartesian_product. ```python lollipop_graph = rx.generators.lollipop_graph(4, 3) mesh_graph = rx.generators.mesh_graph(4) combined_graph = rx.cartesian_product(lollipop_graph, mesh_graph)[0] mpl_draw(combined_graph) ``` -------------------------------- ### Analyze Graph Connected Components and Degrees Source: https://github.com/qiskit/rustworkx/blob/main/docs/source/tutorial/introduction.rst Illustrates analyzing a graph by finding its connected components and calculating the degree of each node. ```python G = rx.PyGraph() G.extend_from_edge_list([(0, 1), (0, 2)]) new_node = G.add_node("spam") print(rx.connected_components(G)) degrees = {} for node in G.node_indices(): degrees[node] = G.degree(node) print(degrees) ``` ```python G.remove_node(new_node) ``` -------------------------------- ### AllPairsPathLengthMapping Source: https://github.com/qiskit/rustworkx/blob/main/docs/source/api/custom_return_types.rst A mapping for all-pairs path lengths. ```APIDOC ## AllPairsPathLengthMapping ### Description A mapping for all-pairs path lengths. ### Usage This is a return type and not directly callable. ``` -------------------------------- ### Adding Nodes and Edges in rustworkx Source: https://github.com/qiskit/rustworkx/blob/main/docs/source/networkx.rst Illustrates adding nodes and edges in rustworkx, which returns integer indices for nodes that must be used for access. ```python import rustworkx as rx graph = rx.PyDiGraph() node_a = graph.add_node('my_node_a') node_b = graph.add_node('my_node_b') graph.add_edge(node_a, node_b, None) ``` -------------------------------- ### Lint Rust Code with Clippy Source: https://github.com/qiskit/rustworkx/blob/main/CONTRIBUTING.md Execute Clippy to check your Rust code for common mistakes and style issues. Use the workspace and all-targets flag for comprehensive feedback identical to CI. ```bash cargo clippy ``` ```bash cargo clippy --workspace --all-targets -- -D warnings ``` -------------------------------- ### Run Fuzz Target with Nightly Toolchain Source: https://github.com/qiskit/rustworkx/blob/main/CONTRIBUTING.md Execute a fuzzing target using the nightly Rust toolchain. ```bash cargo +nightly fuzz run test_traversal_node_coverage ``` -------------------------------- ### Calculating All-Pairs Shortest Paths with Edge Weights in rustworkx (Dictionary Payload) Source: https://github.com/qiskit/rustworkx/blob/main/docs/source/networkx.rst Demonstrates using rustworkx's digraph_floyd_warshall_numpy with a weight function that extracts weight from a dictionary payload. ```python import rustworkx as rx graph = rx.PyDiGraph() graph.extend_from_weighted_edge_list( [(0, 1, {'weight': 1}), (0, 2, {'weight': 2}), (1, 3, {'weight': 2}), (3, 0, {'weight': 3})]) dist_matrix = rx.digraph_floyd_warshall_numpy( graph, weight_fn=lambda edge: edge['weight']) ``` -------------------------------- ### Enable Cycle Checking in PyDiGraph Source: https://github.com/qiskit/rustworkx/blob/main/docs/source/tutorial/dags.rst Demonstrates how to create a PyDiGraph with cycle checking enabled or set the check_cycle attribute after creation. This ensures that no cycles can be added to the graph. ```python dag = rx.PyDiGraph(check_cycle=True) ``` ```python dag.check_cycle = True ``` -------------------------------- ### Visitor Patterns Source: https://github.com/qiskit/rustworkx/blob/main/docs/source/api/algorithm_functions/traversal.rst Provides visitor classes for DFS, BFS, and Dijkstra's algorithm to allow custom processing during traversal. ```APIDOC ## DFSVisitor ### Description A visitor class for performing Depth First Search. Allows custom actions at different stages of the traversal. ### Usage Instantiate `DFSVisitor` and use its methods to customize DFS behavior. ``` ```APIDOC ## BFSVisitor ### Description A visitor class for performing Breadth First Search. Allows custom actions at different stages of the traversal. ### Usage Instantiate `BFSVisitor` and use its methods to customize BFS behavior. ``` ```APIDOC ## DijkstraVisitor ### Description A visitor class for Dijkstra's algorithm. Allows custom actions during the shortest path computation. ### Usage Instantiate `DijkstraVisitor` and use its methods to customize Dijkstra's algorithm behavior. ``` -------------------------------- ### Run Specific Test Module by Path with Nox Source: https://github.com/qiskit/rustworkx/blob/main/CONTRIBUTING.md Execute a specific test module by its path using Nox with the '-n' or '--no-discover' option. Paths are relative to the 'tests/' directory. ```bash nox -e test -- -n graph/test_nodes.py ``` -------------------------------- ### Pathfinding and Matrix Operations Source: https://github.com/qiskit/rustworkx/blob/main/docs/source/api/pygraph_api_functions.rst Functions for pathfinding, adjacency matrices, and matrix market file operations. ```APIDOC ## rustworkx.graph_adjacency_matrix ### Description Compute the adjacency matrix for a graph. ### Parameters - **graph** (PyGraph) - The input graph. - **weight_fn** (callable, optional) - A function to compute the weight of an edge. ### Returns numpy.ndarray - The adjacency matrix. ``` ```APIDOC ## rustworkx.graph_all_simple_paths ### Description Find all simple paths between two nodes in a graph. ### Parameters - **graph** (PyGraph) - The input graph. - **source** (int) - The source node index. - **target** (int) - The target node index. ### Returns list - A list of lists, where each inner list represents a simple path. ``` ```APIDOC ## rustworkx.graph_all_pairs_all_simple_paths ### Description Find all simple paths between all pairs of nodes in a graph. ### Parameters - **graph** (PyGraph) - The input graph. ### Returns dict - A dictionary where keys are source nodes and values are dictionaries of target nodes and lists of simple paths. ``` ```APIDOC ## rustworkx.graph_dijkstra_search ### Description Perform a search from a source node using Dijkstra's algorithm and return the path to a target node. ### Parameters - **graph** (PyGraph) - The input graph. - **source** (int) - The source node index. - **target** (int) - The target node index. - **weight_fn** (callable, optional) - A function to compute the weight of an edge. ### Returns list - A list of nodes representing the path from source to target. ``` ```APIDOC ## rustworkx.graph_node_link_json ### Description Generate a JSON representation of the graph in node-link format. ### Parameters - **graph** (PyGraph) - The input graph. ### Returns str - A JSON string representing the graph. ``` ```APIDOC ## rustworkx.graph_longest_simple_path ### Description Find the longest simple path in a directed acyclic graph (DAG). ### Parameters - **graph** (PyGraph) - The input graph (must be a DAG). - **weight_fn** (callable, optional) - A function to compute the weight of an edge. ### Returns list - A list of nodes representing the longest simple path. ``` ```APIDOC ## rustworkx.graph_write_matrix_market ### Description Write the graph's adjacency matrix to a file in Matrix Market format. ### Parameters - **graph** (PyGraph) - The input graph. - **filename** (str) - The path to the output file. - **weight_fn** (callable, optional) - A function to compute the weight of an edge. ``` ```APIDOC ## rustworkx.graph_generate_random_path ### Description Generate a random path in the graph. ### Parameters - **graph** (PyGraph) - The input graph. - **start_node** (int) - The node to start the path from. - **max_length** (int) - The maximum length of the path. ### Returns list - A list of nodes representing the random path. ``` -------------------------------- ### Generate Release Notes RST Source: https://github.com/qiskit/rustworkx/blob/main/CONTRIBUTING.md Use this command to generate the ReStructuredText file for release notes. This is part of the documentation build process. ```bash reno report ``` -------------------------------- ### Create and Manipulate Undirected Graph (PyGraph) Source: https://context7.com/qiskit/rustworkx/llms.txt Demonstrates creating an undirected multigraph, adding nodes and edges, accessing node/edge data, and removing elements. Use `PyGraph(multigraph=False)` to disallow parallel edges. ```python import rustworkx as rx # Create an undirected graph (multigraph by default) g = rx.PyGraph() # add_node returns the integer index of the new node a = g.add_node("A") b = g.add_node("B") c = g.add_node("C") # add_edge(source_idx, target_idx, weight) returns the edge index e1 = g.add_edge(a, b, 1.5) e2 = g.add_edge(b, c, 2.5) e3 = g.add_edge(a, c, 5.0) # Bulk add from a list of (src, tgt, weight) tuples indices = g.add_nodes_from(["D", "E"]) g.add_edges_from([(indices[0], indices[1], 0.5)]) # Access node data via mapping protocol print(g[a]) # "A" g[a] = "Alpha" # mutate in place print(g.nodes()) # all node payloads print(g.edges()) # all edge payloads print(g.node_indices()) # NodeIndices([0, 1, 2, 3, 4]) print(g.edge_indices()) # EdgeIndices print(g.degree(a)) # 2 print(g.neighbors(b)) # [0, 2] print(g.incident_edges(b)) # edge indices incident to b print(g.get_edge_data(a, b)) # 1.5 print(g.get_edge_data_by_index(e1)) # 1.5 print(g.edge_index_map()) # {edge_idx: (src, tgt, weight), ...} # Remove elements (indices of removed nodes/edges may be reused) g.remove_node(c) g.remove_edge(a, b) g.remove_edge_from_index(e3) # Non-multigraph: parallel edges update existing edge weight g2 = rx.PyGraph(multigraph=False) g2.add_nodes_from(range(3)) g2.add_edges_from([(0, 1, "A"), (0, 1, "B"), (1, 2, "C")]) print(g2.get_edge_data(0, 1)) # "B" — second add updated the weight # Graph-level metadata attribute g3 = rx.PyGraph(attrs={"created": "2024-01-01"}) g3.attrs["version"] = 2 ```