Bellman-Ford Single-Source Shortest Path
Glossary
- Directed
-
Directed trait. The algorithm is well-defined on a directed graph.
- Directed
-
Directed trait. The algorithm ignores the direction of the graph.
- Directed
-
Directed trait. The algorithm does not run on a directed graph.
- Undirected
-
Undirected trait. The algorithm is well-defined on an undirected graph.
- Undirected
-
Undirected trait. The algorithm ignores the undirectedness of the graph.
- Heterogeneous nodes
-
Heterogeneous nodes fully supported. The algorithm has the ability to distinguish between nodes of different types.
- Heterogeneous nodes
-
Heterogeneous nodes allowed. The algorithm treats all selected nodes similarly regardless of their label.
- Heterogeneous relationships
-
Heterogeneous relationships fully supported. The algorithm has the ability to distinguish between relationships of different types.
- Heterogeneous relationships
-
Heterogeneous relationships allowed. The algorithm treats all selected relationships similarly regardless of their type.
- Weighted relationships
-
Weighted trait. The algorithm supports a relationship property to be used as weight, specified via the relationshipWeightProperty configuration parameter.
- Weighted relationships
-
Weighted trait. The algorithm treats each relationship as equally important, discarding the value of any relationship weight.
Introduction
The Bellman-Ford Path algorithm computes the shortest path between nodes.
In contrast to the Dijkstra algorithm which works only for graphs with non-negative relationship weights, Bellman-Ford can also handle graphs with negative weights provided that the source cannot reach any node involved in a negative cycle. A cycle in a graph is a path starting and ending at the same node. A negative cycle is a cycle for which the sum of the relationship weights is negative. When negative cycles exist, shortest paths cannot easily be defined. That is so because we can traverse a negative cycle multiple times to get smaller and smaller costs each time.
When the Bellman-Ford algorithm detects negative cycles, it will return negative cycles instead of shortest paths. As the full set of negative cycles can be too large to enumerate, each node will be included in at most one returned negative cycle.
The ability to handle negative weights makes Bellman-Ford more versatile than Dijkstra, but also slower in practice.
The Neo4j GDS Library provides an adaptation of the original Bellman-Ford algorithm called Shortest-Path Faster Algorithm (SPFA). SPFA significantly reduces the computational time of Bellman-Ford by working only on a subset of the nodes rather than iterating over the set of nodes at each step. In addition, the computations are parallelized to further speed-up computations.
Syntax
This section covers the syntax used to execute the Bellman-Ford algorithm in each of its execution modes. We are describing the named graph variant of the syntax. To learn more about general syntax variants, see Syntax overview.
CALL gds.bellmanFord.stream(
graphName: String,
configuration: Map
)
YIELD
index: Integer,
sourceNode: Integer,
targetNode: Integer,
totalCost: Float,
nodeIds: List of Integer,
costs: List of Float,
route: Path,
isNegativeCycle: Boolean
Name | Type | Default | Optional | Description |
---|---|---|---|---|
graphName |
String |
|
no |
The name of a graph stored in the catalog. |
configuration |
Map |
|
yes |
Configuration for algorithm-specifics and/or graph filtering. |
Name | Type | Default | Optional | Description |
---|---|---|---|---|
List of String |
|
yes |
Filter the named graph using the given node labels. Nodes with any of the given labels will be included. |
|
List of String |
|
yes |
Filter the named graph using the given relationship types. Relationships with any of the given types will be included. |
|
Integer |
|
yes |
The number of concurrent threads used for running the algorithm. |
|
String |
|
yes |
An ID that can be provided to more easily track the algorithm’s progress. |
|
Boolean |
|
yes |
If disabled the progress percentage will not be logged. |
|
sourceNode |
Integer |
|
no |
The Neo4j source node or node id. |
String |
|
yes |
Name of the relationship property to use as weights. If unspecified, the algorithm runs unweighted. |
Name | Type | Description |
---|---|---|
index |
Integer |
0-based index of the found route. |
sourceNode |
Integer |
Source node of the route. |
targetNode |
Integer |
Target node of the route. |
totalCost |
Float |
Total cost from source to target. |
nodeIds |
List of Integer |
Node ids on the route in traversal order. |
costs |
List of Float |
Accumulated costs for each node on the route. |
route |
Path |
The route represented as Cypher entity. |
isNegativeCycle |
Boolean |
If true, the discovered route is a negative cycle. Otherwise it is a shortest path. |
The mutate mode creates new relationships in the projected graph.
Each relationship represents a path from the source node to the target node.
The total cost of a path is stored via the totalCost
relationship property.
CALL gds.bellmanFord.mutate(
graphName: String,
configuration: Map
)
YIELD
relationshipsWritten: Integer,
preProcessingMillis: Integer,
computeMillis: Integer,
postProcessingMillis: Integer,
mutateMillis: Integer,
containsNegativeCycle: Boolean,
configuration: Map
Name | Type | Default | Optional | Description |
---|---|---|---|---|
graphName |
String |
|
no |
The name of a graph stored in the catalog. |
configuration |
Map |
|
yes |
Configuration for algorithm-specifics and/or graph filtering. |
Name | Type | Default | Optional | Description |
---|---|---|---|---|
mutateRelationshipType |
String |
|
no |
The relationship type used for the new relationships written to the projected graph. |
List of String |
|
yes |
Filter the named graph using the given node labels. |
|
List of String |
|
yes |
Filter the named graph using the given relationship types. |
|
Integer |
|
yes |
The number of concurrent threads used for running the algorithm. |
|
String |
|
yes |
An ID that can be provided to more easily track the algorithm’s progress. |
|
sourceNode |
Integer |
|
no |
The Neo4j source node or node id. |
mutateNegativeCycles |
Boolean |
|
yes |
If set to true, any discovered negative cycles will be added in the in-memory graph. Otherwise they will be skipped. |
Name | Type | Description |
---|---|---|
preProcessingMillis |
Integer |
Milliseconds for preprocessing the graph. |
computeMillis |
Integer |
Milliseconds for running the algorithm. |
postProcessingMillis |
Integer |
Unused. |
mutateMillis |
Integer |
Milliseconds for adding relationships to the projected graph. |
relationshipsWritten |
Integer |
The number of relationships that were added. |
containsNegativeCycle |
Boolean |
True if negative cycles were discovered. |
configuration |
Map |
The configuration used for running the algorithm. |
The write mode creates new relationships in the Neo4j database.
Each relationship represents a path from the source node to the target node.
Additional path information is stored using relationship properties.
By default, the write mode stores a totalCost
property.
Optionally, one can also store nodeIds
and costs
of intermediate nodes on the path.
CALL gds.bellmanFord.write(
graphName: String,
configuration: Map
)
YIELD
relationshipsWritten: Integer,
preProcessingMillis: Integer,
computeMillis: Integer,
postProcessingMillis: Integer,
writeMillis: Integer,
containsNegativeCycle: Boolean,
configuration: Map
Name | Type | Default | Optional | Description |
---|---|---|---|---|
graphName |
String |
|
no |
The name of a graph stored in the catalog. |
configuration |
Map |
|
yes |
Configuration for algorithm-specifics and/or graph filtering. |
Name | Type | Default | Optional | Description |
---|---|---|---|---|
sourceNode |
Integer |
|
no |
The Neo4j source node or node id. |
writeNegativeCycles |
Boolean |
|
yes |
If set to true, any discovered negative cycles will be written back to the Neo4j graph. Otherwise they will be skipped. |
Name | Type | Description |
---|---|---|
preProcessingMillis |
Integer |
Milliseconds for preprocessing the graph. |
computeMillis |
Integer |
Milliseconds for running the algorithm. |
postProcessingMillis |
Integer |
Unused. |
writeMillis |
Integer |
Milliseconds for writing relationships to Neo4j. |
relationshipsWritten |
Integer |
The number of relationships that were written. |
containsNegativeCycle |
Boolean |
True if negative cycles were discovered. |
configuration |
Map |
The configuration used for running the algorithm. |
CALL gds.bellmanFord.stats(
graphName: String,
configuration: Map
)
YIELD
preProcessingMillis: Integer,
computeMillis: Integer,
postProcessingMillis: Integer,
containsNegativeCycle: Boolean,
configuration: Map
Name | Type | Default | Optional | Description |
---|---|---|---|---|
graphName |
String |
|
no |
The name of a graph stored in the catalog. |
configuration |
Map |
|
yes |
Configuration for algorithm-specifics and/or graph filtering. |
Name | Type | Default | Optional | Description |
---|---|---|---|---|
sourceNode |
Integer |
|
no |
The Neo4j source node or node id. |
Name | Type | Description |
---|---|---|
preProcessingMillis |
Integer |
Milliseconds for preprocessing the graph. |
computeMillis |
Integer |
Milliseconds for running the algorithm. |
postProcessingMillis |
Integer |
Unused. |
containsNegativeCycle |
Boolean |
True if negative cycles were discovered. |
configuration |
Map |
The configuration used for running the algorithm. |
Examples
All the examples below should be run in an empty database. The examples use Cypher projections as the norm. Native projections will be deprecated in a future release. |
In this section we will show examples of running the Bellman-Ford algorithm on a concrete graph. The intention is to illustrate what the results look like and to provide a guide in how to make use of the algorithm in a real setting. We will do this on a small example network graph of a handful nodes connected in a particular pattern. The example graph looks like this:
CREATE (a:Node {name: 'A'}),
(b:Node {name: 'B'}),
(c:Node {name: 'C'}),
(d:Node {name: 'D'}),
(e:Node {name: 'E'}),
(f:Node {name: 'F'}),
(g:Node {name: 'G'}),
(h:Node {name: 'H'}),
(i:Node {name: 'I'}),
(a)-[:REL {cost: 50}]->(b),
(a)-[:REL {cost: -50}]->(c),
(a)-[:REL {cost: 100}]->(d),
(b)-[:REL {cost: 40}]->(d),
(c)-[:REL {cost: 40}]->(d),
(c)-[:REL {cost: 80}]->(e),
(d)-[:REL {cost: 30}]->(e),
(d)-[:REL {cost: 80}]->(f),
(e)-[:REL {cost: 40}]->(f),
(g)-[:REL {cost: 40}]->(h),
(h)-[:REL {cost: -60}]->(i),
(i)-[:REL {cost: 10}]->(g)
This graph builds an example network with relationships between nodes having both negative and positive weights.
These weights are represented by the cost
relationship property.
MATCH (source:Node)-[r:REL]->(target:Node)
RETURN gds.graph.project(
'myGraph',
source,
target,
{ relationshipProperties: r { .cost } }
)
In the following example we will demonstrate the use of the Bellman-Ford Shortest Path algorithm using this graph.
Memory Estimation
First off, we will estimate the cost of running the algorithm using the estimate
procedure.
This can be done with any execution mode.
We will use the write
mode in this example.
Estimating the algorithm is useful to understand the memory impact that running the algorithm on your graph will have.
When you later actually run the algorithm in one of the execution modes the system will perform an estimation.
If the estimation shows that there is a very high probability of the execution going over its memory limitations, the execution is prohibited.
To read more about this, see Automatic estimation and execution blocking.
For more details on estimate
in general, see Memory Estimation.
MATCH (source:Node {name: 'A'})
CALL gds.bellmanFord.write.estimate('myGraph', {
sourceNode: source,
relationshipWeightProperty: 'cost',
writeRelationshipType: 'PATH'
})
YIELD nodeCount, relationshipCount, bytesMin, bytesMax, requiredMemory
RETURN nodeCount, relationshipCount, bytesMin, bytesMax, requiredMemory
nodeCount | relationshipCount | bytesMin | bytesMax | requiredMemory |
---|---|---|---|---|
9 |
12 |
1336 |
1336 |
"1336 Bytes" |
The algorithm supports writing (or mutating) negative cycles if they exist in the graph, this is controlled by the writeNegativeCycles
(mutateNegativeCycles
) configuration parameter.
This requires additional memory because the negative cycles have to be tracked.
MATCH (source:Node {name: 'A'})
CALL gds.bellmanFord.write.estimate('myGraph', {
sourceNode: source,
relationshipWeightProperty: 'cost',
writeRelationshipType: 'PATH',
writeNegativeCycles: true
})
YIELD nodeCount, relationshipCount, bytesMin, bytesMax, requiredMemory
RETURN nodeCount, relationshipCount, bytesMin, bytesMax, requiredMemory
nodeCount | relationshipCount | bytesMin | bytesMax | requiredMemory |
---|---|---|---|---|
9 |
12 |
1448 |
1448 |
"1448 Bytes" |
Stream
In the stream
execution mode, the algorithm returns the shortest path for each source-target-pair or negative cycles.
This allows us to inspect the results directly or post-process them in Cypher without any side effects.
Stream without negative cycles
MATCH (source:Node {name: 'A'})
CALL gds.bellmanFord.stream('myGraph', {
sourceNode: source,
relationshipWeightProperty: 'cost'
})
YIELD index, sourceNode, targetNode, totalCost, nodeIds, costs, route, isNegativeCycle
RETURN
index,
gds.util.asNode(sourceNode).name AS sourceNode,
gds.util.asNode(targetNode).name AS targetNode,
totalCost,
[nodeId IN nodeIds | gds.util.asNode(nodeId).name] AS nodeNames,
costs,
nodes(route) as route,
isNegativeCycle as isNegativeCycle
ORDER BY index
index | sourceNode | targetNode | totalCost | nodeNames | costs | route | isNegativeCycle |
---|---|---|---|---|---|---|---|
0 |
"A" |
"A" |
0.0 |
["A"] |
[0.0] |
[Node[0]] |
false |
1 |
"A" |
"B" |
50.0 |
["A", "B"] |
[0.0, 50.0] |
[Node[0], Node[1]] |
false |
2 |
"A" |
"C" |
-50.0 |
["A", "C"] |
[0.0, -50.0] |
[Node[0], Node[2]] |
false |
3 |
"A" |
"D" |
-10.0 |
["A", "C", "D"] |
[0.0, -50.0, -10.0] |
[Node[0], Node[2], Node[3]] |
false |
4 |
"A" |
"E" |
20.0 |
["A", "C", "D", "E"] |
[0.0, -50.0, -10.0, 20.0] |
[Node[0], Node[2], Node[3], Node[4]] |
false |
5 |
"A" |
"F" |
60.0 |
["A", "C", "D", "E", "F"] |
[0.0, -50.0, -10.0, 20.0, 60.0] |
[Node[0], Node[2], Node[3], Node[4], Node[5]] |
false |
Since the component of A
does not contain any negative cycles, the results depict the shortest paths from A
to all of its reachable nodes.
The ordered lists of node ids for each path as well as their accumulated costs are also returned.
The Cypher Path objects are returned by the path
return field, they contain node objects and virtual relationships which have a cost
property.
Stream with negative cycles
MATCH (source:Node {name: 'G'})
CALL gds.bellmanFord.stream('myGraph', {
sourceNode: source,
relationshipWeightProperty: 'cost'
})
YIELD index, sourceNode, targetNode, totalCost, nodeIds, costs, route, isNegativeCycle
RETURN
index,
gds.util.asNode(sourceNode).name AS sourceNode,
gds.util.asNode(targetNode).name AS targetNode,
totalCost,
[nodeId IN nodeIds | gds.util.asNode(nodeId).name] AS nodeNames,
costs,
nodes(route) as route,
isNegativeCycle as isNegativeCycle
ORDER BY index
index | sourceNode | targetNode | totalCost | nodeNames | costs | route | isNegativeCycle |
---|---|---|---|---|---|---|---|
0 |
"G" |
"G" |
-10.0 |
["G", "H", "I", "G"] |
[0.0, 40.0, -20.0, -10.0] |
[Node[6], Node[7], Node[8], Node[6]] |
true |
For this example, Bellman-Ford did not yield any shortest paths as it detected negative cycles.
A negative cycle for G
of -10 total cost is emitted as the output, with the isNegativeCycle
field set to true.
Stats
In the stats
execution mode, the algorithm returns a single row containing a summary of the algorithm result.
This execution mode does not have any side effects.
It can be useful for evaluating algorithm performance by inspecting the computeMillis
return item.
In the examples below we will omit returning the timings.
The full signature of the procedure can be found in the syntax section.
For more details on the stats
mode in general, see Stats.
stats
modeMATCH (source:Node {name: 'A'})
CALL gds.bellmanFord.stats('myGraph', {
sourceNode: source,
relationshipWeightProperty: 'cost'
})
YIELD containsNegativeCycle
RETURN containsNegativeCycle
containsNegativeCycle |
---|
false |
Running stats mode can be useful if we want to discover if the graph has any negative cycles, but we do not to have them computed or stored.
For this example, we can see that the containsNegativeCycle
field is false as A
cannot reach any negative cycles.
Mutate
The mutate
execution mode updates the named graph with new relationships.
Each new relationship represents a path from source node to target node or a negative cycle.
The relationship type is configured using the mutateRelationshipType option.
The total route cost is stored using the totalCost property.
Mutate without negative cycles
MATCH (source:Node {name: 'A'})
CALL gds.bellmanFord.mutate('myGraph', {
sourceNode: source,
relationshipWeightProperty: 'cost',
mutateRelationshipType: 'ROUTE'
})
YIELD relationshipsWritten, containsNegativeCycle
RETURN relationshipsWritten, containsNegativeCycle
relationshipsWritten | containsNegativeCycle |
---|---|
6 |
false |
After executing the above query, the in-memory graph will be updated with new relationships of type ROUTE
.
Since containsNegativeCycle
is false, these relationships represent shortest paths.
The new relationships will store a single property totalCost
, corresponding to the shortest path cost from source to target.
Mutate with negative cycles
MATCH (source:Node {name: 'G'})
CALL gds.bellmanFord.mutate('myGraph', {
sourceNode: source,
relationshipWeightProperty: 'cost',
mutateRelationshipType: 'ROUTE',
mutateNegativeCycles: true
})
YIELD relationshipsWritten, containsNegativeCycle
RETURN relationshipsWritten, containsNegativeCycle
relationshipsWritten | containsNegativeCycle |
---|---|
1 |
true |
After executing the above query, the in-memory graph will be updated with a single relationship of type ROUTE
.
Since containsNegativeCycle
is true, this relationship represents the discovered negative cycle.
The new relationship stores a single property totalCost
, corresponding to the weight of the negative cycle.
Note that by default, when negative cycles are detected during mutate mode, they will not be written back to the in-memory graph.
This can be bypassed by setting the mutateNegativeCycles
to true as showcased in the above example.
The relationships produced are always directed, even if the input graph is undirected. |
Write
The write
execution mode updates the Neo4j database with new relationships.
Each new relationship represents a path from source node to target node or a negative cycle.
The relationship type is configured using the writeRelationshipType option.
The total cost is stored using the totalCost property.
The intermediate node ids are stored using the nodeIds property.
The accumulated costs to reach an intermediate node are stored using the costs property.
Write without negative cycles
MATCH (source:Node {name: 'A'})
CALL gds.bellmanFord.write('myGraph', {
sourceNode: source,
relationshipWeightProperty: 'cost',
writeRelationshipType: 'ROUTE',
writeNodeIds: true,
writeCosts: true
})
YIELD relationshipsWritten, containsNegativeCycle
RETURN relationshipsWritten, containsNegativeCycle
relationshipsWritten | containsNegativeCycle |
---|---|
6 |
false |
The above query will write 6 relationships of type ROUTE
back to Neo4j.
The relationships store three properties describing the path: totalCost
, nodeIds
and costs
.
Write with negative cycles
MATCH (source:Node {name: 'G'})
CALL gds.bellmanFord.write('myGraph', {
sourceNode: source,
relationshipWeightProperty: 'cost',
writeRelationshipType: 'ROUTE',
writeNodeIds: true,
writeCosts: true,
writeNegativeCycles:true
})
YIELD relationshipsWritten, containsNegativeCycle
RETURN relationshipsWritten, containsNegativeCycle
relationshipsWritten | containsNegativeCycle |
---|---|
1 |
true |
After executing the above query, one relationship of type ROUTE
is written back to the Neo4j graph.
Since containsNegativeCycle
is true, the relationship represents a negative cycle.
Similar to the mutate
mode, the default behavior when encountering negative cycles is to not write them back in tne Neo4j database.
We can set writeNegativeCycles
to true as in the example to override this setting.
The relationships written are always directed, even if the input graph is undirected. |