Search code examples
pythonalgorithmshortest-pathbellman-ford

Which python package implements the Bellman-Ford shortest path algorithm?


Which python package implements the Bellman-Ford shortest path algorithm?

Given a starting node i and an adjacency matrix G with negative weights I want to find the shortest path from i to another node j. E.g. my graph looks like:

import numpy
G = numpy.array([[ 0.  ,  0.55,  1.22],
                 [-0.54,  0.  ,  0.63],
                 [-1.3 , -0.63,  0.  ]])

I can only find an all-pairs shortest path implementation which seems too wasteful for my needs given my graph is large and I only need the shortest path for 1 pair of nodes. Performance will be important for me given I will use it for thousands of graphs.

Hence I'm looking around for a Bellman-Ford implementation -- has anyone seen one?


Solution

  • Rolled my own

    def bellmanFord(source, weights):
        '''
        This implementation takes in a graph and fills two arrays
        (distance and predecessor) with shortest-path (less cost/distance/metric) information
    
        https://en.wikipedia.org/wiki/Bellman%E2%80%93Ford_algorithm
        '''
        n = weights.shape[0]
    
        # Step 1: initialize graph
        distance = np.empty(n)
        distance.fill(float('Inf'))      # At the beginning, all vertices have a weight of infinity
        predecessor = np.empty(n)
        predecessor.fill(float('NaN'))   # And a null predecessor
    
        distance[source] = 0             # Except for the Source, where the Weight is zero
    
        # Step 2: relax edges repeatedly
        for _ in xrange(1, n):
            for (u, v), w in np.ndenumerate(weights):
            if distance[u] + w < distance[v]:
            distance[v] = distance[u] + w
        predecessor[v] = u
    
        # Step 3: check for negative-weight cycles
        for (u, v), w in np.ndenumerate(weights):
            if distance[u] + w < distance[v]:
            raise ValueError("Graph contains a negative-weight cycle")
    
        return distance, predecessor