Skills Agentes

Networkx

Crea, analiza y visualiza redes y grafos complejos en Python con NetworkX: algoritmos de grafos (caminos más cortos, centralidad, clustering), detección de comunidades, generación de redes sintéticas y E/S de formatos.

Estrellas
34.8k

en todo el repo

Actividad
59

0–100, la ruta de este skill

Actualizado
el mes pasado

último commit aquí

Commits
4

últimos 90 días

Contexto
3.4k tok

112 tok en reposo

Paquete
6 archivos

59 KB

Instalar

Funciona con cualquier agente que lea SKILL.md

npx -y skills add K-Dense-AI/scientific-agent-skills --skill networkx --agent claude-code

Se instala solo en este repositorio.

Qué hace

  • Crea y manipula grafos (Graph, DiGraph, MultiGraph, MultiDiGraph) con nodos y aristas con atributos
  • Calcula algoritmos de grafos: caminos más cortos, centralidad (grado, intermediación, PageRank), clustering y componentes conexas
  • Detecta comunidades con algoritmos como greedy_modularity_communities
  • Genera redes sintéticas (Erdős-Rényi, Barabási-Albert, Watts-Strogatz) y grafos clásicos o estructurados
  • Lee y escribe grafos en formatos como edge list, GraphML, GML, JSON, CSV y matrices, y los dibuja con matplotlib

Úsalo cuando

  • Se trabaja con estructuras de datos de red o grafo (sociales, biológicas, de transporte, de citas)
  • Se calculan algoritmos como Dijkstra, PageRank, árboles de expansión mínima o flujo máximo
  • Se generan redes sintéticas para pruebas o simulación
  • Se leen o escriben grafos en distintos formatos, o se visualizan topologías de red

No lo uses cuando

    Qué lo activa

    Di cualquiera de estas frases y el agente debería cargar este skill.

    • Calcula la centralidad de intermediación de este grafo con NetworkX
    • Detecta comunidades en esta red social
    • Genera una red Barabási-Albert de 100 nodos
    • Dibuja este grafo con un layout de resorte

    SKILL.md

    En inglés

    NetworkX

    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 NetworkX 3.x (current stable: 3.6, which requires Python >= 3.11). 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.

    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

    Core Capabilities

    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.

    2. Graph Algorithms

    NetworkX provides extensive algorithms for network analysis:

    Shortest Paths:

    # Find shortest path
    path = nx.shortest_path(G, source=1, target=5)
    length = nx.shortest_path_length(G, source=1, target=5, weight='weight')
    

    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
    
    # Detect communities
    communities = community.greedy_modularity_communities(G)
    

    Connectivity:

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

    Reference: See references/algorithms.md for detailed documentation on all available algorithms including shortest paths, centrality measures, clustering, community detection, flows, matching, tree algorithms, and graph traversal.

    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 comprehensive coverage of all graph generators including classic, random, lattice, bipartite, and specialized network models with detailed parameters and 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 (preserves attributes)
    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)
    G = nx.node_link_graph(data)
    

    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
    
    # Adjacency matrix
    A = nx.to_numpy_array(G)
    G = nx.from_numpy_array(A)
    
    # Sparse matrix
    A = nx.to_scipy_sparse_array(G)
    G = nx.from_scipy_sparse_array(A)
    

    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.

    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:

    plt.figure(figsize=(12, 8))
    pos = nx.spring_layout(G, seed=42)
    nx.draw(G, pos=pos, 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.

    Working with NetworkX

    Installation

    Ensure NetworkX is installed:

    # Check if installed
    import networkx as nx
    print(nx.__version__)
    
    # Install if needed (via bash)
    # uv pip install networkx
    # uv pip install networkx[default]  # With optional dependencies
    

    Common Workflow Pattern

    Most NetworkX tasks follow this pattern:

    1. Create or Load Graph:

      # 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')
      
    2. Examine Structure:

      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)}")
      
    3. Analyze:

      # 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)
      
    4. Visualize:

      pos = nx.spring_layout(G, seed=42)
      nx.draw(G, pos=pos, with_labels=True)
      plt.show()
      
    5. Export Results:

      # 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)
      

    Important Considerations

    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, NetworkX 3.x supports drop-in accelerated backends via the backend= keyword or nx.config.backend_priority — e.g. nx-cugraph (GPU), nx-parallel (multicore), graphblas-algorithms (sparse linear algebra). Install the backend package and pass backend="cugraph" (or similar) to supported functions; no algorithm code changes needed.

    Node and Edge Types:

    • Nodes can be any hashable Python object (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)
    

    Quick Reference

    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
    G.remove_node(1)
    G.remove_edge(1, 2)
    G.clear()
    

    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)
    

    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)
    

    Resources

    This skill includes comprehensive reference documentation:

    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.

    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.

    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.

    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.

    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.

    Additional Resources

    Reproducido de K-Dense-AI/scientific-agent-skills bajo licencia 3-clause BSD license. Leer esta página en markdown.

    Archivos

    6 archivos en el paquete. Solo se lee SKILL.md al activarse — las referencias se cargan si el skill decide que las necesita.

    Antes de instalar

    Está pensado para NetworkX 3.x (estable 3.6), que requiere Python >= 3.11; se instala con `uv pip install networkx`.

    Detalles

    Creador
    K-Dense-AI
    Licencia
    3-clause BSD license
    Recursos incluidos
    referencias
    Código fuente
    Ver SKILL.md

    Etiquetas

    Más de K-Dense-AI/scientific-agent-skills

    Este repo incluye 163 skills. Si instalas uno, normalmente ya tienes los demás.

    Gestión integral de citas académicas: busca en OpenAlex, PubMed y Google Scholar, extrae metadatos precisos, valida citas y genera entradas BibTeX correctamente formateadas.

    Costo de contexto al activarse
    3.7k tok
    Tamaño del paquete
    21 archivos
    Última actualización
    hace 28 días
    investigacion

    Realiza revisiones bibliográficas sistemáticas y completas usando varias bases académicas (PubMed, arXiv, bioRxiv, Semantic Scholar). Genera markdown y PDF con citas verificadas en varios estilos (APA, Nature, Vancouver).

    Costo de contexto al activarse
    3.2k tok
    Tamaño del paquete
    12 archivos
    Última actualización
    hace 15 días
    investigacion

    Crea decks de diapositivas y presentaciones para charlas de investigación: PowerPoint, presentaciones de conferencia, seminarios, defensas de tesis. Da estructura, plantillas, guía de tiempos y validación visual.

    Costo de contexto al activarse
    5.1k tok
    Tamaño del paquete
    24 archivos
    Última actualización
    hace 15 días
    documentos

    Crea infografías profesionales con Nano Banana Pro AI y refinamiento iterativo inteligente. Usa Gemini 3.6 Flash para revisar la calidad e integra investigación con Perplexity Sonar. Soporta 10 tipos, 8 estilos y paletas para daltonismo.

    Costo de contexto al activarse
    2.7k tok
    Tamaño del paquete
    8 archivos
    Última actualización
    hace 15 días
    diseno ui

    Crea pósteres de investigación profesionales en LaTeX con beamerposter, tikzposter o baposter, para conferencias y comunicación científica: layout, colores, columnas múltiples e integración de figuras.

    Costo de contexto al activarse
    3.9k tok
    Tamaño del paquete
    17 archivos
    Última actualización
    hace 15 días
    documentos

    Crea diagramas científicos de calidad de publicación con la IA Nano Banana 2 y refinamiento iterativo inteligente. Gemini 3.6 Flash revisa la calidad y solo regenera si está por debajo del umbral de tu tipo de documento.

    Costo de contexto al activarse
    4.1k tok
    Tamaño del paquete
    6 archivos
    Última actualización
    hace 15 días
    diseno ui

    Skills relacionados

    Aeon

    34.8k

    Para tareas de machine learning con series temporales: clasificación, regresión, clustering, forecasting, detección de anomalías, segmentación y búsqueda de similitud, con APIs compatibles con scikit-learn.

    Costo de contexto al activarse
    3.1k tok
    Tamaño del paquete
    12 archivos
    Última actualización
    el mes pasado
    datos analitica

    Anndata

    34.8k

    Estructura de datos para matrices anotadas en análisis de célula única. Úsala con archivos .h5ad o el ecosistema scverse; para análisis usa scanpy, para modelos probabilísticos scvi-tools, para escala poblacional cellxgene-census.

    Costo de contexto al activarse
    3k tok
    Tamaño del paquete
    6 archivos
    Última actualización
    el mes pasado
    datos analitica

    Infiere redes de regulación génica (GRN) a partir de datos de expresión génica con algoritmos escalables (GRNBoost2, GENIE3), para transcriptómica bulk o de célula única, con computación distribuida.

    Costo de contexto al activarse
    2.1k tok
    Tamaño del paquete
    5 archivos
    Última actualización
    el mes pasado
    datos analitica