Skill Tracer
Skills › Scientific Agent Skills › networkx

networkx

skill · 476 lines · 3-clause BSD license · skills/networkx/SKILL.md

The facts

Its description

Creates, analyzes, and visualizes complex networks and graphs in Python with NetworkX. Use when working with network/graph data structures, computing graph algorithms (shortest paths, centrality, clustering), detecting communities, generating synthetic networks (random, scale-free, small-world), reading/writing graph file formats, or drawing network topologies. Common applications include social, biological, transportation, and citation networks.

The description the agent reads to decide when to use it.

From its settingsline 3

Files it mentions

references/review.md, references/graph-basics.md, references/algorithms.md, references/generators.md, references/io.md (first 5 of 6 lines)

Files the text names, such as ones to read or write. Found by matching words, so treat them as pointers.

Found by matching wordsline 21 line 63 line 114 line 154 line 207

Licence

3-clause BSD license, from the skill file

The terms its author shares it under, which let it be shown here.

From its settingsline 4 licence text

Other settings

compatibility: Requires Python >=3.12 (excluding 3.14.1) and NetworkX 3.7. NumPy, SciPy, pandas and Matplotlib support numerical, tabular and drawing examples; optional integrations need their own packages. No credentials; network needed only for installation or remote data. metadata: version: "1.4" last-reviewed: "2026-10-01" upstream-version: "3.7" skill-author: K-Dense Inc.

More settings at the top of the file, shown as written.

From its settingsline 5 line 6
Other files in this skill (6) Close

The text

Open on GitHub

Most marks come from matching words in the file, so treat them as pointers.

1---
2name: networkx
3description: Creates, analyzes, and visualizes complex networks and graphs in Python with NetworkX. Use when working with network/graph data structures, computing graph algorithms (shortest paths, centrality, clustering), detecting communities, generating synthetic networks (random, scale-free, small-world), reading/writing graph file formats, or drawing network topologies. Common applications include social, biological, transportation, and citation networks.
4license: 3-clause BSD license
5compatibility: Requires Python >=3.12 (excluding 3.14.1) and NetworkX 3.7. NumPy, SciPy, pandas and Matplotlib support numerical, tabular and drawing examples; optional integrations need their own packages. No credentials; network needed only for installation or remote data.
6metadata:
7 version: "1.4"
8 last-reviewed: "2026-10-01"
9 upstream-version: "3.7"
10 skill-author: K-Dense Inc.
11---
13# NetworkX
15## Overview
17NetworkX is a Python package for creating, manipulating, and analyzing complex networks and graphs. Use this skill when working with network or graph data structures, including social networks, biological networks, transportation systems, citation networks, knowledge graphs, or any system involving relationships between entities.
19This skill targets tested NetworkX 3.7 (Python >=3.12, excluding 3.14.1). Several pre-3.0 APIs (`nx.info`, `nx.write_gpickle`, `nx.read_shp`) and the 3.4-era `nx.random_tree` no longer exist — current replacements are used throughout this skill.
21Review sources, executed examples, optional-dependency limits, and reproducibility notes are in [references/review.md](references/review.md). Reference snippets are API patterns: supply the stated graph type and input files; they are not one sequential script.

Overview

NetworkX is a Python package for creating, manipulating, and analyzing complex networks and graphs. Use this skill when working with network or graph data structures, including social networks, biological networks, transportation systems, citation networks, knowledge graphs, or any system involving relationships between entities.

This skill targets tested NetworkX 3.7 (Python >=3.12, excluding 3.14.1). Several pre-3.0 APIs (nx.info, nx.write_gpickle, nx.read_shp) and the 3.4-era nx.random_tree no longer exist — current replacements are used throughout this skill.

Review sources, executed examples, optional-dependency limits, and reproducibility notes are in references/review.md. Reference snippets are API patterns: supply the stated graph type and input files; they are not one sequential script.

Raw lines 15 to 22
Reads a file references/review.md :21
23## When to Use This Skill
25Invoke this skill when tasks involve:
27- **Creating graphs**: Building network structures from data, adding nodes and edges with attributes
28- **Graph analysis**: Computing centrality measures, finding shortest paths, detecting communities, measuring clustering
29- **Graph algorithms**: Running standard algorithms like Dijkstra's, PageRank, minimum spanning trees, maximum flow
30- **Network generation**: Creating synthetic networks (random, scale-free, small-world models) for testing or simulation
31- **Graph I/O**: Reading from or writing to various formats (edge lists, GraphML, JSON, CSV, adjacency matrices)
32- **Visualization**: Drawing and customizing network visualizations with matplotlib or interactive libraries
33- **Network comparison**: Checking isomorphism, computing graph metrics, analyzing structural properties

When to Use This Skill

Invoke this skill when tasks involve:

  • Creating graphs: Building network structures from data, adding nodes and edges with attributes
  • Graph analysis: Computing centrality measures, finding shortest paths, detecting communities, measuring clustering
  • Graph algorithms: Running standard algorithms like Dijkstra's, PageRank, minimum spanning trees, maximum flow
  • Network generation: Creating synthetic networks (random, scale-free, small-world models) for testing or simulation
  • Graph I/O: Reading from or writing to various formats (edge lists, GraphML, JSON, CSV, adjacency matrices)
  • Visualization: Drawing and customizing network visualizations with matplotlib or interactive libraries
  • Network comparison: Checking isomorphism, computing graph metrics, analyzing structural properties
Raw lines 23 to 34
35## Core Capabilities

Core Capabilities

Raw lines 35 to 36
37### 1. Graph Creation and Manipulation
39NetworkX supports four main graph types:
40- **Graph**: Undirected graphs with single edges
41- **DiGraph**: Directed graphs with one-way connections
42- **MultiGraph**: Undirected graphs allowing multiple edges between nodes
43- **MultiDiGraph**: Directed graphs with multiple edges
45Create graphs by:
46```python
47import networkx as nx
49# Create empty graph
50G = nx.Graph()
52# Add nodes (can be any hashable type)
53G.add_node(1)
54G.add_nodes_from([2, 3, 4])
55G.add_node("protein_A", type='enzyme', weight=1.5)
57# Add edges
58G.add_edge(1, 2)
59G.add_edges_from([(1, 3), (2, 4)])
60G.add_edge(1, 4, weight=0.8, relation='interacts')
61```
63**Reference**: See `references/graph-basics.md` for comprehensive guidance on creating, modifying, examining, and managing graph structures, including working with attributes and subgraphs.

1. Graph Creation and Manipulation

NetworkX supports four main graph types:

  • Graph: Undirected graphs with single edges
  • DiGraph: Directed graphs with one-way connections
  • MultiGraph: Undirected graphs allowing multiple edges between nodes
  • MultiDiGraph: Directed graphs with multiple edges

Create graphs by:

import networkx as nx

# Create empty graph
G = nx.Graph()

# Add nodes (can be any hashable type)
G.add_node(1)
G.add_nodes_from([2, 3, 4])
G.add_node("protein_A", type='enzyme', weight=1.5)

# Add edges
G.add_edge(1, 2)
G.add_edges_from([(1, 3), (2, 4)])
G.add_edge(1, 4, weight=0.8, relation='interacts')

Reference: See references/graph-basics.md for comprehensive guidance on creating, modifying, examining, and managing graph structures, including working with attributes and subgraphs.

Raw lines 37 to 64
65### 2. Graph Algorithms
67NetworkX provides extensive algorithms for network analysis:
69**Shortest Paths**:
71For weighted paths and betweenness, weights represent distances/costs: larger values
72make a route less favorable. Similarity, correlation, or interaction strength needs an
73explicit scientifically justified conversion before use as distance. Validate the chosen
74attribute on every edge and use strictly positive distances for weighted betweenness.
76```python
77# Same distance model for route and length
78G = nx.Graph()
79G.add_weighted_edges_from([(1, 2, 1), (2, 5, 1), (1, 5, 5)], weight='distance')
80path = nx.shortest_path(G, source=1, target=5, weight='distance')
81length = nx.shortest_path_length(G, source=1, target=5, weight='distance')
82assert path == [1, 2, 5] and length == 2
83```
85**Centrality Measures**:
86```python
87# Degree centrality
88degree_cent = nx.degree_centrality(G)
90# Betweenness centrality
91betweenness = nx.betweenness_centrality(G)
93# PageRank
94pagerank = nx.pagerank(G)
95```
97**Community Detection**:
98```python
99from networkx.algorithms import community
101# Specify weight=None for unweighted topology
102communities = community.greedy_modularity_communities(G, weight=None)
103```
105**Connectivity**:
106```python
107# Check connectivity
108is_connected = nx.is_connected(G)
110# Find connected components
111components = list(nx.connected_components(G))
112```
114**Reference**: See `references/algorithms.md` for worked API patterns for common algorithms including shortest paths, centrality measures, clustering, community detection, flows, matching, tree algorithms, and graph traversal.

2. Graph Algorithms

NetworkX provides extensive algorithms for network analysis:

Shortest Paths:

For weighted paths and betweenness, weights represent distances/costs: larger values make a route less favorable. Similarity, correlation, or interaction strength needs an explicit scientifically justified conversion before use as distance. Validate the chosen attribute on every edge and use strictly positive distances for weighted betweenness.

# Same distance model for route and length
G = nx.Graph()
G.add_weighted_edges_from([(1, 2, 1), (2, 5, 1), (1, 5, 5)], weight='distance')
path = nx.shortest_path(G, source=1, target=5, weight='distance')
length = nx.shortest_path_length(G, source=1, target=5, weight='distance')
assert path == [1, 2, 5] and length == 2

Centrality Measures:

# Degree centrality
degree_cent = nx.degree_centrality(G)

# Betweenness centrality
betweenness = nx.betweenness_centrality(G)

# PageRank
pagerank = nx.pagerank(G)

Community Detection:

from networkx.algorithms import community

# Specify weight=None for unweighted topology
communities = community.greedy_modularity_communities(G, weight=None)

Connectivity:

# Check connectivity
is_connected = nx.is_connected(G)

# Find connected components
components = list(nx.connected_components(G))

Reference: See references/algorithms.md for worked API patterns for common algorithms including shortest paths, centrality measures, clustering, community detection, flows, matching, tree algorithms, and graph traversal.

Raw lines 65 to 115
Reads a file references/algorithms.md :114
116### 3. Graph Generators
118Create synthetic networks for testing, simulation, or modeling:
120**Classic Graphs**:
121```python
122# Complete graph
123G = nx.complete_graph(n=10)
125# Cycle graph
126G = nx.cycle_graph(n=20)
128# Known graphs
129G = nx.karate_club_graph()
130G = nx.petersen_graph()
131```
133**Random Networks**:
134```python
135# Erdős-Rényi random graph
136G = nx.erdos_renyi_graph(n=100, p=0.1, seed=42)
138# Barabási-Albert scale-free network
139G = nx.barabasi_albert_graph(n=100, m=3, seed=42)
141# Watts-Strogatz small-world network
142G = nx.watts_strogatz_graph(n=100, k=6, p=0.1, seed=42)
143```
145**Structured Networks**:
146```python
147# Grid graph
148G = nx.grid_2d_graph(m=5, n=7)
150# Random tree (random_tree was removed in NetworkX 3.4)
151G = nx.random_labeled_tree(100, seed=42)
152```
154**Reference**: See `references/generators.md` for representative graph generators including classic, random, lattice, bipartite, and specialized network models with detailed parameters and use cases.

3. Graph Generators

Create synthetic networks for testing, simulation, or modeling:

Classic Graphs:

# Complete graph
G = nx.complete_graph(n=10)

# Cycle graph
G = nx.cycle_graph(n=20)

# Known graphs
G = nx.karate_club_graph()
G = nx.petersen_graph()

Random Networks:

# Erdős-Rényi random graph
G = nx.erdos_renyi_graph(n=100, p=0.1, seed=42)

# Barabási-Albert scale-free network
G = nx.barabasi_albert_graph(n=100, m=3, seed=42)

# Watts-Strogatz small-world network
G = nx.watts_strogatz_graph(n=100, k=6, p=0.1, seed=42)

Structured Networks:

# Grid graph
G = nx.grid_2d_graph(m=5, n=7)

# Random tree (random_tree was removed in NetworkX 3.4)
G = nx.random_labeled_tree(100, seed=42)

Reference: See references/generators.md for representative graph generators including classic, random, lattice, bipartite, and specialized network models with detailed parameters and use cases.

Raw lines 116 to 155
Reads a file references/generators.md :154
156### 4. Reading and Writing Graphs
158NetworkX supports numerous file formats and data sources:
160**File Formats**:
161```python
162# Edge list
163G = nx.read_edgelist('graph.edgelist')
164nx.write_edgelist(G, 'graph.edgelist')
166# GraphML (supported scalar attributes; node IDs read as strings by default)
167G = nx.read_graphml('graph.graphml')
168nx.write_graphml(G, 'graph.graphml')
170# GML
171G = nx.read_gml('graph.gml')
172nx.write_gml(G, 'graph.gml')
174# JSON (node-link format; edge list is stored under the "edges" key
175# since NetworkX 3.6 — older files may use "links", see references/io.md)
176data = nx.node_link_data(G, edges="edges")
177G = nx.node_link_graph(data, edges="edges")
178```
180**Pandas Integration**:
181```python
182import pandas as pd
184# From DataFrame
185df = pd.DataFrame({'source': [1, 2, 3], 'target': [2, 3, 4], 'weight': [0.5, 1.0, 0.75]})
186G = nx.from_pandas_edgelist(df, 'source', 'target', edge_attr='weight')
188# To DataFrame
189df = nx.to_pandas_edgelist(G)
190```
192**Matrix Formats**:
193```python
194import numpy as np
196# Simple-graph adjacency: preserve node ordering, direction and zero weights
197nodes = list(G)
198A = nx.to_numpy_array(G, nodelist=nodes, nonedge=np.nan)
199H = nx.from_numpy_array(A, nodelist=nodes, create_using=type(G), nonedge=np.nan)
201# Sparse adjacency sums parallel-edge weights; save labels separately
202A = nx.to_scipy_sparse_array(G, nodelist=nodes)
203H = nx.from_scipy_sparse_array(A, create_using=type(G))
204H = nx.relabel_nodes(H, dict(enumerate(nodes)))
205```
207**Reference**: See `references/io.md` for complete documentation on all I/O formats including CSV, SQL databases, Cytoscape, DOT, and guidance on format selection for different use cases.

4. Reading and Writing Graphs

NetworkX supports numerous file formats and data sources:

File Formats:

# Edge list
G = nx.read_edgelist('graph.edgelist')
nx.write_edgelist(G, 'graph.edgelist')

# GraphML (supported scalar attributes; node IDs read as strings by default)
G = nx.read_graphml('graph.graphml')
nx.write_graphml(G, 'graph.graphml')

# GML
G = nx.read_gml('graph.gml')
nx.write_gml(G, 'graph.gml')

# JSON (node-link format; edge list is stored under the "edges" key
# since NetworkX 3.6 — older files may use "links", see references/io.md)
data = nx.node_link_data(G, edges="edges")
G = nx.node_link_graph(data, edges="edges")

Pandas Integration:

import pandas as pd

# From DataFrame
df = pd.DataFrame({'source': [1, 2, 3], 'target': [2, 3, 4], 'weight': [0.5, 1.0, 0.75]})
G = nx.from_pandas_edgelist(df, 'source', 'target', edge_attr='weight')

# To DataFrame
df = nx.to_pandas_edgelist(G)

Matrix Formats:

import numpy as np

# Simple-graph adjacency: preserve node ordering, direction and zero weights
nodes = list(G)
A = nx.to_numpy_array(G, nodelist=nodes, nonedge=np.nan)
H = nx.from_numpy_array(A, nodelist=nodes, create_using=type(G), nonedge=np.nan)

# Sparse adjacency sums parallel-edge weights; save labels separately
A = nx.to_scipy_sparse_array(G, nodelist=nodes)
H = nx.from_scipy_sparse_array(A, create_using=type(G))
H = nx.relabel_nodes(H, dict(enumerate(nodes)))

Reference: See references/io.md for complete documentation on all I/O formats including CSV, SQL databases, Cytoscape, DOT, and guidance on format selection for different use cases.

Raw lines 156 to 208
Reads a file references/io.md :207
209### 5. Visualization
211Create clear and informative network visualizations:
213**Basic Visualization**:
214```python
215import matplotlib.pyplot as plt
217# Simple draw
218nx.draw(G, with_labels=True)
219plt.show()
221# With layout
222pos = nx.spring_layout(G, seed=42)
223nx.draw(G, pos=pos, with_labels=True, node_color='lightblue', node_size=500)
224plt.show()
225```
227**Customization**:
228```python
229# Color by degree
230node_colors = [G.degree(n) for n in G.nodes()]
231nx.draw(G, node_color=node_colors, cmap=plt.cm.viridis)
233# Size by centrality
234centrality = nx.betweenness_centrality(G)
235node_sizes = [3000 * centrality[n] for n in G.nodes()]
236nx.draw(G, node_size=node_sizes)
238# Edge weights
239edge_widths = [3 * G[u][v].get('weight', 1) for u, v in G.edges()]
240nx.draw(G, width=edge_widths)
241```
243**Layout Algorithms**:
244```python
245# Spring layout (force-directed)
246pos = nx.spring_layout(G, seed=42)
248# Circular layout
249pos = nx.circular_layout(G)
251# Kamada-Kawai layout
252pos = nx.kamada_kawai_layout(G)
254# Spectral layout
255pos = nx.spectral_layout(G)
256```
258**Publication Quality**:
259```python
260fig, ax = plt.subplots(figsize=(12, 8))
261pos = nx.spring_layout(G, seed=42)
262nx.draw(G, pos=pos, ax=ax, node_color='lightblue', node_size=500,
263 edge_color='gray', with_labels=True, font_size=10)
264plt.title('Network Visualization', fontsize=16)
265plt.axis('off')
266plt.tight_layout()
267plt.savefig('network.png', dpi=300, bbox_inches='tight')
268plt.savefig('network.pdf', bbox_inches='tight') # Vector format
269```
271**Reference**: See `references/visualization.md` for extensive documentation on visualization techniques including layout algorithms, customization options, interactive visualizations with Plotly and PyVis, 3D networks, and publication-quality figure creation.

5. Visualization

Create clear and informative network visualizations:

Basic Visualization:

import matplotlib.pyplot as plt

# Simple draw
nx.draw(G, with_labels=True)
plt.show()

# With layout
pos = nx.spring_layout(G, seed=42)
nx.draw(G, pos=pos, with_labels=True, node_color='lightblue', node_size=500)
plt.show()

Customization:

# Color by degree
node_colors = [G.degree(n) for n in G.nodes()]
nx.draw(G, node_color=node_colors, cmap=plt.cm.viridis)

# Size by centrality
centrality = nx.betweenness_centrality(G)
node_sizes = [3000 * centrality[n] for n in G.nodes()]
nx.draw(G, node_size=node_sizes)

# Edge weights
edge_widths = [3 * G[u][v].get('weight', 1) for u, v in G.edges()]
nx.draw(G, width=edge_widths)

Layout Algorithms:

# Spring layout (force-directed)
pos = nx.spring_layout(G, seed=42)

# Circular layout
pos = nx.circular_layout(G)

# Kamada-Kawai layout
pos = nx.kamada_kawai_layout(G)

# Spectral layout
pos = nx.spectral_layout(G)

Publication Quality:

fig, ax = plt.subplots(figsize=(12, 8))
pos = nx.spring_layout(G, seed=42)
nx.draw(G, pos=pos, ax=ax, node_color='lightblue', node_size=500,
        edge_color='gray', with_labels=True, font_size=10)
plt.title('Network Visualization', fontsize=16)
plt.axis('off')
plt.tight_layout()
plt.savefig('network.png', dpi=300, bbox_inches='tight')
plt.savefig('network.pdf', bbox_inches='tight')  # Vector format

Reference: See references/visualization.md for extensive documentation on visualization techniques including layout algorithms, customization options, interactive visualizations with Plotly and PyVis, 3D networks, and publication-quality figure creation.

Raw lines 209 to 272
Reads a file references/visualization.md :271
273## Working with NetworkX

Working with NetworkX

Raw lines 273 to 274
275### Installation
277Ensure NetworkX is installed:
278```python
279# Check if installed
280import networkx as nx
281print(nx.__version__)
283# Install if needed (via bash)
284# uv pip install "networkx==3.7"
285# uv pip install "networkx[default]==3.7" # With optional dependencies
286```

Installation

Ensure NetworkX is installed:

# Check if installed
import networkx as nx
print(nx.__version__)

# Install if needed (via bash)
# uv pip install "networkx==3.7"
# uv pip install "networkx[default]==3.7"  # With optional dependencies
Raw lines 275 to 287
288### Common Workflow Pattern
290Most NetworkX tasks follow this pattern:
2921. **Create or Load Graph**: choose direction, parallel-edge and self-loop rules before importing. Keep an explicit node table so isolates survive edge-list imports.
293 ```python
294 # From scratch
295 G = nx.Graph()
296 G.add_edges_from([(1, 2), (2, 3), (3, 4)])
298 # Or load from file/data
299 G = nx.read_edgelist('data.txt')
300 ```
3022. **Examine Structure**:
303 ```python
304 print(f"Nodes: {G.number_of_nodes()}")
305 print(f"Edges: {G.number_of_edges()}")
306 print(f"Density: {nx.density(G)}")
307 print(f"Connected: {nx.is_connected(G)}")
308 ```
3103. **Analyze**:
311 ```python
312 # Compute metrics
313 degree_cent = nx.degree_centrality(G)
314 avg_clustering = nx.average_clustering(G)
316 # Find paths
317 path = nx.shortest_path(G, source=1, target=4)
319 # Detect communities
320 communities = community.greedy_modularity_communities(G)
321 ```
3234. **Visualize**:
324 ```python
325 pos = nx.spring_layout(G, seed=42)
326 nx.draw(G, pos=pos, with_labels=True)
327 plt.show()
328 ```
3305. **Export Results**:
331 ```python
332 # Save graph
333 nx.write_graphml(G, 'analyzed_network.graphml')
335 # Save metrics
336 df = pd.DataFrame({
337 'node': list(degree_cent.keys()),
338 'centrality': list(degree_cent.values())
339 })
340 df.to_csv('centrality_results.csv', index=False)
341 ```

Common Workflow Pattern

Most NetworkX tasks follow this pattern:

  1. Create or Load Graph: choose direction, parallel-edge and self-loop rules before importing. Keep an explicit node table so isolates survive edge-list imports. ```python # From scratch G = nx.Graph() G.add_edges_from([(1, 2), (2, 3), (3, 4)])

# Or load from file/data G = nx.read_edgelist('data.txt') ```

  1. Examine Structure: ``python print(f"Nodes: {G.number_of_nodes()}") print(f"Edges: {G.number_of_edges()}") print(f"Density: {nx.density(G)}") print(f"Connected: {nx.is_connected(G)}")
  1. Analyze: ```python # Compute metrics degree_cent = nx.degree_centrality(G) avg_clustering = nx.average_clustering(G)

# Find paths path = nx.shortest_path(G, source=1, target=4)

# Detect communities communities = community.greedy_modularity_communities(G) ```

  1. Visualize: ``python pos = nx.spring_layout(G, seed=42) nx.draw(G, pos=pos, with_labels=True) plt.show()
  1. Export Results: ```python # Save graph nx.write_graphml(G, 'analyzed_network.graphml')

# Save metrics df = pd.DataFrame({ 'node': list(degree_cent.keys()), 'centrality': list(degree_cent.values()) }) df.to_csv('centrality_results.csv', index=False) ```

Raw lines 288 to 342
343### Important Considerations
345**Analysis contract**: specify node/edge meaning, sampling and missingness, weight units, and whether parallel observations should be retained or aggregated. All four graph classes allow self-loops. Repeated `Graph.add_edge` updates an existing edge; it does not sum observations. `nx.is_connected` is for nonempty undirected graphs; directed graphs require strong/weak connectivity. Report component sizes before choosing a subset.
347**Scientific interpretation**: centrality is conditional on the observed graph and weight model. Community partitions optimize a chosen objective; they are not significance tests. Test seed/resolution sensitivity and use a domain-justified null ensemble. Converting a configuration multigraph to a simple graph changes its degree sequence. A generated preferential-attachment graph does not demonstrate that empirical data follow a power law.
349**Floating Point Precision**: When graphs contain floating-point numbers, all results are inherently approximate due to precision limitations. This can affect algorithm outcomes, particularly in minimum/maximum computations.
351**Memory and Performance**: Each time a script runs, graph data must be loaded into memory. For large networks:
352- Use appropriate data structures (sparse matrices for large sparse graphs)
353- Consider loading only necessary subgraphs
354- Use efficient file formats (pickle for Python objects, compressed formats)
355- Leverage approximate algorithms for very large networks (e.g., `k` parameter in centrality calculations)
356- For heavy workloads, dispatchable functions accept `backend=` or configured `nx.config.backend_priority`. Check the backend's function, graph-type and parameter coverage; conversion costs, supported weights, seeds and numerical results can differ. Accelerated backends were not runtime-tested here.
358**Node and Edge Types**:
359- Nodes can be any hashable Python object except `None` (numbers, strings, tuples, custom objects)
360- Use meaningful identifiers for clarity
361- When removing nodes, all incident edges are automatically removed
363**Random Seeds**: Always set random seeds for reproducibility in random graph generation and force-directed layouts:
364```python
365G = nx.erdos_renyi_graph(n=100, p=0.1, seed=42)
366pos = nx.spring_layout(G, seed=42)
367```

Important Considerations

Analysis contract: specify node/edge meaning, sampling and missingness, weight units, and whether parallel observations should be retained or aggregated. All four graph classes allow self-loops. Repeated Graph.add_edge updates an existing edge; it does not sum observations. nx.is_connected is for nonempty undirected graphs; directed graphs require strong/weak connectivity. Report component sizes before choosing a subset.

Scientific interpretation: centrality is conditional on the observed graph and weight model. Community partitions optimize a chosen objective; they are not significance tests. Test seed/resolution sensitivity and use a domain-justified null ensemble. Converting a configuration multigraph to a simple graph changes its degree sequence. A generated preferential-attachment graph does not demonstrate that empirical data follow a power law.

Floating Point Precision: When graphs contain floating-point numbers, all results are inherently approximate due to precision limitations. This can affect algorithm outcomes, particularly in minimum/maximum computations.

Memory and Performance: Each time a script runs, graph data must be loaded into memory. For large networks:

  • Use appropriate data structures (sparse matrices for large sparse graphs)
  • Consider loading only necessary subgraphs
  • Use efficient file formats (pickle for Python objects, compressed formats)
  • Leverage approximate algorithms for very large networks (e.g., k parameter in centrality calculations)
  • For heavy workloads, dispatchable functions accept backend= or configured nx.config.backend_priority. Check the backend's function, graph-type and parameter coverage; conversion costs, supported weights, seeds and numerical results can differ. Accelerated backends were not runtime-tested here.

Node and Edge Types:

  • Nodes can be any hashable Python object except None (numbers, strings, tuples, custom objects)
  • Use meaningful identifiers for clarity
  • When removing nodes, all incident edges are automatically removed

Random Seeds: Always set random seeds for reproducibility in random graph generation and force-directed layouts:

G = nx.erdos_renyi_graph(n=100, p=0.1, seed=42)
pos = nx.spring_layout(G, seed=42)
Raw lines 343 to 368
369## Quick Reference

Quick Reference

Raw lines 369 to 370
371### Basic Operations
372```python
373# Create
374G = nx.Graph()
375G.add_edge(1, 2)
377# Query
378G.number_of_nodes()
379G.number_of_edges()
380G.degree(1)
381list(G.neighbors(1))
383# Check
384G.has_node(1)
385G.has_edge(1, 2)
386nx.is_connected(G)
388# Modify: remove the edge before deleting its endpoint
389G.remove_edge(1, 2)
390G.remove_node(1)
391G.clear()
392```

Basic Operations

# Create
G = nx.Graph()
G.add_edge(1, 2)

# Query
G.number_of_nodes()
G.number_of_edges()
G.degree(1)
list(G.neighbors(1))

# Check
G.has_node(1)
G.has_edge(1, 2)
nx.is_connected(G)

# Modify: remove the edge before deleting its endpoint
G.remove_edge(1, 2)
G.remove_node(1)
G.clear()
Raw lines 371 to 393
394### Essential Algorithms
395```python
396# Paths
397nx.shortest_path(G, source, target)
398nx.all_pairs_shortest_path(G)
400# Centrality
401nx.degree_centrality(G)
402nx.betweenness_centrality(G)
403nx.closeness_centrality(G)
404nx.pagerank(G)
406# Clustering
407nx.clustering(G)
408nx.average_clustering(G)
410# Components
411nx.connected_components(G)
412nx.strongly_connected_components(G) # Directed
414# Community
415community.greedy_modularity_communities(G)
416```

Essential Algorithms

# Paths
nx.shortest_path(G, source, target)
nx.all_pairs_shortest_path(G)

# Centrality
nx.degree_centrality(G)
nx.betweenness_centrality(G)
nx.closeness_centrality(G)
nx.pagerank(G)

# Clustering
nx.clustering(G)
nx.average_clustering(G)

# Components
nx.connected_components(G)
nx.strongly_connected_components(G)  # Directed

# Community
community.greedy_modularity_communities(G)
Raw lines 394 to 417
418### File I/O Quick Reference
419```python
420# Read
421nx.read_edgelist('file.txt')
422nx.read_graphml('file.graphml')
423nx.read_gml('file.gml')
425# Write
426nx.write_edgelist(G, 'file.txt')
427nx.write_graphml(G, 'file.graphml')
428nx.write_gml(G, 'file.gml')
430# Pandas
431nx.from_pandas_edgelist(df, 'source', 'target')
432nx.to_pandas_edgelist(G)
433```

File I/O Quick Reference

# Read
nx.read_edgelist('file.txt')
nx.read_graphml('file.graphml')
nx.read_gml('file.gml')

# Write
nx.write_edgelist(G, 'file.txt')
nx.write_graphml(G, 'file.graphml')
nx.write_gml(G, 'file.gml')

# Pandas
nx.from_pandas_edgelist(df, 'source', 'target')
nx.to_pandas_edgelist(G)
Raw lines 418 to 434
435## Resources
437This skill includes comprehensive reference documentation:

Resources

This skill includes comprehensive reference documentation:

Raw lines 435 to 438
439### references/graph-basics.md
440Detailed guide on graph types, creating and modifying graphs, adding nodes and edges, managing attributes, examining structure, and working with subgraphs.

references/graph-basics.md

Detailed guide on graph types, creating and modifying graphs, adding nodes and edges, managing attributes, examining structure, and working with subgraphs.

Raw lines 439 to 441
442### references/algorithms.md
443Complete coverage of NetworkX algorithms including shortest paths, centrality measures, connectivity, clustering, community detection, flow algorithms, tree algorithms, matching, coloring, isomorphism, and graph traversal.

references/algorithms.md

Complete coverage of NetworkX algorithms including shortest paths, centrality measures, connectivity, clustering, community detection, flow algorithms, tree algorithms, matching, coloring, isomorphism, and graph traversal.

Raw lines 442 to 444
445### references/generators.md
446Comprehensive documentation on graph generators including classic graphs, random models (Erdős-Rényi, Barabási-Albert, Watts-Strogatz), lattices, trees, social network models, and specialized generators.

references/generators.md

Comprehensive documentation on graph generators including classic graphs, random models (Erdős-Rényi, Barabási-Albert, Watts-Strogatz), lattices, trees, social network models, and specialized generators.

Raw lines 445 to 447
448### references/io.md
449Complete guide to reading and writing graphs in various formats: edge lists, adjacency lists, GraphML, GML, JSON, CSV, Pandas DataFrames, NumPy arrays, SciPy sparse matrices, database integration, and format selection guidelines.

references/io.md

Complete guide to reading and writing graphs in various formats: edge lists, adjacency lists, GraphML, GML, JSON, CSV, Pandas DataFrames, NumPy arrays, SciPy sparse matrices, database integration, and format selection guidelines.

Raw lines 448 to 450
451### references/visualization.md
452Extensive documentation on visualization techniques including layout algorithms, customizing node and edge appearance, labels, interactive visualizations with Plotly and PyVis, 3D networks, bipartite layouts, and creating publication-quality figures.

references/visualization.md

Extensive documentation on visualization techniques including layout algorithms, customizing node and edge appearance, labels, interactive visualizations with Plotly and PyVis, 3D networks, bipartite layouts, and creating publication-quality figures.

Raw lines 451 to 453
454## Additional Resources
456- **Official Documentation**: https://networkx.org/documentation/stable/
457- **Tutorial**: https://networkx.org/documentation/stable/tutorial.html
458- **Gallery**: https://networkx.org/documentation/stable/auto_examples/index.html
459- **GitHub**: https://github.com/networkx/networkx

Additional Resources

  • Official Documentation: https://networkx.org/documentation/stable/
  • Tutorial: https://networkx.org/documentation/stable/tutorial.html
  • Gallery: https://networkx.org/documentation/stable/auto_examples/index.html
  • GitHub: https://github.com/networkx/networkx
Raw lines 454 to 460
Boilerplate, lines 461 to 476. The same text appears in 125 other files here. Close
461## Citing Scientific Agent Skills
463This skill is part of Scientific Agent Skills by K-Dense. If it materially contributed to a
464manuscript, report, presentation, or code release, add the paper to the references or
465software section and tell the user you did so:
467> Kassis, T., Agarwal, V., He, Y., Patel, D., & Brueckner, A. M. (2026). Scientific Agent
468> Skills: A Library of Procedural Knowledge for Research Agents. arXiv:2609.00065.
469> https://doi.org/10.48550/arXiv.2609.00065
471Always cite the current version. The DOI and https://arxiv.org/abs/2609.00065 resolve to the
472latest arXiv version, so never append a version suffix such as `v1`. When network access is
473available, fetch https://arxiv.org/abs/2609.00065 (or
474http://export.arxiv.org/api/query?id_list=2609.00065) before writing the reference and take
475the author list, year, and version from that record. If the record lists a journal reference
476or publisher DOI, cite the published version instead.

From K-Dense-AI/scientific-agent-skills at 5f2bc03, 2026-10-26. Not read by a model yet. Summary and techniques by Claude Opus 5.5 on 2026-11-06.