### NetworkX Installation Instructions Source: https://networkx.org/documentation/stable/release/old_release_log.html Provides detailed instructions for installing NetworkX. This includes information on dependencies and potential issues, ensuring a smooth setup process. ```text More detailed installation instructions are available. ``` -------------------------------- ### Verify Installation and Setup Pre-commit Source: https://networkx.org/documentation/stable/developer/contribute.html Commands to verify the NetworkX installation using pytest and to initialize the pre-commit hooks for automated code formatting. ```bash pytest --pyargs networkx pre-commit install ``` -------------------------------- ### Setup Development Environment with venv Source: https://networkx.org/documentation/stable/developer/contribute.html Sets up a Python virtual environment using venv, installs NetworkX development dependencies, and installs NetworkX from source. Includes optional installation of pygraphviz and pydot. ```bash # Create a virtualenv named ``networkx-dev`` that lives in the directory of # the same name python -m venv networkx-dev # Activate it source networkx-dev/bin/activate # Install main development and runtime dependencies of networkx pip install -r requirements/default.txt -r requirements/test.txt -r requirements/developer.txt # # (Optional) Install pygraphviz and pydot packages # These packages require that you have your system properly configured # and what that involves differs on various systems. # pip install -r requirements/extra.txt # # Build and install networkx from source pip install -e . # Test your installation pytest --pyargs networkx ``` -------------------------------- ### Setup Development Environment with conda Source: https://networkx.org/documentation/stable/developer/contribute.html Sets up a conda environment, installs NetworkX development dependencies, and installs NetworkX from source. Includes optional installation of pygraphviz and pydot. ```bash # Create a conda environment named ``networkx-dev`` conda create --name networkx-dev # Activate it conda activate networkx-dev # Install main development and runtime dependencies of networkx conda install -c conda-forge --file requirements/default.txt --file requirements/test.txt --file requirements/developer.txt # # (Optional) Install pygraphviz and pydot packages # These packages require that you have your system properly configured # and what that involves differs on various systems. # conda install -c conda-forge --file requirements/extra.txt # # Install networkx from source pip install -e . ``` -------------------------------- ### Compute all shortest paths from a source node using NetworkX Source: https://networkx.org/documentation/stable/reference/algorithms/generated/networkx.algorithms.shortest_paths.generic.single_source_all_shortest_paths.html This example demonstrates how to initialize a NetworkX graph, add a path, and compute all shortest simple paths from a starting node. The output is a dictionary mapping target nodes to lists of shortest paths. ```python import networkx as nx G = nx.Graph() nx.add_path(G, [0, 1, 2, 3, 0]) paths = dict(nx.single_source_all_shortest_paths(G, source=0)) print(paths) ``` -------------------------------- ### Install NetworkX Development Version from Git Source: https://networkx.org/documentation/stable/install.html Installs the latest development version of NetworkX directly from its GitHub repository. This requires Git to be installed and may involve uninstalling the stable version first. ```bash $ pip uninstall networkx $ git clone https://github.com/networkx/networkx.git $ cd networkx $ pip install -e .[default] ``` -------------------------------- ### Create Example Gallery Contribution Branch Source: https://networkx.org/documentation/stable/developer/new_contributor_faq.html This command creates a new Git branch for contributing an example to the NetworkX gallery. It's a standard practice to name branches descriptively. ```bash git checkout -b complete-graph-circular-layout-example ``` -------------------------------- ### Install NetworkX from Source with Pip Source: https://networkx.org/documentation/stable/install.html Installs NetworkX from a downloaded source archive or directory. This method is used when installing from a local copy of the source code. ```bash $ pip install .[default] ``` -------------------------------- ### Example: Generate Network with Specified Parameters (Python) Source: https://networkx.org/documentation/stable/_modules/networkx/generators/geometric.html Demonstrates how to create a geometric soft configuration graph using NetworkX by providing parameters such as beta, n, gamma, and mean_degree. This example generates a network with 100 nodes, beta=1.5, gamma=2.7, and mean_degree=5. ```python import networkx as nx G = nx.geometric_soft_configuration_graph( beta=1.5, n=100, gamma=2.7, mean_degree=5 ) ``` -------------------------------- ### Running Tests with Setuptools in NetworkX Source: https://networkx.org/documentation/stable/release/old_release_log.html Provides instructions on how to run NetworkX tests using `python setup_egg.py test`, which requires setuptools to be installed. This is an alternative method for testing the library. ```python python setup_egg.py test ``` -------------------------------- ### Create Quotient Graph with Node Partition (Python) Source: https://networkx.org/documentation/stable/_modules/networkx/algorithms/minors/contraction.html Demonstrates creating a quotient graph using `nx.quotient_graph` with a list of sets representing the node partition. It shows how to relabel nodes and lists the edges of the resulting quotient graph. ```Python G = nx.path_graph(6) partition = [{0, 1}, {2, 3}, {4, 5}] M = nx.quotient_graph(G, partition, relabel=True) list(M.edges()) ``` -------------------------------- ### GET /graph/negative-cycle Source: https://networkx.org/documentation/stable/_modules/networkx/algorithms/shortest_paths/weighted.html Finds a negative cycle in a graph starting from a specified source node. ```APIDOC ## GET /graph/negative-cycle ### Description Identifies a negative cycle in the graph starting from the provided source node. Returns the list of nodes forming the cycle. ### Method GET ### Endpoint /graph/negative-cycle ### Parameters #### Query Parameters - **G** (Graph) - Required - The NetworkX graph object. - **source** (node) - Required - The starting node for cycle detection. - **weight** (string/function) - Optional - The edge attribute or function used to determine weight. ### Request Example { "source": 0, "weight": "weight" } ### Response #### Success Response (200) - **cycle** (list) - A list of nodes in the order of the cycle found. #### Response Example { "cycle": [4, 0, 1, 4] } ``` -------------------------------- ### Initialize Graph for Flow Calculation Source: https://networkx.org/documentation/stable/_modules/networkx/algorithms/flow/preflowpush.html Example demonstrating how to construct a directed graph with capacity attributes suitable for flow algorithms in NetworkX. ```python import networkx as nx from networkx.algorithms.flow import preflow_push G = nx.DiGraph() G.add_edge("x", "a", capacity=3.0) G.add_edge("x", "b", capacity=1.0) G.add_edge("a", "c", capacity=3.0) G.add_edge("b", "c", capacity=5.0) G.add_edge("b", "d", capacity=4.0) ``` -------------------------------- ### GET /dfs_tree Source: https://networkx.org/documentation/stable/_modules/networkx/algorithms/traversal/depth_first_search.html Constructs an oriented tree from a depth-first-search traversal starting from a source node. ```APIDOC ## GET /dfs_tree ### Description Returns an oriented DiGraph representing the tree constructed from a DFS traversal. ### Method GET ### Endpoint /dfs_tree ### Parameters #### Query Parameters - **G** (Graph) - Required - The NetworkX graph object. - **source** (node) - Optional - Starting node for the search. - **depth_limit** (int) - Optional - Maximum search depth. - **sort_neighbors** (function) - Optional - Custom ordering function for neighbor iteration. ### Request Example { "G": "path_graph(5)", "source": 0 } ### Response #### Success Response (200) - **tree** (DiGraph) - An oriented tree structure. #### Response Example { "edges": [[0, 1], [1, 2], [2, 3], [3, 4]] } ``` -------------------------------- ### MappedQueue Initialization Examples Source: https://networkx.org/documentation/stable/reference/generated/networkx.utils.mapped_queue.MappedQueue.html Demonstrates how to initialize a MappedQueue with a dictionary of elements and priorities, or with an iterable. ```APIDOC ## MappedQueue Initialization Examples ### Example 1: Initialization with a dictionary ```python >>> colors_nm = {"red": 665, "blue": 470, "green": 550} >>> q = MappedQueue(colors_nm) >>> q.remove("red") >>> q.update("green", "violet", 400) >>> q.push("indigo", 425) True >>> [q.pop().element for i in range(len(q.heap))] ['violet', 'indigo', 'blue'] ``` ### Example 2: Initialization with an iterable ```python >>> q = MappedQueue([916, 50, 4609, 493, 237]) >>> q.remove(493) >>> q.update(237, 1117) >>> [q.pop() for i in range(len(q.heap))] [50, 916, 1117, 4609] ``` ### Example 3: Handling non-comparable elements with a dictionary ```python >>> q = MappedQueue({100: 0, "a": 1}) ``` ``` -------------------------------- ### GET /internal/direction_of_ascent Source: https://networkx.org/documentation/stable/_modules/networkx/algorithms/approximation/traveling_salesman.html Computes the direction of ascent at point pi to guide the optimization process. ```APIDOC ## GET /internal/direction_of_ascent ### Description Computes the direction of ascent at point pi as defined in the Held and Karp paper (1970). This is used to adjust the dual variables in the ATSP approximation algorithm. ### Method GET ### Endpoint /internal/direction_of_ascent ### Parameters #### Path Parameters - None #### Query Parameters - None ### Request Example {} ### Response #### Success Response (200) - **direction** (dict) - A mapping from graph nodes to values representing the direction of ascent. #### Response Example { "direction": { "node_1": 0, "node_2": 0 } } ``` -------------------------------- ### Initialize and Populate DiGraph Source: https://networkx.org/documentation/stable/reference/classes/digraph.html Demonstrates how to create an empty directed graph and add nodes and edges using various methods. ```python import networkx as nx G = nx.DiGraph() G.add_node(1) G.add_nodes_from([2, 3]) G.add_edge(1, 2) G.add_edges_from([(1, 2), (1, 3)]) ``` -------------------------------- ### GET /algorithms/traversal/edge_bfs Source: https://networkx.org/documentation/stable/reference/algorithms/generated/networkx.algorithms.traversal.edgebfs.edge_bfs.html Performs a directed, breadth-first-search of edges in a graph starting from a specified source node. ```APIDOC ## GET /algorithms/traversal/edge_bfs ### Description A directed, breadth-first-search of edges in G, beginning at source. Yields the edges of G in a breadth-first-search order continuing until all edges are generated. ### Method GET ### Endpoint /algorithms/traversal/edge_bfs ### Parameters #### Query Parameters - **G** (graph) - Required - A directed/undirected graph or multigraph. - **source** (node/list) - Optional - The node from which the traversal begins. If None, chosen arbitrarily. - **orientation** (string) - Optional - None, 'original', 'reverse', or 'ignore'. Determines how edge traversal respects direction. ### Request Example { "G": "GraphObject", "source": 0, "orientation": "original" } ### Response #### Success Response (200) - **edges** (list) - A list of directed edges indicating the path taken by the BFS. #### Response Example [ [0, 1], [1, 0], [2, 0] ] ``` -------------------------------- ### Initialize NetworkX Graphs Source: https://networkx.org/documentation/stable/reference/classes/generated/networkx.Graph.__init__.html Demonstrates how to instantiate a new NetworkX graph object, including creating an empty graph, naming a graph, and initializing from a list of edges. ```python import networkx as nx # Create an empty graph G = nx.Graph() # Create a graph with a name attribute G = nx.Graph(name="my graph") # Initialize from a list of edges e = [(1, 2), (2, 3), (3, 4)] G = nx.Graph(e) ``` -------------------------------- ### GET /immediate_dominators Source: https://networkx.org/documentation/stable/reference/algorithms/generated/networkx.algorithms.dominance.immediate_dominators.html Computes the immediate dominators for all nodes in a directed graph relative to a start node. ```APIDOC ## GET /immediate_dominators ### Description Returns the immediate dominators of all nodes of a directed graph reachable from a start node. The immediate dominator of a node is the unique node that strictly dominates the node but does not strictly dominate any other node that strictly dominates the node. ### Method GET ### Endpoint immediate_dominators(G, start) ### Parameters #### Path Parameters - **G** (DiGraph or MultiDiGraph) - Required - The directed graph to analyze. - **start** (node) - Required - The starting node for dominance computation. ### Request Example { "G": "nx.DiGraph([(1, 2), (1, 3), (2, 5), (3, 4), (4, 5)])", "start": 1 } ### Response #### Success Response (200) - **idom** (dict) - A dictionary mapping nodes to their immediate dominators. #### Response Example { "idom": {"2": 1, "3": 1, "4": 3, "5": 1} } ### Errors - **NetworkXNotImplemented**: Raised if the provided graph is undirected. - **NetworkXError**: Raised if the start node is not present in the graph. ``` -------------------------------- ### Initialize and Populate a DiGraph Source: https://networkx.org/documentation/stable/_modules/networkx/classes/digraph.html Demonstrates how to instantiate a directed graph and add nodes or edges using various input formats. ```python import networkx as nx # Initialize empty graph G = nx.DiGraph() # Add nodes G.add_node(1) G.add_nodes_from([2, 3]) # Add edges G.add_edge(1, 2) G.add_edges_from([(1, 2), (1, 3)]) ``` -------------------------------- ### GET /dominance_frontiers Source: https://networkx.org/documentation/stable/reference/algorithms/generated/networkx.algorithms.dominance.dominance_frontiers.html Computes the dominance frontiers of all nodes in a directed graph starting from a given node. ```APIDOC ## GET /dominance_frontiers ### Description Returns the dominance frontiers of all nodes of a directed graph reachable from the start node. ### Method GET ### Endpoint /dominance_frontiers ### Parameters #### Query Parameters - **G** (DiGraph/MultiDiGraph) - Required - The directed graph where dominance is to be computed. - **start** (node) - Required - The start node of dominance computation. ### Request Example { "G": "DiGraph([(1, 2), (1, 3), (2, 5), (3, 4), (4, 5)])", "start": 1 } ### Response #### Success Response (200) - **df** (dict) - A dictionary keyed by nodes, containing the dominance frontiers of each node as lists. #### Response Example { "1": [], "2": [5], "3": [5], "4": [5], "5": [] } ``` -------------------------------- ### nx.quotient_graph() - Basic Usage Source: https://networkx.org/documentation/stable/reference/algorithms/generated/networkx.algorithms.minors.quotient_graph.html Demonstrates the basic usage of nx.quotient_graph with a list of sets representing the partition. ```APIDOC ## nx.quotient_graph() - Basic Usage ### Description Creates a quotient graph from an original graph G and a partition. The nodes of the quotient graph are the blocks of the partition. An edge exists between two nodes in the quotient graph if there is an edge in the original graph between any node in the first block and any node in the second block. ### Method `nx.quotient_graph(G, partition, relabel=False)` ### Parameters #### Path Parameters None #### Query Parameters - **relabel** (bool) - Optional - If True, the nodes in the quotient graph will be relabeled to the block labels. #### Request Body None ### Request Example ```python import networkx as nx G = nx.path_graph(6) partition = [{0, 1}, {2, 3}, {4, 5}] M = nx.quotient_graph(G, partition, relabel=True) print(list(M.edges())) ``` ### Response #### Success Response (200) Returns a NetworkX graph object representing the quotient graph. #### Response Example ``` [(0, 1), (1, 2)] ``` ``` -------------------------------- ### GET /bfs_tree Source: https://networkx.org/documentation/stable/reference/algorithms/generated/networkx.algorithms.traversal.breadth_first_search.bfs_tree.html Returns an oriented tree constructed from a breadth-first search starting at a specified source node. ```APIDOC ## GET /bfs_tree ### Description Returns an oriented tree constructed from a breadth-first search starting at the provided source node. ### Method GET ### Endpoint /bfs_tree ### Parameters #### Query Parameters - **G** (NetworkX graph) - Required - The graph to perform the search on. - **source** (node) - Required - The starting node for the breadth-first search. - **reverse** (bool) - Optional - If True, traverse a directed graph in the reverse direction. - **depth_limit** (int) - Optional - The maximum search depth (default is the length of G). - **sort_neighbors** (function) - Optional - A function to order neighbors during traversal. ### Request Example { "G": "path_graph(3)", "source": 1 } ### Response #### Success Response (200) - **T** (DiGraph) - An oriented tree representing the BFS traversal. #### Response Example { "edges": [[1, 0], [1, 2]] } ``` -------------------------------- ### Get the first pair of communities Source: https://networkx.org/documentation/stable/reference/algorithms/generated/networkx.algorithms.community.centrality.girvan_newman.html This example demonstrates how to get the first pair of communities from a graph using the Girvan-Newman algorithm. It initializes a path graph and then iterates through the communities generated by `girvan_newman` to extract the first set. ```python >>> G = nx.path_graph(10) >>> comp = nx.community.girvan_newman(G) >>> tuple(sorted(c) for c in next(comp)) ([0, 1, 2, 3, 4], [5, 6, 7, 8, 9]) ``` -------------------------------- ### Initialize NetworkX Graph Source: https://networkx.org/documentation/stable/reference/classes/graph.html Demonstrates how to create an empty NetworkX Graph object. This is the starting point for building graph structures. ```python import networkx as nx G = nx.Graph() ``` -------------------------------- ### GET /edge_dfs Source: https://networkx.org/documentation/stable/reference/algorithms/generated/networkx.algorithms.traversal.edgedfs.edge_dfs.html Performs a depth-first search of edges in a graph starting from a specified source node or set of nodes. ```APIDOC ## GET /edge_dfs ### Description A directed, depth-first-search of edges in G, beginning at source. Yields the edges of G in a depth-first-search order continuing until all edges are generated. ### Method GET ### Endpoint edge_dfs(G, source=None, orientation=None) ### Parameters #### Path Parameters - **G** (graph) - Required - A directed/undirected graph or multigraph. #### Query Parameters - **source** (node or list of nodes) - Optional - The node from which the traversal begins. If None, a source is chosen arbitrarily. - **orientation** (string) - Optional - Defines edge traversal behavior: 'original', 'reverse', 'ignore', or None (default). ### Request Example { "G": "Graph object", "source": 0, "orientation": "original" } ### Response #### Success Response (200) - **edge** (tuple) - A directed edge indicating the path taken. For graphs: (u, v). For multigraphs: (u, v, key). If orientation is set, includes direction ('forward' or 'reverse'). #### Response Example [ [0, 1], [1, 2] ] ``` -------------------------------- ### Initialize Environment and Dependencies Source: https://networkx.org/documentation/stable/_downloads/c8b52e50c38eb7e019495b45c7d35d33/plot_image_segmentation_spectral_graph_partition.ipynb Imports necessary libraries including NumPy, NetworkX, Matplotlib, and Scikit-learn for spectral clustering. ```python import numpy as np import networkx as nx import matplotlib.pyplot as plt from matplotlib import animation from matplotlib.lines import Line2D from sklearn.cluster import SpectralClustering ``` -------------------------------- ### Initialize and Populate NetworkX Graph Source: https://networkx.org/documentation/stable/_modules/networkx/classes/graph.html Demonstrates how to instantiate a NetworkX Graph, add nodes from various containers, and add edges. The graph automatically handles node creation when adding edges. ```python import networkx as nx # Create empty graph G = nx.Graph(day="Friday") # Add nodes G.add_node(1) G.add_nodes_from([2, 3]) # Add edges G.add_edge(1, 2) G.add_edges_from([(1, 2), (1, 3)]) # Access attributes print(G.graph) ``` -------------------------------- ### GET /centrality/subgraph Source: https://networkx.org/documentation/stable/_modules/networkx/algorithms/centrality/subgraph_alg.html Calculates the subgraph centrality for each node in the graph, which is based on the number of closed walks starting and ending at a node. ```APIDOC ## GET /centrality/subgraph ### Description Calculates the subgraph centrality for each node in a graph. Subgraph centrality is defined as the sum of the weights of all closed walks starting and ending at a node. ### Method GET ### Endpoint /centrality/subgraph ### Parameters #### Query Parameters - **normalized** (boolean) - Optional - If true, the centrality values are normalized. ### Response #### Success Response (200) - **nodes** (dictionary) - A dictionary where keys are node identifiers and values are the calculated centrality scores. ### Response Example { "1": 3.90, "2": 3.90, "3": 3.64 } ``` -------------------------------- ### Graph Shortcuts and Iteration Source: https://networkx.org/documentation/stable/reference/classes/multidigraph.html Provides examples of common shortcuts for checking node existence, iterating through nodes, getting the graph size, and accessing adjacency information. ```APIDOC ## Graph Shortcuts and Iteration ### Description NetworkX provides convenient Pythonic ways to interact with graph objects, such as checking for node membership, iterating over nodes, and accessing neighbors. ### Shortcuts - **Node Membership**: `node in G` checks if a node exists in the graph. - **Node Iteration**: `for n in G:` iterates through all nodes. - **Graph Size**: `len(G)` returns the number of nodes. - **Adjacency View**: `G[node]` provides a dictionary-like view of a node's neighbors and their edge data. - **Adjacency Iteration**: `G.adjacency()` or `G.adj` allows iteration over nodes and their neighbors. ### Request Example ```python import networkx as nx G = nx.MultiDiGraph() G.add_edges_from([(1, 2), (1, 3), (2, 3), (3, 4), (4, 5, {'route': 282}), (4, 5, {'route': 37})]) # Check if a node is in the graph print(f"Is node 1 in G? {1 in G}") # Iterate through nodes print("Nodes in G:") for n in G: print(n) # Get the number of nodes print(f"Number of nodes: {len(G)}") # Get neighbors of node 1 print(f"Neighbors of node 1: {G[1]}") # Iterate through adjacency list print("Adjacency list:") for node, neighbors in G.adjacency(): print(f"Node {node}: {neighbors}") ``` ### Response Example ```json { "node_membership": { "1_in_G": true }, "nodes_iterated": [ 1, 2, 3, 4, 5 ], "graph_size": 5, "adjacency_view_1": { "2": {"0": {}}, "3": {"0": {}} }, "adjacency_list_iteration": [ {"node": 1, "neighbors": {"2": {"0": {}}, "3": {"0": {}}}}, {"node": 2, "neighbors": {"3": {"0": {}}}}, {"node": 3, "neighbors": {"4": {"0": {}}}}, {"node": 4, "neighbors": {"5": {"0": {"route": 282}, "1": {"route": 37}}}}, {"node": 5, "neighbors": {}} ] } ``` ``` -------------------------------- ### Command line operations for testing and documentation Source: https://networkx.org/documentation/stable/developer/contribute.html A collection of shell commands for installing dependencies, running image comparison tests, and building documentation in various formats. ```bash pip install pytest-mpl PYTHONPATH=. pytest --mpl --pyargs networkx.drawing pytest -k test_barbell --mpl-generate-path=networkx/drawing/tests/baseline pytest -k test_barbell --mpl pip install -r requirements/doc.txt pip install -r requirements/extra.txt pip install -r requirements/example.txt make html make html-noplot make latexpdf ``` -------------------------------- ### GET /generators/partial_duplication Source: https://networkx.org/documentation/stable/_modules/networkx/generators/duplication.html Generates a random graph using the partial duplication model, starting from an initial clique and iteratively adding nodes with edge duplication probabilities. ```APIDOC ## GET /generators/partial_duplication ### Description Returns a random graph using the partial duplication model. This model grows a graph by creating a fully connected initial clique and iteratively adding nodes that duplicate edges from existing nodes based on probabilities p and q. ### Method GET ### Parameters #### Query Parameters - **N** (int) - Required - The total number of nodes in the final graph. - **n** (int) - Required - The number of nodes in the initial clique. - **p** (float) - Required - Probability of joining each neighbor of a source node to the duplicate node (0 <= p <= 1). - **q** (float) - Required - Probability of joining the source node to the duplicate node (0 <= q <= 1). - **seed** (int/random_state) - Optional - Random number generation state. ### Response #### Success Response (200) - **G** (Graph) - The generated undirected graph object. ``` -------------------------------- ### Import NetworkX Approximation Algorithms Source: https://networkx.org/documentation/stable/reference/algorithms/approximation.html Demonstrates how to import approximation algorithms from the networkx.algorithms module. This is the recommended way to access these functions. ```python from networkx.algorithms import approximation ``` -------------------------------- ### Custom Heuristic for RCM Ordering Source: https://networkx.org/documentation/stable/reference/generated/networkx.utils.rcm.reverse_cuthill_mckee_ordering.html Shows how to define and supply a custom heuristic function to the reverse_cuthill_mckee_ordering algorithm. This example uses the node with the smallest degree as the starting point for the search. ```python def smallest_degree(G): return min(G, key=G.degree) rcm = list(reverse_cuthill_mckee_ordering(G, heuristic=smallest_degree)) ``` -------------------------------- ### Create Example Directed Graph Source: https://networkx.org/documentation/stable/_downloads/538f38325dbb659c6ead9fd27aaef906/plot_subgraphs.ipynb Constructs a sample directed graph with nodes assigned specific 'node_type' and 'node_color' attributes to demonstrate the partitioning logic. ```python G_ex = nx.DiGraph() G_ex.add_nodes_from(["In"], node_type="input", node_color="b") G_ex.add_nodes_from(["A", "C", "E", "F"], node_type="supported", node_color="g") G_ex.add_nodes_from(["B", "D"], node_type="unsupported", node_color="r") G_ex.add_nodes_from(["Out"], node_type="output", node_color="m") G_ex.add_edges_from([("In", "A"), ("A", "B"), ("B", "C"), ("B", "D"), ("D", "E"), ("C", "F"), ("E", "F"), ("F", "Out")]) ``` -------------------------------- ### Get Biconnected Components of a Graph Source: https://networkx.org/documentation/stable/reference/algorithms/generated/networkx.algorithms.components.biconnected_components.html Generates sets of nodes for each biconnected component. Use list() to collect all components. This example demonstrates checking if a graph is biconnected before and after adding an edge. ```python >>> G = nx.lollipop_graph(5, 1) >>> print(nx.is_biconnected(G)) False >>> bicomponents = list(nx.biconnected_components(G)) >>> len(bicomponents) 2 >>> G.add_edge(0, 5) >>> print(nx.is_biconnected(G)) True >>> bicomponents = list(nx.biconnected_components(G)) >>> len(bicomponents) 1 ``` -------------------------------- ### Create Empty Graphs with NetworkX Source: https://networkx.org/documentation/stable/reference/generated/networkx.generators.classic.empty_graph.html Demonstrates how to initialize empty graphs using different node counts, node labels, and graph types like DiGraph and MultiGraph. ```python import networkx as nx # Create a standard empty graph with 10 nodes G = nx.empty_graph(10) # Create an empty DiGraph with 10 nodes G_di = nx.empty_graph(10, create_using=nx.DiGraph) # Create an empty graph with specific node labels G_labels = nx.empty_graph("ABC") # Using a custom constructor function def mygraph(n, create_using=None): G = nx.empty_graph(n, create_using, nx.MultiGraph) G.add_edges_from([(0, 1), (0, 1)]) return G ``` -------------------------------- ### Compute Eulerian Circuit in NetworkX Source: https://networkx.org/documentation/stable/reference/algorithms/generated/networkx.algorithms.euler.eulerian_circuit.html Demonstrates how to generate an Eulerian circuit from a complete graph using NetworkX. The example shows how to retrieve edges as tuples and how to specify a custom starting node. ```python import networkx as nx G = nx.complete_graph(3) # Get edges of the circuit circuit_edges = list(nx.eulerian_circuit(G)) # Get edges starting from a specific node circuit_from_source = list(nx.eulerian_circuit(G, source=1)) # Extract vertex sequence from edges vertices = [u for u, v in nx.eulerian_circuit(G)] ``` -------------------------------- ### Approximate TSP Solution with greedy_tsp Source: https://networkx.org/documentation/stable/reference/algorithms/generated/networkx.algorithms.approximation.traveling_salesman.greedy_tsp.html This example demonstrates how to initialize a directed graph with weighted edges and compute an approximate TSP cycle starting from a specific node using the greedy_tsp approximation algorithm. ```python from networkx.algorithms import approximation as approx import networkx as nx G = nx.DiGraph() G.add_weighted_edges_from({ ("A", "B", 3), ("A", "C", 17), ("A", "D", 14), ("B", "A", 3), ("B", "C", 12), ("B", "D", 16), ("C", "A", 13), ("C", "B", 12), ("C", "D", 4), ("D", "A", 14), ("D", "B", 15), ("D", "C", 2) }) cycle = approx.greedy_tsp(G, source="D") cost = sum(G[n][nbr]["weight"] for n, nbr in nx.utils.pairwise(cycle)) print(f"Cycle: {cycle}") print(f"Total Cost: {cost}") ``` -------------------------------- ### Graph Shortcuts for Node and Edge Operations (Python) Source: https://networkx.org/documentation/stable/_modules/networkx/classes/digraph.html Provides examples of Pythonic shortcuts for common graph operations, such as checking node membership, iterating through nodes, and getting the number of nodes in the graph. ```python print(1 in G) print([n for n in G if n < 3]) print(len(G)) ``` -------------------------------- ### Initialize 3D Graph and Layout Source: https://networkx.org/documentation/stable/auto_examples/3d_drawing/plot_3d_animation_walk.html Sets up a dodecahedral graph using NetworkX and calculates 3D coordinates for nodes and edges using a spectral layout. ```python import numpy as np import networkx as nx import random import matplotlib.pyplot as plt from matplotlib import animation G = nx.dodecahedral_graph() pos = nx.spectral_layout(G, dim=3) nodes = np.array([pos[v] for v in G]) edges = np.array([(pos[u], pos[v]) for u, v in G.edges()]) ``` -------------------------------- ### Check Available Backends for a Function Source: https://networkx.org/documentation/stable/reference/backends.html Retrieves a set of all installed backends that implement a specific NetworkX function. This is done by accessing the `.backends` attribute of the function object. For example, `nx.betweenness_centrality.backends` will show which backends support this function. ```python >>> import networkx as nx >>> nx.betweenness_centrality.backends {'parallel'} ``` -------------------------------- ### Visualize NetworkX Graphs with Default Settings Source: https://networkx.org/documentation/stable/_downloads/fc8235e6f1dd535c7287d8fd1fd054c2/plot_iplotx.ipynb A minimal example demonstrating how to render a NetworkX graph using iplotx with default visual parameters. ```python ipx.network(H, layout) ``` -------------------------------- ### Compute shortest paths from multiple sources using NetworkX Source: https://networkx.org/documentation/stable/reference/algorithms/generated/networkx.algorithms.shortest_paths.weighted.multi_source_dijkstra.html This example demonstrates how to use multi_source_dijkstra to find shortest paths from a set of source nodes in a path graph. It shows both the case where all reachable nodes are calculated and the case where a specific target node is provided. ```python import networkx as nx G = nx.path_graph(5) # Calculate shortest paths from sources 0 and 4 to all nodes length, path = nx.multi_source_dijkstra(G, {0, 4}) for node in [0, 1, 2, 3, 4]: print(f"{node}: {length[node]}") # Calculate shortest path from sources {0, 4} to target 1 length, path = nx.multi_source_dijkstra(G, {0, 4}, 1) print(f"Distance: {length}") print(f"Path: {path}") ``` -------------------------------- ### Detect Negative Cycle in a Directed Graph Source: https://networkx.org/documentation/stable/reference/algorithms/generated/networkx.algorithms.shortest_paths.weighted.find_negative_cycle.html This example demonstrates how to create a directed graph with weighted edges and use the find_negative_cycle function to identify a cycle with a negative total weight starting from a specific source node. ```python import networkx as nx G = nx.DiGraph() G.add_weighted_edges_from([(0, 1, 2), (1, 2, 2), (2, 0, 1), (1, 4, 2), (4, 0, -5)]) cycle = nx.find_negative_cycle(G, 0) print(cycle) ```