ngraph.path

repository·main·Indexed 25 days ago

https://github.com/anvaka/ngraph.path

A high-performance library for finding paths in arbitrary graphs, supporting weighted, oriented, and guided searches. Version 1.6.1 provides several A* based finders, including aStar for standard guided search, aGreedy for speed over optimality, and nba for bi-directional optimal A* search. It supports custom distance functions, heuristics, and blocked path handling via the PathFinder interface.

Tokens
1.9K
Snippets
6
Records
16
Agent score
82%

What's inside ngraph.path

  1. Install ngraph.path

    main

    You can install the module via npm or use a CDN for browser-based projects.

    npm:

    npm i ngraph.path

    CDN:

    <script src="https://unpkg.com/ngraph.path@1.6.1/dist/ngraph.path.umd.js"></script>

    If using the CDN, the library is available under the global name ngraphPath.

    npm i ngraph.path
  2. Find paths in an unweighted graph

    main

    To find a path between two nodes in an unweighted graph, use the aStar finder. This is equivalent to Dijkstra's algorithm. The find method returns an array of nodes representing the path. If no path is found, it returns an empty array.

    let path = require('ngraph.path');
    let pathFinder = path.aStar(graph); // graph is an ngraph.graph instance
    
    let fromNodeId = 40;
    let toNodeId = 42;
    let foundPath = pathFinder.find(fromNodeId, toNodeId);
    // foundPath is array of nodes in the graph
  3. Handle blocked paths with the blocked() option

    main

    You can prevent the pathfinder from using certain links by providing a blocked function in the options. The blocked function receives (fromNode, toNode, link) and should return true if the path is blocked.

    let pathFinder = path.aStar(graph, {
      blocked(fromNode, toNode, link) {
        return link.data.disruption;
      },
    });
    let result = pathFinder.find('NYC', 'Washington');
  4. Use A* with a heuristic (Guided Search)

    main

    To speed up the search, you can provide a heuristic function. This function 'guesses' the distance between the current node and the target.

    Important: The heuristic must not overestimate the actual distance between nodes, otherwise the algorithm cannot guarantee the shortest path.

    Options:

    • distance(fromNode, toNode): The actual cost to move between nodes.
    • heuristic(fromNode, toNode): The estimated cost from the current node to the target.
    let pathFinder = aStar(graph, {
      distance(fromNode, toNode) {
        let dx = fromNode.data.x - toNode.data.x;
        let dy = fromNode.data.y - toNode.data.y;
        return Math.sqrt(dx * dx + dy * dy);
      },
      heuristic(fromNode, toNode) {
        let dx = fromNode.data.x - toNode.data.x;
        let dy = fromNode.data.y - toNode.data.y;
        return Math.sqrt(dx * dx + dy * dy);
      }
    });
    let path = pathFinder.find('NYC', 'Washington');
  5. Find paths in a weighted graph

    main

    To find the shortest path based on edge weights, provide a distance function in the options object passed to aStar. The distance function receives (fromNode, toNode, link) and should return the weight of the link.

    let pathFinder = aStar(graph, {
      distance(fromNode, toNode, link) {
        return link.data.weight;
      }
    });
    let path = pathFinder.find('a', 'd');
  6. Choose the right path finder

    main

    The library provides several A* based finders. All finders implement the .find(fromNodeId, toNodeId) method.

    FinderBest Use Case
    aStarStandard A* search. Use if you can provide a heuristic.
    aGreedyUse when speed is more important than finding the mathematically optimal path.
    nbaNBA*: A bi-directional, optimal A* algorithm. Use when accuracy and optimality are the top priority.
    Dijkstra(Implicitly via aStar without heuristic) Use if there is no way to estimate distance between nodes.
  7. Implement NBA* pathfinding

    main

    The nba function implements the NBA* (Yet another bidirectional algorithm for shortest paths) algorithm. It creates a pathfinder object used to find the shortest path between two nodes in a graph. It supports weighted graphs, heuristics (A*), oriented graphs, and blocked paths.

    Parameters

    • graph: An ngraph.graph instance.
    • options: An object to configure the search:
      • blocked: A function (a, b, link) => boolean that returns true if the link between nodes a and b is blocked. This allows temporarily blocking routes without rebuilding the graph.
      • heuristic: A function (a, b) => number that returns an estimated distance between nodes a and b. It must be admissible (never overestimate actual distance). Defaults to returning 0 (Dijkstra search).
      • distance: A function (a, b, link) => number that returns the actual distance between nodes a and b. Defaults to graph-theoretical distance (always 1).
      • oriented: Boolean. If true, the search respects edge directionality.
      • quitFast: Boolean. If true, the search terminates as soon as a path is found (may not be the shortest if the heuristic is not perfect).
  8. Configure PathFinderOptions for pathfinding algorithms

    main

    When using aStar, aGreedy, or nba, you can provide an optional PathFinderOptions object to customize the search behavior. Supported options include:

    • oriented: boolean. If true, the search respects the direction of links in the graph.
    • quitFast: boolean. If true, the algorithm may terminate earlier with a potentially non-optimal path.
    • heuristic: function. A function (from: Node<NodeData>, to: Node<NodeData>) => number used for guided searches (like A-Star). It estimates the cost from the current node to the destination.
    • distance: function. A function (from: Node<NodeData>, to: Node<NodeData>, link: Link<LinkData>) => number that defines the weight/cost of traversing a specific link.
    • blocked: function. A function (from: Node<NodeData>, to: Node<NodeData>, link: Link<LinkData>) => boolean that allows you to dynamically prevent the algorithm from traversing certain links.
  9. Find paths using the PathFinder interface

    main
    All pathfinding functions (aStar, aGreedy, nba) return an object implementing the PathFinder interface. The primary method is find(from: NodeId, to: NodeId), which returns an array of Node<NodeData> representing the path from the start node to the end node.