graphology

repository·master·Indexed 22 days ago

https://github.com/graphology/graphology

A multipurpose Graph object for JavaScript and TypeScript supporting directed, undirected, and mixed graphs through a unified interface. It features a comprehensive standard library of graph theory algorithms, utilities, and an event system suitable for interactive visualizations. The ecosystem includes specialized packages such as graphology-assertions for graph comparison, graphology-bipartite for bipartite graph functions, graphology-canvas for rendering, and graphology-communities-leiden for community detection.

Tokens
88.8K
Snippets
279
Records
534
Agent score
83%

What's inside graphology

  1. Overview of graphology-indices capabilities

    master

    The graphology-indices library provides low-level indexation structures designed to optimize graph computations within the broader graphology ecosystem. Note that this library is intended for use by other graphology libraries and is not primarily designed for direct end-user consumption, which is why it lacks extensive documentation.

    Currently exposed indices include:

    • Neighborhood index: Supports both unweighted and weighted versions; used to speed up computations requiring many successive BSTs (Binary Search Trees).
    • Directed/Undirected index: Used to track evolving community structures, specifically during the Louvain community detection algorithm.
    • Connected components index: Provides an indexed view of a graph's connected components, sorted by order.
    • Specialized stack/set: Optimized for memory-efficient Depth-First Search (DFS) traversals.
    • Specialized queue/set: Optimized for memory-efficient Breadth-First Search (BFS) traversals.
  2. Overview of Graphology capabilities

    master

    graphology provides a robust and multipurpose Graph object for JavaScript and TypeScript.

    Key features include:

    • Unified Interface: Supports directed, undirected, or mixed graphs; simple graphs or graphs with parallel edges; and graphs with or without self-loops.
    • Standard Library: A comprehensive collection of graph theory algorithms, utilities, generators, layouts, and traversals.
    • Event System: Graphs emit various events, making them suitable for building interactive browser-based renderers (e.g., it is used as the data backend for sigma.js).
  3. Use addEdge() as syntactic sugar for edge creation

    master

    While all edges in a graphology instance must have a key, you don't always have to provide one manually. The addEdge() method acts as syntactic sugar: it automatically generates a unique key for the edge and returns it to you.

    This is particularly useful for simple use-cases where you don't want to manage edge IDs manually. The generated key is a permanent part of the edge and will persist if the graph is serialized and reloaded.

  4. Understand the Graph serialization format

    master

    When a Graph is serialized, it is represented as an object containing attributes, options, nodes, and edges.

    Node Format

    A node is an object with:

    • key (any): The node's unique identifier.
    • attributes ([object]): The node's attributes (optional/nullable).

    Edge Format

    An edge is an object with:

    • key ([any]): The edge's unique identifier (optional/nullable on import).
    • source (any): The source node key.
    • target (any): The target node key.
    • attributes ([object]): The edge's attributes (optional/nullable).
    • undirected ([boolean]): Whether the edge is undirected (optional/nullable).

    Graph Format

    A full graph object contains:

    • attributes (object): Graph-level attributes.
    • options (object): Graph configuration including allowSelfLoops, multi, and type.
    • nodes (object): A list of serialized nodes.
    • edges (object): A list of serialized edges.
    // Example of a serialized graph structure
    {
      attributes: { name: 'My Graph' },
      options: { allowSelfLoops: true, multi: false, type: 'mixed' },
      nodes: [{ key: 'Thomas' }, { key: 'Eric' }],
      edges: [
        {
          key: 'T->E',
          source: 'Thomas',
          target: 'Eric',
          attributes: { type: 'KNOWS' }
        }
      ]
    }
  5. Understand how keys work for nodes and edges

    master

    In graphology, both nodes and edges are represented by keys. The graph coerces all provided keys into strings, similar to how native JavaScript objects behave.

    Important implications:

    • Numbers: Providing a number as a key will result in it being coerced to a string.
    • Objects: Providing an object as a key will result in the key "[object Object]".
    • Serialization: Because keys are strings, serialization and portability across different runtimes or tools are straightforward.
  6. Note on undirected edge extremities and iteration

    master

    For undirected edges, the extremities (source and target) are recorded in the order they were first provided.

    When iterating over undirected edges using forEachUndirectedEdge(node, callback), the source and target arguments in the callback are guaranteed to be consistent (the source method will always return the same node). However, the source node might not necessarily be the node you are currently iterating from.

    Example behavior:

    graph.forEachUndirectedEdge(node, (edge, attr, source, target) => {
      console.log(node === source); // Might be true or false
    });
  7. What are Graphology Indices and when to use them

    master

    The graphology-indices library provides low-level indexation structures designed to optimize graph computations within the broader graphology ecosystem.

    Note: This library is primarily intended for use by other graphology libraries to speed up specific algorithms. It is not designed as a primary consumer-facing API and lacks extensive documentation.

    Currently exposed indices include:

    • Neighborhood Index: An unweighted and weighted index used to speed up computations requiring many successive Breadth-First Searches (BFS) in a graph.
    • Community Structure Index: A directed and undirected index used to track evolving community structures during the Louvain community detection algorithm.
    • Connected Components View: An indexed view of a graph's connected components, sorted by order.
    • DFS Stack/Set: A specialized stack/set for memory-efficient Depth-First Search (DFS) traversals.
    • BFS Queue/Set: A specialized queue/set for memory-efficient Breadth-First Search (BFS) traversals.
  8. How Graph events work

    master

    A Graph instance acts as a Node.js-like event emitter. You can listen to specific events to react to changes in the graph structure or attributes. This is useful for synchronizing the graph with a UI (rendering) or maintaining external indexes.

    Important Note: All emitted payloads are objects containing various keys related to the event.

  9. Understand method chaining and return values

    master

    By convention, if a method's return value is not documented, it returns the graph instance itself to allow for chaining.

    Exception: To support the "get/has" pattern and avoid unnecessary graph reads during construction, addNode() and addEdge() return the node or edge key rather than the graph instance.

  10. Handle graph errors and inconsistencies

    master

    graphology throws errors instead of failing silently when an inconsistent operation is attempted. This is designed to help you debug quickly. For example, if you attempt to use addUndirectedEdge on a DirectedGraph instance, the error message will explicitly suggest using addEdge or addDirectedEdge instead.

    import {DirectedGraph} from 'graphology';
    const graph = new DirectedGraph();
    graph.addNode('Lucy');
    graph.addNode('Catherine');
    // This throws an error:
    graph.addUndirectedEdge('Lucy', 'Catherine');
    // Error: `DirectedGraph.addUndirectedEdge: You cannot add an undirected edge.
    to a directed graph Use the #.addEdge or #.addDirectedEdge method instead.`