[{"data":1,"prerenderedAt":-1},["ShallowReactive",2],{"skill:01M73HFDA2C2AMHEB4RY9PF27D":3,"skill-same:01M73HFDA2C2AMHEB4RY9PF27D":48},{"skillNo":4,"name":5,"nameZh":6,"description":7,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":16,"categories":17,"keywords":18,"publishedAt":19,"linkOnly":20,"markdownContent":21,"markdownBody":22,"frontMatter":23,"refName":24,"commitSha":25,"skillDirectory":26,"forksCount":27,"repositoryHtmlUrl":28,"repositoryHomepageUrl":29,"ownerHtmlUrl":30,"ownerBlogUrl":31,"ownerDescription":32,"updatedAt":33,"install":34,"resources":47},"01M73HFDA2C2AMHEB4RY9PF27D","networkx-graph-analysis",null,"Graph and network analysis toolkit. Four graph types (directed, undirected, multi-edge), centrality, shortest paths, community detection, generators, I\u002FO (GraphML, GML, edge list), matplotlib viz. For large graphs (100K+ nodes) use igraph or graph-tool; for GNNs use PyG.","bg-szy\u002FTOP-SKILLS","bg-szy","https:\u002F\u002Favatars.githubusercontent.com\u002Fu\u002F106576190?v=4","01M73A4E8KPV67SFXRY8XZGNBX","ShuZhiyong","01M73A4E96MQ294MHM74TZBVQD",6,"BSD-3-Clause","https:\u002F\u002Fgithub.com\u002Fbg-szy\u002FTOP-SKILLS\u002Fblob\u002Fmaster\u002Fskills\u002Fawesome-skills\u002Fnetworkx-graph-analysis\u002FSKILL.md",[],[],"2026-11-11 15:11:14",false,"---\nname: \"networkx-graph-analysis\"\ndescription: \"Graph and network analysis toolkit. Four graph types (directed, undirected, multi-edge), centrality, shortest paths, community detection, generators, I\u002FO (GraphML, GML, edge list), matplotlib viz. For large graphs (100K+ nodes) use igraph or graph-tool; for GNNs use PyG.\"\nlicense: BSD-3-Clause\n---\n\n# NetworkX Graph Analysis\n\n## Overview\n\nNetworkX is a Python library for creating, manipulating, and analyzing complex networks and graphs. It provides data structures for undirected, directed, and multi-edge graphs along with a comprehensive collection of graph algorithms, generators, and I\u002FO utilities. Use NetworkX when working with relationship data in social networks, biological interaction networks, transportation systems, citation graphs, or any domain involving pairwise entity relationships.\n\n## When to Use\n\n- Analyzing protein-protein interaction networks, gene regulatory networks, or metabolic pathways\n- Computing centrality measures (degree, betweenness, PageRank) to identify important nodes\n- Finding shortest paths or optimal routes in transportation or communication networks\n- Detecting communities or clusters in social networks or co-expression data\n- Generating synthetic networks (scale-free, small-world, random) for simulation or null models\n- Reading and writing graph data in standard formats (GraphML, GML, edge lists, JSON)\n- Visualizing network topology with node\u002Fedge attribute mapping\n- Checking graph properties: connectivity, planarity, isomorphism, DAG structure\n- For large-scale graphs (100K+ nodes) where speed is critical, use `igraph` or `graph-tool` instead\n- For billion-edge graphs or GPU-accelerated analytics, use `graph-tool` with OpenMP or `cuGraph`\n- For graph neural networks and deep learning on graphs, use `torch-geometric-graph-neural-networks`\n\n## Prerequisites\n\n- **Python packages**: `networkx`, `matplotlib`, `scipy`, `pandas`, `numpy`\n- **Optional**: `pydot` or `pygraphviz` (Graphviz layouts)\n\n```bash\npip install networkx matplotlib scipy pandas numpy\n```\n\n## Quick Start\n\n```python\nimport networkx as nx\n\n# Create a graph and add edges with weights\nG = nx.karate_club_graph()\nprint(f\"Nodes: {G.number_of_nodes()}, Edges: {G.number_of_edges()}\")\n# Nodes: 34, Edges: 78\n\n# Compute centrality and find most central node\nbc = nx.betweenness_centrality(G)\ntop_node = max(bc, key=bc.get)\nprint(f\"Most central node: {top_node}, betweenness: {bc[top_node]:.3f}\")\n\n# Detect communities\nfrom networkx.algorithms import community\ncomms = community.greedy_modularity_communities(G)\nprint(f\"Communities found: {len(comms)}\")\n```\n\n## Core API\n\n### Module 1: Graph Creation and Types\n\n```python\nimport networkx as nx\n\n# Undirected graph (most common)\nG = nx.Graph()\nG.add_node(\"protein_A\", type=\"kinase\", weight=1.5)\nG.add_nodes_from([\"protein_B\", \"protein_C\"])\nG.add_edge(\"protein_A\", \"protein_B\", weight=0.9, interaction=\"phosphorylation\")\nG.add_edges_from([(\"protein_B\", \"protein_C\"), (\"protein_A\", \"protein_C\")])\nprint(f\"Nodes: {G.number_of_nodes()}, Edges: {G.number_of_edges()}\")\n# Nodes: 3, Edges: 3\n\n# Directed graph (gene regulation, citations)\nD = nx.DiGraph()\nD.add_edges_from([(\"TF1\", \"geneA\"), (\"TF1\", \"geneB\"), (\"TF2\", \"geneA\")])\nprint(f\"TF1 out-degree: {D.out_degree('TF1')}\")  # 2\n\n# MultiGraph (multiple relationship types between same nodes)\nM = nx.MultiGraph()\nM.add_edge(\"A\", \"B\", key=\"binding\", affinity=0.8)\nM.add_edge(\"A\", \"B\", key=\"regulation\", effect=\"inhibition\")\nprint(f\"Edges between A-B: {M.number_of_edges('A', 'B')}\")  # 2\n```\n\n### Module 2: Node and Edge Operations\n\n```python\nimport networkx as nx\nG = nx.karate_club_graph()\n\n# Query structure\nprint(f\"Degree of node 0: {G.degree(0)}\")\nprint(f\"Neighbors of node 0: {list(G.neighbors(0))[:5]}\")\nprint(f\"Has edge 0-1: {G.has_edge(0, 1)}\")\n\n# Set and get attributes\nG.nodes[0][\"role\"] = \"instructor\"\nnx.set_node_attributes(G, {0: \"high\", 33: \"high\"}, \"importance\")\nG[0][1][\"weight\"] = 0.95\n\n# Iterate with data\nfor u, v, data in G.edges(data=True):\n    if \"weight\" in data:\n        print(f\"  Edge {u}-{v}: weight={data['weight']}\")\n        break\n\n# Subgraphs (returns read-only view; use .copy() for mutable)\nH = G.subgraph([0, 1, 2, 3, 4, 5]).copy()\nprint(f\"Subgraph: {H.number_of_nodes()} nodes, {H.number_of_edges()} edges\")\n```\n\n### Module 3: Graph Analysis (Centrality)\n\n```python\nimport networkx as nx\nG = nx.karate_club_graph()\n\ndegree_c = nx.degree_centrality(G)\nbetween_c = nx.betweenness_centrality(G, weight=\"weight\")\n# For large graphs, approximate: nx.betweenness_centrality(G, k=100)\nclose_c = nx.closeness_centrality(G)\neigen_c = nx.eigenvector_centrality(G, max_iter=1000)\npr = nx.pagerank(G, alpha=0.85)\n\n# Compare top nodes across measures\nfor name, metric in [(\"Degree\", degree_c), (\"Betweenness\", between_c),\n                     (\"Closeness\", close_c), (\"PageRank\", pr)]:\n    top = max(metric, key=metric.get)\n    print(f\"{name:12s}: top node={top}, score={metric[top]:.4f}\")\n```\n\n### Module 4: Path and Connectivity\n\n```python\nimport networkx as nx\nG = nx.karate_club_graph()\n\n# Shortest path\npath = nx.shortest_path(G, source=0, target=33)\nlength = nx.shortest_path_length(G, source=0, target=33)\nprint(f\"Shortest path 0->33: {path} (length {length})\")\nprint(f\"Average shortest path length: {nx.average_shortest_path_length(G):.3f}\")\n\n# Connected components\nprint(f\"Connected: {nx.is_connected(G)}\")\ncomponents = list(nx.connected_components(G))\nprint(f\"Components: {len(components)}, largest: {len(max(components, key=len))}\")\n\n# For directed graphs: strong\u002Fweak connectivity\nD = nx.DiGraph([(0,1),(1,2),(2,0),(3,4)])\nprint(f\"Strongly connected: {list(nx.strongly_connected_components(D))}\")\n\n# Connectivity measures\nprint(f\"Node connectivity: {nx.node_connectivity(G)}\")\nprint(f\"Edge connectivity: {nx.edge_connectivity(G)}\")\n```\n\n### Module 5: Community Detection\n\nPartition networks into densely connected groups.\n\n```python\nimport networkx as nx\nfrom networkx.algorithms import community\nimport itertools\n\nG = nx.karate_club_graph()\n\n# Greedy modularity maximization\ncomms_greedy = community.greedy_modularity_communities(G)\nmod_score = community.modularity(G, comms_greedy)\nprint(f\"Greedy: {len(comms_greedy)} communities, modularity={mod_score:.4f}\")\n\n# Label propagation (fast, non-deterministic)\ncomms_lpa = community.label_propagation_communities(G)\nprint(f\"Label propagation: {len(list(comms_lpa))} communities\")\n\n# Girvan-Newman (hierarchical, edge betweenness removal)\ngn = community.girvan_newman(G)\n# Get first level of partition\nfirst_level = next(gn)\nprint(f\"Girvan-Newman first split: {len(first_level)} groups\")\nprint(f\"  Sizes: {[len(c) for c in first_level]}\")\n```\n\n### Module 6: I\u002FO and Serialization\n\n```python\nimport networkx as nx\nimport pandas as pd\nimport json\n\nG = nx.karate_club_graph()\n\n# Edge list (simple text format)\nnx.write_edgelist(G, \"karate.edgelist\")\nG_loaded = nx.read_edgelist(\"karate.edgelist\", nodetype=int)\n\n# GraphML (preserves all attributes, XML-based)\nnx.write_graphml(G, \"karate.graphml\")\nG_xml = nx.read_graphml(\"karate.graphml\")\n\n# JSON (node-link format, web-friendly for d3.js)\ndata = nx.node_link_data(G)\nwith open(\"karate.json\", \"w\") as f:\n    json.dump(data, f)\n\n# Pandas integration\ndf = pd.DataFrame({\"source\": [1,2,3], \"target\": [2,3,4], \"weight\": [0.5,1.0,0.75]})\nG_pd = nx.from_pandas_edgelist(df, \"source\", \"target\", edge_attr=\"weight\")\ndf_out = nx.to_pandas_edgelist(G_pd)\nprint(f\"Pandas round-trip: {len(df_out)} edges\")\n\n# NumPy\u002FSciPy matrices\nA = nx.to_numpy_array(G)\nprint(f\"Adjacency matrix shape: {A.shape}\")\nA_sparse = nx.to_scipy_sparse_array(G, format=\"csr\")  # Memory-efficient\n```\n\n### Module 7: Visualization\n\n```python\nimport networkx as nx\nimport matplotlib.pyplot as plt\n\nG = nx.karate_club_graph()\npos = nx.spring_layout(G, seed=42)\n\n# Color by degree, size by betweenness centrality\nbc = nx.betweenness_centrality(G)\nfig, ax = plt.subplots(figsize=(10, 8))\nnx.draw(G, pos=pos, ax=ax,\n        node_color=[G.degree(n) for n in G.nodes()], cmap=plt.cm.viridis,\n        node_size=[3000 * bc[n] + 100 for n in G.nodes()],\n        edge_color=\"gray\", alpha=0.8, with_labels=True, font_size=8)\nplt.tight_layout()\nplt.savefig(\"network.png\", dpi=300, bbox_inches=\"tight\")\nplt.savefig(\"network.pdf\", bbox_inches=\"tight\")  # Vector format\nprint(\"Saved network.png and network.pdf\")\n```\n\n### Module 8: Generators\n\n```python\nimport networkx as nx\n\n# Erdos-Renyi random graph: n nodes, edge probability p\nG_er = nx.erdos_renyi_graph(n=200, p=0.05, seed=42)\nprint(f\"ER: {G_er.number_of_nodes()} nodes, {G_er.number_of_edges()} edges\")\n\n# Barabasi-Albert scale-free (power-law degree distribution)\nG_ba = nx.barabasi_albert_graph(n=200, m=3, seed=42)\n\n# Watts-Strogatz small-world\nG_ws = nx.watts_strogatz_graph(n=200, k=6, p=0.1, seed=42)\nprint(f\"WS clustering: {nx.average_clustering(G_ws):.3f}\")\n\n# Stochastic block model (community structure)\nsizes, probs = [50, 50, 50], [[0.25,0.05,0.02],[0.05,0.35,0.07],[0.02,0.07,0.40]]\nG_sbm = nx.stochastic_block_model(sizes, probs, seed=42)\n\n# Built-in datasets and classic graphs\nG_karate = nx.karate_club_graph()       # Zachary's karate club\nG_grid = nx.grid_2d_graph(5, 7)         # 2D lattice\nG_tree = nx.random_tree(n=50, seed=42)  # Random tree\nG_geo = nx.random_geometric_graph(n=100, radius=0.2, seed=42)\n# See references\u002Falgorithms_generators.md for full generator catalog\n```\n\n## Key Concepts\n\n### Graph Types\n\n| Class | Directed | Multi-edge | Self-loops | Use Case |\n|-------|----------|------------|------------|----------|\n| `Graph` | No | No | Yes | Undirected networks: social, PPI |\n| `DiGraph` | Yes | No | Yes | Gene regulation, citations, web |\n| `MultiGraph` | No | Yes | Yes | Multiple relationship types |\n| `MultiDiGraph` | Yes | Yes | Yes | Transportation with routes |\n\n### Attribute Patterns\n\nAttributes are stored as dictionaries at graph, node, and edge levels:\n\n```python\nimport networkx as nx\nG = nx.Graph(name=\"example\")              # Graph-level attribute\nG.add_node(1, label=\"hub\", weight=1.5)    # Node attributes\nG.add_edge(1, 2, weight=0.8, type=\"ppi\")  # Edge attributes\n\n# Bulk set\u002Fget\nnx.set_node_attributes(G, {1: \"red\", 2: \"blue\"}, \"color\")\ncolors = nx.get_node_attributes(G, \"color\")  # {1: 'red', 2: 'blue'}\n```\n\n### Layout Algorithms\n\n| Layout | Function | Best For |\n|--------|----------|----------|\n| Spring (force-directed) | `spring_layout(G, seed=42)` | General networks |\n| Circular | `circular_layout(G)` | Regular graphs, cycles |\n| Kamada-Kawai | `kamada_kawai_layout(G)` | Small-medium networks |\n| Spectral | `spectral_layout(G)` | Highlighting clusters |\n| Shell (concentric) | `shell_layout(G, nlist=[[...],[...]])` | Layered\u002Fhierarchical |\n| Planar | `planar_layout(G)` | Planar graphs only |\n\n## Common Workflows\n\n### Workflow 1: Social Network Analysis\n\n**Goal**: Identify influential actors, detect communities, and visualize.\n\n```python\nimport networkx as nx\nimport matplotlib.pyplot as plt\nfrom networkx.algorithms import community\n\n# Step 1: Load network and basic stats\nG = nx.karate_club_graph()\nprint(f\"Network: {G.number_of_nodes()} actors, {G.number_of_edges()} ties\")\nprint(f\"Density: {nx.density(G):.4f}, Clustering: {nx.average_clustering(G):.4f}\")\n\n# Step 2: Identify influential nodes\nbc = nx.betweenness_centrality(G)\ntop_bc = sorted(bc.items(), key=lambda x: x[1], reverse=True)[:5]\nprint(\"Top 5 by betweenness:\", [(n, f\"{s:.3f}\") for n, s in top_bc])\n\n# Step 3: Detect communities\ncomms = community.greedy_modularity_communities(G)\nprint(f\"Communities: {len(comms)}, modularity: {community.modularity(G, comms):.4f}\")\n\n# Step 4: Visualize with community coloring\npos = nx.spring_layout(G, seed=42)\nfig, ax = plt.subplots(figsize=(10, 8))\nfor i, comm in enumerate(comms):\n    nx.draw_networkx_nodes(G, pos, nodelist=list(comm), ax=ax,\n                           node_color=[plt.cm.Set2(i)]*len(comm), node_size=400)\nnx.draw_networkx_edges(G, pos, ax=ax, alpha=0.3)\nnx.draw_networkx_labels(G, pos, ax=ax, font_size=8)\nplt.axis(\"off\")\nplt.tight_layout()\nplt.savefig(\"social_network_analysis.png\", dpi=300, bbox_inches=\"tight\")\nprint(\"Saved social_network_analysis.png\")\n```\n\n### Workflow 2: Biological Interaction Network\n\n**Goal**: Build a PPI network from tabular data, analyze topology, and identify hub proteins.\n\n```python\nimport networkx as nx\nimport pandas as pd\n\n# Step 1: Load interaction data from DataFrame\ninteractions = pd.DataFrame({\n    \"protein_a\": [\"TP53\",\"TP53\",\"BRCA1\",\"BRCA1\",\"MDM2\",\"ATM\",\"ATM\",\"CHEK2\",\"RB1\",\"CDK2\"],\n    \"protein_b\": [\"MDM2\",\"BRCA1\",\"ATM\",\"CHEK2\",\"RB1\",\"CHEK2\",\"BRCA2\",\"CDC25A\",\"CDK2\",\"CCNA2\"],\n    \"score\": [0.99, 0.95, 0.92, 0.88, 0.91, 0.97, 0.85, 0.90, 0.87, 0.93]\n})\nG = nx.from_pandas_edgelist(interactions, \"protein_a\", \"protein_b\",\n                             edge_attr=\"score\")\nprint(f\"PPI network: {G.number_of_nodes()} proteins, {G.number_of_edges()} interactions\")\n\n# Step 2: Network statistics\nprint(f\"Connected: {nx.is_connected(G)}\")\nprint(f\"Diameter: {nx.diameter(G)}\")\nprint(f\"Avg path length: {nx.average_shortest_path_length(G):.2f}\")\nprint(f\"Transitivity: {nx.transitivity(G):.4f}\")\n\n# Step 3: Hub identification (multiple centrality measures)\ndegree_c = nx.degree_centrality(G)\nbetween_c = nx.betweenness_centrality(G)\nclose_c = nx.closeness_centrality(G)\n\nresults = pd.DataFrame({\n    \"protein\": list(G.nodes()),\n    \"degree_centrality\": [degree_c[n] for n in G.nodes()],\n    \"betweenness\": [between_c[n] for n in G.nodes()],\n    \"closeness\": [close_c[n] for n in G.nodes()],\n}).sort_values(\"betweenness\", ascending=False)\nprint(\"\\nHub proteins:\")\nprint(results.head(5).to_string(index=False))\n\n# Step 4: Export for downstream analysis\nnx.write_graphml(G, \"ppi_network.graphml\")\nresults.to_csv(\"protein_centrality.csv\", index=False)\nprint(\"Exported ppi_network.graphml and protein_centrality.csv\")\n```\n\n## Key Parameters\n\n| Parameter | Module | Default | Range \u002F Options | Effect |\n|-----------|--------|---------|-----------------|--------|\n| `weight` | Paths\u002FCentrality | `None` | Edge attribute name | Use weighted edges for path\u002Fcentrality calculations |\n| `alpha` | `pagerank` | `0.85` | `0.0`-`1.0` | Damping factor; lower = more uniform distribution |\n| `k` | `betweenness_centrality` | `None` | `int` | Sample k nodes for approximation on large graphs |\n| `max_iter` | `eigenvector_centrality` | `100` | `int` | Max iterations for convergence |\n| `seed` | Generators\u002FLayouts | `None` | `int` | Random seed for reproducibility |\n| `n` \u002F `p` \u002F `m` | ER\u002FBA generators | varies | `int`\u002F`float` | Node count, edge probability, edges per new node |\n| `k` \u002F `p` | Watts-Strogatz | varies | `int`\u002F`float` | Nearest neighbors, rewiring probability |\n| `nodetype` | `read_edgelist` | `str` | `int`, `float`, `str` | Type conversion for node identifiers |\n| `edge_attr` | `from_pandas_edgelist` | `None` | Column name(s) | Edge attribute columns to include from DataFrame |\n| `format` | `to_scipy_sparse_array` | `\"csc\"` | `\"csr\"`, `\"csc\"`, `\"coo\"` | Sparse matrix format |\n\n## Best Practices\n\n1. **Always set random seeds** for reproducible generators and layouts: `seed=42` in both `erdos_renyi_graph()` and `spring_layout()`.\n\n2. **Use approximate algorithms for large graphs**: `nx.betweenness_centrality(G, k=500)` samples k nodes instead of all pairs.\n\n3. **Prefer `from_pandas_edgelist`** over manual `add_edge` loops for bulk data loading -- handles attributes cleanly and is faster.\n\n4. **Copy subgraphs before modification**: `G.subgraph(nodes)` returns a read-only view; call `.copy()` for a mutable independent graph.\n\n5. **Use GraphML or GML for persistent storage** to preserve all node\u002Fedge attributes. Edge lists lose metadata unless explicitly handled.\n\n6. **Convert graph types explicitly**: `D.to_undirected()` (DiGraph -> Graph), `nx.Graph(M)` (MultiGraph -> Graph, collapses multi-edges).\n\n7. **Use sparse matrices for large adjacency exports**: `to_scipy_sparse_array()` is far more memory-efficient than `to_numpy_array()`.\n\n8. **Anti-pattern -- Don't use `nx.info()`**: Deprecated; use `G.number_of_nodes()`, `G.number_of_edges()`, `nx.density(G)` directly.\n\n9. **Anti-pattern -- Don't assume node ordering**: Algorithms may return results in different orders. Always index by node key, not position.\n\n## Common Recipes\n\n### Recipe: Minimum Spanning Tree\n\nExtract the minimum spanning tree and compare to the original graph.\n\n```python\nimport networkx as nx\n\n# Create weighted graph\nG = nx.erdos_renyi_graph(50, 0.15, seed=42)\nfor u, v in G.edges():\n    G[u][v][\"weight\"] = round(nx.utils.py_random_state(42).random(), 2)\n\nmst = nx.minimum_spanning_tree(G, weight=\"weight\")\nprint(f\"Original: {G.number_of_edges()} edges\")\nprint(f\"MST: {mst.number_of_edges()} edges\")\ntotal_weight = sum(d[\"weight\"] for _, _, d in mst.edges(data=True))\nprint(f\"MST total weight: {total_weight:.2f}\")\n```\n\n### Recipe: Graph Coloring and Cliques\n\nFind cliques and compute graph coloring.\n\n```python\nimport networkx as nx\n\nG = nx.karate_club_graph()\n\n# Find all maximal cliques\ncliques = list(nx.find_cliques(G))\nprint(f\"Maximal cliques: {len(cliques)}\")\nlargest_clique = max(cliques, key=len)\nprint(f\"Largest clique size: {len(largest_clique)}, nodes: {largest_clique}\")\n\n# Greedy graph coloring\ncoloring = nx.greedy_color(G, strategy=\"largest_first\")\nn_colors = max(coloring.values()) + 1\nprint(f\"Chromatic number (greedy upper bound): {n_colors}\")\n```\n\n### Recipe: DAG and Topological Sort\n\nBuild a directed acyclic graph and find execution order.\n\n```python\nimport networkx as nx\n\n# Task dependency DAG\nD = nx.DiGraph()\nD.add_edges_from([\n    (\"download_data\", \"preprocess\"),\n    (\"download_data\", \"validate\"),\n    (\"preprocess\", \"analyze\"),\n    (\"validate\", \"analyze\"),\n    (\"analyze\", \"visualize\"),\n    (\"analyze\", \"report\"),\n    (\"visualize\", \"report\"),\n])\n\nprint(f\"Is DAG: {nx.is_directed_acyclic_graph(D)}\")\norder = list(nx.topological_sort(D))\nprint(f\"Execution order: {order}\")\n\n# Find all paths from start to end\npaths = list(nx.all_simple_paths(D, \"download_data\", \"report\"))\nprint(f\"Paths to report: {len(paths)}\")\nfor p in paths:\n    print(f\"  {' -> '.join(p)}\")\n```\n\n## Troubleshooting\n\n| Problem | Cause | Solution |\n|---------|-------|----------|\n| `NetworkXError: Graph is not connected` | Algorithm requires connected graph | Extract largest component: `G.subgraph(max(nx.connected_components(G), key=len)).copy()` |\n| `PowerIterationFailedConvergence` | Eigenvector\u002FPageRank did not converge | Increase `max_iter` (e.g., 1000) or check for disconnected components |\n| Very slow centrality computation | O(n*m) complexity on large graphs | Use `k` parameter for sampling: `betweenness_centrality(G, k=500)` |\n| `nx.NetworkXNotImplemented` | Algorithm not available for graph type | Convert graph type: `G.to_undirected()` or `G.to_directed()` |\n| Memory error on large graphs | Dense adjacency matrix | Use `to_scipy_sparse_array()` instead of `to_numpy_array()` |\n| Node IDs read as strings from file | `read_edgelist` defaults to `str` | Pass `nodetype=int`: `nx.read_edgelist(f, nodetype=int)` |\n| Community detection returns frozen sets | Normal return type for communities | Convert: `[list(c) for c in communities]` |\n| Self-loops in generated graphs | Configuration model allows self-loops | Remove: `G.remove_edges_from(nx.selfloop_edges(G))` |\n| Visualization too cluttered | Too many nodes\u002Fedges | Filter to subgraph, adjust `alpha`, increase figure size, or use interactive tools (Plotly, PyVis) |\n\n## Bundled Resources\n\nMigrated from original entry (STUB: 436-line main file + 2,014 lines across 5 reference files, main\u002Ftotal = 17.8%).\n\n### references\u002Falgorithms_generators.md\n\nCovers: Detailed algorithm parameters for traversal (DFS\u002FBFS), cycles, cliques, graph coloring, isomorphism, matching\u002Fcovering, tree algorithms (MST variants). Full generator catalog: classic graphs, lattice\u002Fgrid, tree, bipartite, degree sequence, graph operations (union, compose, complement, products).\nRelocated inline: Core algorithms (centrality, paths, connectivity, community, flow) -> Core API Modules 3-5. Core generators (ER, BA, WS, SBM) -> Module 8.\nOmitted: A* heuristic customization, Bellman-Ford negative weights -- consult official docs.\n\n**Original file disposition**:\n- `algorithms.md` (383 lines): Top algorithms relocated to Core API Modules 3-5 + Recipes. Remaining (traversal, cliques, coloring, isomorphism, matching, cycles, trees) -> this reference.\n- `generators.md` (378 lines): Core generators relocated to Module 8. Full catalog (classic, lattice, tree, bipartite, degree sequence, operators) -> this reference.\n\n### references\u002Fio_visualization.md\n\nCovers: All I\u002FO formats (adjacency list, GEXF, Pajek, LEDA, Cytoscape JSON, DOT\u002FGraphviz, Matrix Market, CSV, database\u002FSQL, compressed gzip). Format selection guide. Advanced visualization: Plotly interactive, PyVis HTML, Graphviz layouts, 3D networks, bipartite layout, community coloring, subgraph highlighting, multi-panel figures, edge labels, directed arrows.\nRelocated inline: Core I\u002FO (edge list, GraphML, JSON, pandas, NumPy\u002FSciPy) -> Module 6. Basic matplotlib -> Module 7.\nOmitted: `write_gpickle`\u002F`read_gpickle` (deprecated), `read_shp`\u002F`write_shp` (removed in NetworkX 3.0; use geopandas).\n\n**Original file disposition**:\n- `io.md` (441 lines): Core formats relocated to Module 6. Remaining formats + format selection guide -> this reference.\n- `visualization.md` (529 lines): Basic matplotlib relocated to Module 7. Advanced techniques (Plotly, PyVis, 3D, bipartite, community coloring) -> this reference.\n\n### Fully consolidated original file\n\n- `graph-basics.md` (283 lines): Fully consolidated into main SKILL.md. Graph types -> Key Concepts. Node\u002Fedge operations, attributes, subgraphs -> Core API Modules 1-2. Diagnostics -> Common Workflows. Memory\u002Ffloat-point considerations -> Best Practices + Troubleshooting. Omitted: `nx.info()` (deprecated).\n\n## Related Skills\n\n- **torch-geometric-graph-neural-networks** -- graph neural networks (GCN, GAT, GraphSAGE) for node\u002Fgraph classification and link prediction on graph-structured data\n- **matplotlib-scientific-plotting** -- advanced figure customization beyond NetworkX's built-in `nx.draw`\n- **plotly-interactive-plots** -- interactive network plots with hover, zoom, and pan\n- **pandas** (planned) -- DataFrame operations for preparing edge\u002Fnode data before graph construction\n- **scipy** (planned) -- sparse matrix operations and numerical algorithms used by NetworkX internally\n\n## References\n\n- [NetworkX documentation](https:\u002F\u002Fnetworkx.org\u002Fdocumentation\u002Flatest\u002F) -- official docs and API reference\n- [NetworkX tutorial](https:\u002F\u002Fnetworkx.org\u002Fdocumentation\u002Flatest\u002Ftutorial.html) -- official getting started guide\n- [NetworkX GitHub](https:\u002F\u002Fgithub.com\u002Fnetworkx\u002Fnetworkx) -- source code and issue tracker\n- [NetworkX gallery](https:\u002F\u002Fnetworkx.org\u002Fdocumentation\u002Flatest\u002Fauto_examples\u002Findex.html) -- example gallery with visualizations\n- Hagberg, A., Schult, D., & Swart, P. (2008). Exploring network structure, dynamics, and function using NetworkX. SciPy 2008.\n","# NetworkX Graph Analysis\n\n## Overview\n\nNetworkX is a Python library for creating, manipulating, and analyzing complex networks and graphs. It provides data structures for undirected, directed, and multi-edge graphs along with a comprehensive collection of graph algorithms, generators, and I\u002FO utilities. Use NetworkX when working with relationship data in social networks, biological interaction networks, transportation systems, citation graphs, or any domain involving pairwise entity relationships.\n\n## When to Use\n\n- Analyzing protein-protein interaction networks, gene regulatory networks, or metabolic pathways\n- Computing centrality measures (degree, betweenness, PageRank) to identify important nodes\n- Finding shortest paths or optimal routes in transportation or communication networks\n- Detecting communities or clusters in social networks or co-expression data\n- Generating synthetic networks (scale-free, small-world, random) for simulation or null models\n- Reading and writing graph data in standard formats (GraphML, GML, edge lists, JSON)\n- Visualizing network topology with node\u002Fedge attribute mapping\n- Checking graph properties: connectivity, planarity, isomorphism, DAG structure\n- For large-scale graphs (100K+ nodes) where speed is critical, use `igraph` or `graph-tool` instead\n- For billion-edge graphs or GPU-accelerated analytics, use `graph-tool` with OpenMP or `cuGraph`\n- For graph neural networks and deep learning on graphs, use `torch-geometric-graph-neural-networks`\n\n## Prerequisites\n\n- **Python packages**: `networkx`, `matplotlib`, `scipy`, `pandas`, `numpy`\n- **Optional**: `pydot` or `pygraphviz` (Graphviz layouts)\n\n```bash\npip install networkx matplotlib scipy pandas numpy\n```\n\n## Quick Start\n\n```python\nimport networkx as nx\n\n# Create a graph and add edges with weights\nG = nx.karate_club_graph()\nprint(f\"Nodes: {G.number_of_nodes()}, Edges: {G.number_of_edges()}\")\n# Nodes: 34, Edges: 78\n\n# Compute centrality and find most central node\nbc = nx.betweenness_centrality(G)\ntop_node = max(bc, key=bc.get)\nprint(f\"Most central node: {top_node}, betweenness: {bc[top_node]:.3f}\")\n\n# Detect communities\nfrom networkx.algorithms import community\ncomms = community.greedy_modularity_communities(G)\nprint(f\"Communities found: {len(comms)}\")\n```\n\n## Core API\n\n### Module 1: Graph Creation and Types\n\n```python\nimport networkx as nx\n\n# Undirected graph (most common)\nG = nx.Graph()\nG.add_node(\"protein_A\", type=\"kinase\", weight=1.5)\nG.add_nodes_from([\"protein_B\", \"protein_C\"])\nG.add_edge(\"protein_A\", \"protein_B\", weight=0.9, interaction=\"phosphorylation\")\nG.add_edges_from([(\"protein_B\", \"protein_C\"), (\"protein_A\", \"protein_C\")])\nprint(f\"Nodes: {G.number_of_nodes()}, Edges: {G.number_of_edges()}\")\n# Nodes: 3, Edges: 3\n\n# Directed graph (gene regulation, citations)\nD = nx.DiGraph()\nD.add_edges_from([(\"TF1\", \"geneA\"), (\"TF1\", \"geneB\"), (\"TF2\", \"geneA\")])\nprint(f\"TF1 out-degree: {D.out_degree('TF1')}\")  # 2\n\n# MultiGraph (multiple relationship types between same nodes)\nM = nx.MultiGraph()\nM.add_edge(\"A\", \"B\", key=\"binding\", affinity=0.8)\nM.add_edge(\"A\", \"B\", key=\"regulation\", effect=\"inhibition\")\nprint(f\"Edges between A-B: {M.number_of_edges('A', 'B')}\")  # 2\n```\n\n### Module 2: Node and Edge Operations\n\n```python\nimport networkx as nx\nG = nx.karate_club_graph()\n\n# Query structure\nprint(f\"Degree of node 0: {G.degree(0)}\")\nprint(f\"Neighbors of node 0: {list(G.neighbors(0))[:5]}\")\nprint(f\"Has edge 0-1: {G.has_edge(0, 1)}\")\n\n# Set and get attributes\nG.nodes[0][\"role\"] = \"instructor\"\nnx.set_node_attributes(G, {0: \"high\", 33: \"high\"}, \"importance\")\nG[0][1][\"weight\"] = 0.95\n\n# Iterate with data\nfor u, v, data in G.edges(data=True):\n    if \"weight\" in data:\n        print(f\"  Edge {u}-{v}: weight={data['weight']}\")\n        break\n\n# Subgraphs (returns read-only view; use .copy() for mutable)\nH = G.subgraph([0, 1, 2, 3, 4, 5]).copy()\nprint(f\"Subgraph: {H.number_of_nodes()} nodes, {H.number_of_edges()} edges\")\n```\n\n### Module 3: Graph Analysis (Centrality)\n\n```python\nimport networkx as nx\nG = nx.karate_club_graph()\n\ndegree_c = nx.degree_centrality(G)\nbetween_c = nx.betweenness_centrality(G, weight=\"weight\")\n# For large graphs, approximate: nx.betweenness_centrality(G, k=100)\nclose_c = nx.closeness_centrality(G)\neigen_c = nx.eigenvector_centrality(G, max_iter=1000)\npr = nx.pagerank(G, alpha=0.85)\n\n# Compare top nodes across measures\nfor name, metric in [(\"Degree\", degree_c), (\"Betweenness\", between_c),\n                     (\"Closeness\", close_c), (\"PageRank\", pr)]:\n    top = max(metric, key=metric.get)\n    print(f\"{name:12s}: top node={top}, score={metric[top]:.4f}\")\n```\n\n### Module 4: Path and Connectivity\n\n```python\nimport networkx as nx\nG = nx.karate_club_graph()\n\n# Shortest path\npath = nx.shortest_path(G, source=0, target=33)\nlength = nx.shortest_path_length(G, source=0, target=33)\nprint(f\"Shortest path 0->33: {path} (length {length})\")\nprint(f\"Average shortest path length: {nx.average_shortest_path_length(G):.3f}\")\n\n# Connected components\nprint(f\"Connected: {nx.is_connected(G)}\")\ncomponents = list(nx.connected_components(G))\nprint(f\"Components: {len(components)}, largest: {len(max(components, key=len))}\")\n\n# For directed graphs: strong\u002Fweak connectivity\nD = nx.DiGraph([(0,1),(1,2),(2,0),(3,4)])\nprint(f\"Strongly connected: {list(nx.strongly_connected_components(D))}\")\n\n# Connectivity measures\nprint(f\"Node connectivity: {nx.node_connectivity(G)}\")\nprint(f\"Edge connectivity: {nx.edge_connectivity(G)}\")\n```\n\n### Module 5: Community Detection\n\nPartition networks into densely connected groups.\n\n```python\nimport networkx as nx\nfrom networkx.algorithms import community\nimport itertools\n\nG = nx.karate_club_graph()\n\n# Greedy modularity maximization\ncomms_greedy = community.greedy_modularity_communities(G)\nmod_score = community.modularity(G, comms_greedy)\nprint(f\"Greedy: {len(comms_greedy)} communities, modularity={mod_score:.4f}\")\n\n# Label propagation (fast, non-deterministic)\ncomms_lpa = community.label_propagation_communities(G)\nprint(f\"Label propagation: {len(list(comms_lpa))} communities\")\n\n# Girvan-Newman (hierarchical, edge betweenness removal)\ngn = community.girvan_newman(G)\n# Get first level of partition\nfirst_level = next(gn)\nprint(f\"Girvan-Newman first split: {len(first_level)} groups\")\nprint(f\"  Sizes: {[len(c) for c in first_level]}\")\n```\n\n### Module 6: I\u002FO and Serialization\n\n```python\nimport networkx as nx\nimport pandas as pd\nimport json\n\nG = nx.karate_club_graph()\n\n# Edge list (simple text format)\nnx.write_edgelist(G, \"karate.edgelist\")\nG_loaded = nx.read_edgelist(\"karate.edgelist\", nodetype=int)\n\n# GraphML (preserves all attributes, XML-based)\nnx.write_graphml(G, \"karate.graphml\")\nG_xml = nx.read_graphml(\"karate.graphml\")\n\n# JSON (node-link format, web-friendly for d3.js)\ndata = nx.node_link_data(G)\nwith open(\"karate.json\", \"w\") as f:\n    json.dump(data, f)\n\n# Pandas integration\ndf = pd.DataFrame({\"source\": [1,2,3], \"target\": [2,3,4], \"weight\": [0.5,1.0,0.75]})\nG_pd = nx.from_pandas_edgelist(df, \"source\", \"target\", edge_attr=\"weight\")\ndf_out = nx.to_pandas_edgelist(G_pd)\nprint(f\"Pandas round-trip: {len(df_out)} edges\")\n\n# NumPy\u002FSciPy matrices\nA = nx.to_numpy_array(G)\nprint(f\"Adjacency matrix shape: {A.shape}\")\nA_sparse = nx.to_scipy_sparse_array(G, format=\"csr\")  # Memory-efficient\n```\n\n### Module 7: Visualization\n\n```python\nimport networkx as nx\nimport matplotlib.pyplot as plt\n\nG = nx.karate_club_graph()\npos = nx.spring_layout(G, seed=42)\n\n# Color by degree, size by betweenness centrality\nbc = nx.betweenness_centrality(G)\nfig, ax = plt.subplots(figsize=(10, 8))\nnx.draw(G, pos=pos, ax=ax,\n        node_color=[G.degree(n) for n in G.nodes()], cmap=plt.cm.viridis,\n        node_size=[3000 * bc[n] + 100 for n in G.nodes()],\n        edge_color=\"gray\", alpha=0.8, with_labels=True, font_size=8)\nplt.tight_layout()\nplt.savefig(\"network.png\", dpi=300, bbox_inches=\"tight\")\nplt.savefig(\"network.pdf\", bbox_inches=\"tight\")  # Vector format\nprint(\"Saved network.png and network.pdf\")\n```\n\n### Module 8: Generators\n\n```python\nimport networkx as nx\n\n# Erdos-Renyi random graph: n nodes, edge probability p\nG_er = nx.erdos_renyi_graph(n=200, p=0.05, seed=42)\nprint(f\"ER: {G_er.number_of_nodes()} nodes, {G_er.number_of_edges()} edges\")\n\n# Barabasi-Albert scale-free (power-law degree distribution)\nG_ba = nx.barabasi_albert_graph(n=200, m=3, seed=42)\n\n# Watts-Strogatz small-world\nG_ws = nx.watts_strogatz_graph(n=200, k=6, p=0.1, seed=42)\nprint(f\"WS clustering: {nx.average_clustering(G_ws):.3f}\")\n\n# Stochastic block model (community structure)\nsizes, probs = [50, 50, 50], [[0.25,0.05,0.02],[0.05,0.35,0.07],[0.02,0.07,0.40]]\nG_sbm = nx.stochastic_block_model(sizes, probs, seed=42)\n\n# Built-in datasets and classic graphs\nG_karate = nx.karate_club_graph()       # Zachary's karate club\nG_grid = nx.grid_2d_graph(5, 7)         # 2D lattice\nG_tree = nx.random_tree(n=50, seed=42)  # Random tree\nG_geo = nx.random_geometric_graph(n=100, radius=0.2, seed=42)\n# See references\u002Falgorithms_generators.md for full generator catalog\n```\n\n## Key Concepts\n\n### Graph Types\n\n| Class | Directed | Multi-edge | Self-loops | Use Case |\n|-------|----------|------------|------------|----------|\n| `Graph` | No | No | Yes | Undirected networks: social, PPI |\n| `DiGraph` | Yes | No | Yes | Gene regulation, citations, web |\n| `MultiGraph` | No | Yes | Yes | Multiple relationship types |\n| `MultiDiGraph` | Yes | Yes | Yes | Transportation with routes |\n\n### Attribute Patterns\n\nAttributes are stored as dictionaries at graph, node, and edge levels:\n\n```python\nimport networkx as nx\nG = nx.Graph(name=\"example\")              # Graph-level attribute\nG.add_node(1, label=\"hub\", weight=1.5)    # Node attributes\nG.add_edge(1, 2, weight=0.8, type=\"ppi\")  # Edge attributes\n\n# Bulk set\u002Fget\nnx.set_node_attributes(G, {1: \"red\", 2: \"blue\"}, \"color\")\ncolors = nx.get_node_attributes(G, \"color\")  # {1: 'red', 2: 'blue'}\n```\n\n### Layout Algorithms\n\n| Layout | Function | Best For |\n|--------|----------|----------|\n| Spring (force-directed) | `spring_layout(G, seed=42)` | General networks |\n| Circular | `circular_layout(G)` | Regular graphs, cycles |\n| Kamada-Kawai | `kamada_kawai_layout(G)` | Small-medium networks |\n| Spectral | `spectral_layout(G)` | Highlighting clusters |\n| Shell (concentric) | `shell_layout(G, nlist=[[...],[...]])` | Layered\u002Fhierarchical |\n| Planar | `planar_layout(G)` | Planar graphs only |\n\n## Common Workflows\n\n### Workflow 1: Social Network Analysis\n\n**Goal**: Identify influential actors, detect communities, and visualize.\n\n```python\nimport networkx as nx\nimport matplotlib.pyplot as plt\nfrom networkx.algorithms import community\n\n# Step 1: Load network and basic stats\nG = nx.karate_club_graph()\nprint(f\"Network: {G.number_of_nodes()} actors, {G.number_of_edges()} ties\")\nprint(f\"Density: {nx.density(G):.4f}, Clustering: {nx.average_clustering(G):.4f}\")\n\n# Step 2: Identify influential nodes\nbc = nx.betweenness_centrality(G)\ntop_bc = sorted(bc.items(), key=lambda x: x[1], reverse=True)[:5]\nprint(\"Top 5 by betweenness:\", [(n, f\"{s:.3f}\") for n, s in top_bc])\n\n# Step 3: Detect communities\ncomms = community.greedy_modularity_communities(G)\nprint(f\"Communities: {len(comms)}, modularity: {community.modularity(G, comms):.4f}\")\n\n# Step 4: Visualize with community coloring\npos = nx.spring_layout(G, seed=42)\nfig, ax = plt.subplots(figsize=(10, 8))\nfor i, comm in enumerate(comms):\n    nx.draw_networkx_nodes(G, pos, nodelist=list(comm), ax=ax,\n                           node_color=[plt.cm.Set2(i)]*len(comm), node_size=400)\nnx.draw_networkx_edges(G, pos, ax=ax, alpha=0.3)\nnx.draw_networkx_labels(G, pos, ax=ax, font_size=8)\nplt.axis(\"off\")\nplt.tight_layout()\nplt.savefig(\"social_network_analysis.png\", dpi=300, bbox_inches=\"tight\")\nprint(\"Saved social_network_analysis.png\")\n```\n\n### Workflow 2: Biological Interaction Network\n\n**Goal**: Build a PPI network from tabular data, analyze topology, and identify hub proteins.\n\n```python\nimport networkx as nx\nimport pandas as pd\n\n# Step 1: Load interaction data from DataFrame\ninteractions = pd.DataFrame({\n    \"protein_a\": [\"TP53\",\"TP53\",\"BRCA1\",\"BRCA1\",\"MDM2\",\"ATM\",\"ATM\",\"CHEK2\",\"RB1\",\"CDK2\"],\n    \"protein_b\": [\"MDM2\",\"BRCA1\",\"ATM\",\"CHEK2\",\"RB1\",\"CHEK2\",\"BRCA2\",\"CDC25A\",\"CDK2\",\"CCNA2\"],\n    \"score\": [0.99, 0.95, 0.92, 0.88, 0.91, 0.97, 0.85, 0.90, 0.87, 0.93]\n})\nG = nx.from_pandas_edgelist(interactions, \"protein_a\", \"protein_b\",\n                             edge_attr=\"score\")\nprint(f\"PPI network: {G.number_of_nodes()} proteins, {G.number_of_edges()} interactions\")\n\n# Step 2: Network statistics\nprint(f\"Connected: {nx.is_connected(G)}\")\nprint(f\"Diameter: {nx.diameter(G)}\")\nprint(f\"Avg path length: {nx.average_shortest_path_length(G):.2f}\")\nprint(f\"Transitivity: {nx.transitivity(G):.4f}\")\n\n# Step 3: Hub identification (multiple centrality measures)\ndegree_c = nx.degree_centrality(G)\nbetween_c = nx.betweenness_centrality(G)\nclose_c = nx.closeness_centrality(G)\n\nresults = pd.DataFrame({\n    \"protein\": list(G.nodes()),\n    \"degree_centrality\": [degree_c[n] for n in G.nodes()],\n    \"betweenness\": [between_c[n] for n in G.nodes()],\n    \"closeness\": [close_c[n] for n in G.nodes()],\n}).sort_values(\"betweenness\", ascending=False)\nprint(\"\\nHub proteins:\")\nprint(results.head(5).to_string(index=False))\n\n# Step 4: Export for downstream analysis\nnx.write_graphml(G, \"ppi_network.graphml\")\nresults.to_csv(\"protein_centrality.csv\", index=False)\nprint(\"Exported ppi_network.graphml and protein_centrality.csv\")\n```\n\n## Key Parameters\n\n| Parameter | Module | Default | Range \u002F Options | Effect |\n|-----------|--------|---------|-----------------|--------|\n| `weight` | Paths\u002FCentrality | `None` | Edge attribute name | Use weighted edges for path\u002Fcentrality calculations |\n| `alpha` | `pagerank` | `0.85` | `0.0`-`1.0` | Damping factor; lower = more uniform distribution |\n| `k` | `betweenness_centrality` | `None` | `int` | Sample k nodes for approximation on large graphs |\n| `max_iter` | `eigenvector_centrality` | `100` | `int` | Max iterations for convergence |\n| `seed` | Generators\u002FLayouts | `None` | `int` | Random seed for reproducibility |\n| `n` \u002F `p` \u002F `m` | ER\u002FBA generators | varies | `int`\u002F`float` | Node count, edge probability, edges per new node |\n| `k` \u002F `p` | Watts-Strogatz | varies | `int`\u002F`float` | Nearest neighbors, rewiring probability |\n| `nodetype` | `read_edgelist` | `str` | `int`, `float`, `str` | Type conversion for node identifiers |\n| `edge_attr` | `from_pandas_edgelist` | `None` | Column name(s) | Edge attribute columns to include from DataFrame |\n| `format` | `to_scipy_sparse_array` | `\"csc\"` | `\"csr\"`, `\"csc\"`, `\"coo\"` | Sparse matrix format |\n\n## Best Practices\n\n1. **Always set random seeds** for reproducible generators and layouts: `seed=42` in both `erdos_renyi_graph()` and `spring_layout()`.\n\n2. **Use approximate algorithms for large graphs**: `nx.betweenness_centrality(G, k=500)` samples k nodes instead of all pairs.\n\n3. **Prefer `from_pandas_edgelist`** over manual `add_edge` loops for bulk data loading -- handles attributes cleanly and is faster.\n\n4. **Copy subgraphs before modification**: `G.subgraph(nodes)` returns a read-only view; call `.copy()` for a mutable independent graph.\n\n5. **Use GraphML or GML for persistent storage** to preserve all node\u002Fedge attributes. Edge lists lose metadata unless explicitly handled.\n\n6. **Convert graph types explicitly**: `D.to_undirected()` (DiGraph -> Graph), `nx.Graph(M)` (MultiGraph -> Graph, collapses multi-edges).\n\n7. **Use sparse matrices for large adjacency exports**: `to_scipy_sparse_array()` is far more memory-efficient than `to_numpy_array()`.\n\n8. **Anti-pattern -- Don't use `nx.info()`**: Deprecated; use `G.number_of_nodes()`, `G.number_of_edges()`, `nx.density(G)` directly.\n\n9. **Anti-pattern -- Don't assume node ordering**: Algorithms may return results in different orders. Always index by node key, not position.\n\n## Common Recipes\n\n### Recipe: Minimum Spanning Tree\n\nExtract the minimum spanning tree and compare to the original graph.\n\n```python\nimport networkx as nx\n\n# Create weighted graph\nG = nx.erdos_renyi_graph(50, 0.15, seed=42)\nfor u, v in G.edges():\n    G[u][v][\"weight\"] = round(nx.utils.py_random_state(42).random(), 2)\n\nmst = nx.minimum_spanning_tree(G, weight=\"weight\")\nprint(f\"Original: {G.number_of_edges()} edges\")\nprint(f\"MST: {mst.number_of_edges()} edges\")\ntotal_weight = sum(d[\"weight\"] for _, _, d in mst.edges(data=True))\nprint(f\"MST total weight: {total_weight:.2f}\")\n```\n\n### Recipe: Graph Coloring and Cliques\n\nFind cliques and compute graph coloring.\n\n```python\nimport networkx as nx\n\nG = nx.karate_club_graph()\n\n# Find all maximal cliques\ncliques = list(nx.find_cliques(G))\nprint(f\"Maximal cliques: {len(cliques)}\")\nlargest_clique = max(cliques, key=len)\nprint(f\"Largest clique size: {len(largest_clique)}, nodes: {largest_clique}\")\n\n# Greedy graph coloring\ncoloring = nx.greedy_color(G, strategy=\"largest_first\")\nn_colors = max(coloring.values()) + 1\nprint(f\"Chromatic number (greedy upper bound): {n_colors}\")\n```\n\n### Recipe: DAG and Topological Sort\n\nBuild a directed acyclic graph and find execution order.\n\n```python\nimport networkx as nx\n\n# Task dependency DAG\nD = nx.DiGraph()\nD.add_edges_from([\n    (\"download_data\", \"preprocess\"),\n    (\"download_data\", \"validate\"),\n    (\"preprocess\", \"analyze\"),\n    (\"validate\", \"analyze\"),\n    (\"analyze\", \"visualize\"),\n    (\"analyze\", \"report\"),\n    (\"visualize\", \"report\"),\n])\n\nprint(f\"Is DAG: {nx.is_directed_acyclic_graph(D)}\")\norder = list(nx.topological_sort(D))\nprint(f\"Execution order: {order}\")\n\n# Find all paths from start to end\npaths = list(nx.all_simple_paths(D, \"download_data\", \"report\"))\nprint(f\"Paths to report: {len(paths)}\")\nfor p in paths:\n    print(f\"  {' -> '.join(p)}\")\n```\n\n## Troubleshooting\n\n| Problem | Cause | Solution |\n|---------|-------|----------|\n| `NetworkXError: Graph is not connected` | Algorithm requires connected graph | Extract largest component: `G.subgraph(max(nx.connected_components(G), key=len)).copy()` |\n| `PowerIterationFailedConvergence` | Eigenvector\u002FPageRank did not converge | Increase `max_iter` (e.g., 1000) or check for disconnected components |\n| Very slow centrality computation | O(n*m) complexity on large graphs | Use `k` parameter for sampling: `betweenness_centrality(G, k=500)` |\n| `nx.NetworkXNotImplemented` | Algorithm not available for graph type | Convert graph type: `G.to_undirected()` or `G.to_directed()` |\n| Memory error on large graphs | Dense adjacency matrix | Use `to_scipy_sparse_array()` instead of `to_numpy_array()` |\n| Node IDs read as strings from file | `read_edgelist` defaults to `str` | Pass `nodetype=int`: `nx.read_edgelist(f, nodetype=int)` |\n| Community detection returns frozen sets | Normal return type for communities | Convert: `[list(c) for c in communities]` |\n| Self-loops in generated graphs | Configuration model allows self-loops | Remove: `G.remove_edges_from(nx.selfloop_edges(G))` |\n| Visualization too cluttered | Too many nodes\u002Fedges | Filter to subgraph, adjust `alpha`, increase figure size, or use interactive tools (Plotly, PyVis) |\n\n## Bundled Resources\n\nMigrated from original entry (STUB: 436-line main file + 2,014 lines across 5 reference files, main\u002Ftotal = 17.8%).\n\n### references\u002Falgorithms_generators.md\n\nCovers: Detailed algorithm parameters for traversal (DFS\u002FBFS), cycles, cliques, graph coloring, isomorphism, matching\u002Fcovering, tree algorithms (MST variants). Full generator catalog: classic graphs, lattice\u002Fgrid, tree, bipartite, degree sequence, graph operations (union, compose, complement, products).\nRelocated inline: Core algorithms (centrality, paths, connectivity, community, flow) -> Core API Modules 3-5. Core generators (ER, BA, WS, SBM) -> Module 8.\nOmitted: A* heuristic customization, Bellman-Ford negative weights -- consult official docs.\n\n**Original file disposition**:\n- `algorithms.md` (383 lines): Top algorithms relocated to Core API Modules 3-5 + Recipes. Remaining (traversal, cliques, coloring, isomorphism, matching, cycles, trees) -> this reference.\n- `generators.md` (378 lines): Core generators relocated to Module 8. Full catalog (classic, lattice, tree, bipartite, degree sequence, operators) -> this reference.\n\n### references\u002Fio_visualization.md\n\nCovers: All I\u002FO formats (adjacency list, GEXF, Pajek, LEDA, Cytoscape JSON, DOT\u002FGraphviz, Matrix Market, CSV, database\u002FSQL, compressed gzip). Format selection guide. Advanced visualization: Plotly interactive, PyVis HTML, Graphviz layouts, 3D networks, bipartite layout, community coloring, subgraph highlighting, multi-panel figures, edge labels, directed arrows.\nRelocated inline: Core I\u002FO (edge list, GraphML, JSON, pandas, NumPy\u002FSciPy) -> Module 6. Basic matplotlib -> Module 7.\nOmitted: `write_gpickle`\u002F`read_gpickle` (deprecated), `read_shp`\u002F`write_shp` (removed in NetworkX 3.0; use geopandas).\n\n**Original file disposition**:\n- `io.md` (441 lines): Core formats relocated to Module 6. Remaining formats + format selection guide -> this reference.\n- `visualization.md` (529 lines): Basic matplotlib relocated to Module 7. Advanced techniques (Plotly, PyVis, 3D, bipartite, community coloring) -> this reference.\n\n### Fully consolidated original file\n\n- `graph-basics.md` (283 lines): Fully consolidated into main SKILL.md. Graph types -> Key Concepts. Node\u002Fedge operations, attributes, subgraphs -> Core API Modules 1-2. Diagnostics -> Common Workflows. Memory\u002Ffloat-point considerations -> Best Practices + Troubleshooting. Omitted: `nx.info()` (deprecated).\n\n## Related Skills\n\n- **torch-geometric-graph-neural-networks** -- graph neural networks (GCN, GAT, GraphSAGE) for node\u002Fgraph classification and link prediction on graph-structured data\n- **matplotlib-scientific-plotting** -- advanced figure customization beyond NetworkX's built-in `nx.draw`\n- **plotly-interactive-plots** -- interactive network plots with hover, zoom, and pan\n- **pandas** (planned) -- DataFrame operations for preparing edge\u002Fnode data before graph construction\n- **scipy** (planned) -- sparse matrix operations and numerical algorithms used by NetworkX internally\n\n## References\n\n- [NetworkX documentation](https:\u002F\u002Fnetworkx.org\u002Fdocumentation\u002Flatest\u002F) -- official docs and API reference\n- [NetworkX tutorial](https:\u002F\u002Fnetworkx.org\u002Fdocumentation\u002Flatest\u002Ftutorial.html) -- official getting started guide\n- [NetworkX GitHub](https:\u002F\u002Fgithub.com\u002Fnetworkx\u002Fnetworkx) -- source code and issue tracker\n- [NetworkX gallery](https:\u002F\u002Fnetworkx.org\u002Fdocumentation\u002Flatest\u002Fauto_examples\u002Findex.html) -- example gallery with visualizations\n- Hagberg, A., Schult, D., & Swart, P. (2008). Exploring network structure, dynamics, and function using NetworkX. SciPy 2008.\n",{"name":5,"license":15,"description":7},"master","63f17866001c5ca854bf2fa0b678ce277133de5b","skills\u002Fawesome-skills\u002Fnetworkx-graph-analysis",0,"https:\u002F\u002Fgithub.com\u002Fbg-szy\u002FTOP-SKILLS","https:\u002F\u002Fbg-szy.github.io\u002FTOP-SKILLS\u002F","https:\u002F\u002Fgithub.com\u002Fbg-szy","https:\u002F\u002Fwww.ecust.edu.cn\u002F","a student of East China University of Science and Technology","2026-11-15 03:38:02",{"source":8,"skillName":5,"commands":35,"prompt":45,"zipAvailable":46},[36,39,42],{"tool":37,"command":38},"npx","npx skills add bg-szy\u002FTOP-SKILLS --skill networkx-graph-analysis",{"tool":40,"command":41},"bunx","bunx skills add bg-szy\u002FTOP-SKILLS --skill networkx-graph-analysis",{"tool":43,"command":44},"pnpm","pnpm dlx skills add bg-szy\u002FTOP-SKILLS --skill networkx-graph-analysis","安装技能，技能地址：https:\u002F\u002Fgithub.com\u002Fbg-szy\u002FTOP-SKILLS\u002Fblob\u002Fmaster\u002Fskills\u002Fawesome-skills\u002Fnetworkx-graph-analysis\u002FSKILL.md",true,[],[49,58,65,72,79,86],{"skillNo":50,"name":51,"nameZh":6,"description":52,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":53,"licenseFileUrl":6,"sourceHtmlUrl":54,"categories":55,"keywords":56,"publishedAt":57},"01M7DXW9N826PKXK174PVW3038","serpmaven","Scrape Google search results (SERP) to JSON with SERP Maven (serpmaven) - a real Chrome browser on a residential proxy with sticky sessions. Run it as a CLI, a Python library, a local HTTP search API (`serve`), an MCP server or a Docker image; set the proxy login, workers, pages and cost tracking. Use when the user wants Google results, rank tracking, a self-hosted SERP API, or live Google search for an AI agent.","MIT","https:\u002F\u002Fgithub.com\u002Fbg-szy\u002FTOP-SKILLS\u002Fblob\u002Fmaster\u002Fskills\u002Fmarketplace\u002Fserpmaven\u002FSKILL.md",[],[],"2026-11-15 14:19:17",{"skillNo":59,"name":60,"nameZh":6,"description":61,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":53,"licenseFileUrl":6,"sourceHtmlUrl":62,"categories":63,"keywords":64,"publishedAt":57},"01M7DXVHSTWDV65475QEQ915M7","revnu-landing-page-audit","Find out why a landing page isn't turning visitors into signups, demos or sales. Audits one page against what the ad, post or search that sends people there promised, then checks the first screen, proof, call to action, friction and mobile. Returns at most 7 prioritized fixes, plus what is fine and what could not be checked; rewrites specific lines and fixes the page in the repo when asked. Never promises a conversion lift. Works without a Revnu account. Use when the user says or asks: \"audit my landing page\", \"why isn't this page converting\", \"review my homepage\", \"my ads get clicks but no signups\", \"people bounce from the pricing page\", \"CRO review\", \"improve conversion rate\", \"is my hero section clear\", \"roast my landing page\", \"rewrite my headline\", \"what's wrong with this page\", \"landing page feedback\", \"make the signup page convert better\". Not for SEO or AI-search audits, page speed engineering on its own, or building a new page from scratch.","https:\u002F\u002Fgithub.com\u002Fbg-szy\u002FTOP-SKILLS\u002Fblob\u002Fmaster\u002Fskills\u002Fmarketplace\u002Frevnu-landing-page-audit\u002FSKILL.md",[],[],{"skillNo":66,"name":67,"nameZh":6,"description":68,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":53,"licenseFileUrl":6,"sourceHtmlUrl":69,"categories":70,"keywords":71,"publishedAt":57},"01M7DXV8X2D7B3VTD4HHYYHTGR","revnu-growth-context","Write down once who buys, what they're stuck on, what it costs, what proof you have and what you've already tried, so every growth task starts from facts instead of a questionnaire. Creates or updates .agents\u002Frevnu-growth.md from the repo, the live site and the user, and imports an existing product-marketing.md. Use when the user says \"set up our marketing context\", \"who is our ideal customer\", \"write our ICP\", \"describe the product for marketing\", \"positioning doc\", \"what's our brand voice\", \"remember this about our customers\", \"log what we tried\", \"what have we learned from marketing\", \"we changed pricing, update the context\", \"update our growth notes\", \"summarize the business for the agent\", \"import my product-marketing.md\", \"start a growth doc\", or before a first marketing, SEO, outreach or launch task when no context file exists. Works without a Revnu account.","https:\u002F\u002Fgithub.com\u002Fbg-szy\u002FTOP-SKILLS\u002Fblob\u002Fmaster\u002Fskills\u002Fmarketplace\u002Frevnu-growth-context\u002FSKILL.md",[],[],{"skillNo":73,"name":74,"nameZh":6,"description":75,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":53,"licenseFileUrl":6,"sourceHtmlUrl":76,"categories":77,"keywords":78,"publishedAt":57},"01M7DXV0DGJ1G0A60PAHC6J3C5","revnu-get-listed","Get onto the third-party pages AI answers and search cite when buyers ask for the best tool in your category: \"best X\" roundups, directories, review sites, GitHub awesome lists, community threads and comparison pages. Finds which ones are cited, ranks them by fit and effort, and drafts each submission, PR or pitch by the target's own rules. Use when the user says \"get us listed\", \"which directories should we submit to\", \"how do we get into best-of lists\", \"why does ChatGPT recommend competitors and not us\", \"get mentioned in AI answers\", \"submit to awesome lists\", \"get on G2\", \"where are our competitors listed\", \"pitch listicle authors\", \"find backlink opportunities\", \"launch directories\", \"get into roundups\", \"Product Hunt alternatives\", \"where should we be listed\", \"get cited by Perplexity\". Never submits, pays or posts without a yes. Works without a Revnu account.","https:\u002F\u002Fgithub.com\u002Fbg-szy\u002FTOP-SKILLS\u002Fblob\u002Fmaster\u002Fskills\u002Fmarketplace\u002Frevnu-get-listed\u002FSKILL.md",[],[],{"skillNo":80,"name":81,"nameZh":6,"description":82,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":53,"licenseFileUrl":6,"sourceHtmlUrl":83,"categories":84,"keywords":85,"publishedAt":57},"01M7DXTSPMGT9D6DSS0HP9BSTA","revnu-ai-readiness-audit","Audit whether your website gives ChatGPT, Perplexity, Claude, Gemini and Google's AI Overviews something worth quoting, and fix the pages that don't. Use when the user says or asks \"is my site ready for AI search\", \"audit my site for AI answers\", \"AEO audit\", \"GEO audit\", \"why doesn't ChatGPT quote our pricing\", \"make our pages citable by AI\", \"do I need llms.txt\", \"does schema help with ChatGPT\", \"check our structured data\", \"is our content visible without JavaScript\", \"AI SEO audit\", \"optimize our homepage for AI answers\", \"LLM SEO check\", \"why does AI get our product wrong\", \"fix our site for AI Overviews\". Checks fetchability and indexability, answers in the raw HTML, entity facts, schema (including JS-injected markup), headings, dates and llms.txt, then gives at most 10 prioritised fixes and edits the repo when asked. Works without a Revnu account.","https:\u002F\u002Fgithub.com\u002Fbg-szy\u002FTOP-SKILLS\u002Fblob\u002Fmaster\u002Fskills\u002Fmarketplace\u002Frevnu-ai-readiness-audit\u002FSKILL.md",[],[],{"skillNo":87,"name":88,"nameZh":6,"description":89,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":53,"licenseFileUrl":6,"sourceHtmlUrl":90,"categories":91,"keywords":92,"publishedAt":57},"01M7DXSZHCVTRS620GC3S97JZV","proxy-troubleshooting","Diagnose residential proxy failures, with NodeMaven's gateway as the reference - 407 with correct credentials, 406, 410, 500, a connection that hangs, ERR_TUNNEL_CONNECTION_FAILED in a browser, Playwright or Puppeteer ignoring proxy credentials, a sticky session that changes IP, geo-targeting that is silently ignored, passwords with special characters, and unexpected traffic from headless Chrome. Use when a proxy connection fails, returns the wrong location, or costs more traffic than expected.","https:\u002F\u002Fgithub.com\u002Fbg-szy\u002FTOP-SKILLS\u002Fblob\u002Fmaster\u002Fskills\u002Fmarketplace\u002Fproxy-troubleshooting\u002FSKILL.md",[],[]]