Files
gonum/graph/path/bellman_ford_moore.go
Dan Kortschak 3d5d9d4a35 graph/path: allow incremental Bellman-Ford search
The impact on the current implementation is negligible.

name                          old time/op    new time/op    delta
BellmanFordFrom/500_tenth-8     4.14ms ± 1%    4.11ms ± 1%  -0.73%  (p=0.001 n=10+9)
BellmanFordFrom/1000_tenth-8    16.3ms ± 1%    16.1ms ± 1%  -0.82%  (p=0.000 n=10+10)
BellmanFordFrom/2000_tenth-8    66.2ms ± 1%    60.9ms ± 0%  -8.08%  (p=0.000 n=10+9)
BellmanFordFrom/500_half-8      18.0ms ± 5%    16.9ms ± 1%  -6.28%  (p=0.000 n=10+9)
BellmanFordFrom/1000_half-8     68.5ms ± 2%    67.4ms ± 1%  -1.50%  (p=0.000 n=9+8)
BellmanFordFrom/2000_half-8      281ms ± 1%     276ms ± 1%  -1.45%  (p=0.000 n=9+10)
BellmanFordFrom/500_full-8      33.4ms ± 0%    33.0ms ± 1%  -1.29%  (p=0.000 n=9+9)
BellmanFordFrom/1000_full-8      137ms ± 1%     133ms ± 0%  -3.11%  (p=0.000 n=8+9)
BellmanFordFrom/2000_full-8      549ms ± 1%     546ms ± 1%    ~     (p=0.065 n=10+9)

name                          old alloc/op   new alloc/op   delta
BellmanFordFrom/500_tenth-8      142kB ± 0%     142kB ± 0%    ~     (p=0.110 n=10+9)
BellmanFordFrom/1000_tenth-8     284kB ± 0%     284kB ± 0%    ~     (p=0.382 n=10+10)
BellmanFordFrom/2000_tenth-8     624kB ± 0%     624kB ± 0%    ~     (p=0.956 n=10+10)
BellmanFordFrom/500_half-8       142kB ± 0%     142kB ± 0%    ~     (p=0.666 n=10+10)
BellmanFordFrom/1000_half-8      284kB ± 0%     284kB ± 0%    ~     (p=0.070 n=10+8)
BellmanFordFrom/2000_half-8      624kB ± 0%     624kB ± 0%    ~     (p=0.290 n=10+10)
BellmanFordFrom/500_full-8       142kB ± 0%     142kB ± 0%    ~     (p=0.234 n=9+10)
BellmanFordFrom/1000_full-8      284kB ± 0%     284kB ± 0%    ~     (p=0.051 n=10+9)
BellmanFordFrom/2000_full-8      624kB ± 0%     624kB ± 0%    ~     (p=0.790 n=9+10)

name                          old allocs/op  new allocs/op  delta
BellmanFordFrom/500_tenth-8      2.03k ± 0%     2.03k ± 0%    ~     (all equal)
BellmanFordFrom/1000_tenth-8     4.03k ± 0%     4.03k ± 0%    ~     (all equal)
BellmanFordFrom/2000_tenth-8     8.03k ± 0%     8.03k ± 0%    ~     (all equal)
BellmanFordFrom/500_half-8       2.03k ± 0%     2.03k ± 0%    ~     (p=0.294 n=10+8)
BellmanFordFrom/1000_half-8      4.03k ± 0%     4.03k ± 0%    ~     (all equal)
BellmanFordFrom/2000_half-8      8.03k ± 0%     8.03k ± 0%    ~     (all equal)
BellmanFordFrom/500_full-8       2.03k ± 0%     2.03k ± 0%    ~     (p=1.000 n=10+10)
BellmanFordFrom/1000_full-8      4.03k ± 0%     4.03k ± 0%    ~     (all equal)
BellmanFordFrom/2000_full-8      8.03k ± 0%     8.03k ± 0%    ~     (p=1.000 n=10+10)

The performance of the lazy implementation is a little worse and allocations
are a lot worse than the eager implementation. This reflects that the benchmark
is performed on a graph with a single connected component which gains no benefit
from the incremental approach but suffers the cost of repeated reallocation for
appends.

name                          new time/op    inc time/op    delta
BellmanFordFrom/500_tenth-8     4.11ms ± 1%    4.28ms ± 1%   +4.05%  (p=0.000 n=9+10)
BellmanFordFrom/1000_tenth-8    16.1ms ± 1%    16.0ms ± 6%     ~     (p=0.143 n=10+10)
BellmanFordFrom/2000_tenth-8    60.9ms ± 0%    62.8ms ± 0%   +3.13%  (p=0.000 n=9+10)
BellmanFordFrom/500_half-8      16.9ms ± 1%    17.5ms ± 1%   +3.97%  (p=0.000 n=9+10)
BellmanFordFrom/1000_half-8     67.4ms ± 1%    70.0ms ± 2%   +3.76%  (p=0.000 n=8+9)
BellmanFordFrom/2000_half-8      276ms ± 1%     285ms ± 0%   +2.91%  (p=0.000 n=10+10)
BellmanFordFrom/500_full-8      33.0ms ± 1%    35.5ms ± 5%   +7.40%  (p=0.000 n=9+10)
BellmanFordFrom/1000_full-8      133ms ± 0%     137ms ± 2%   +3.48%  (p=0.000 n=9+9)
BellmanFordFrom/2000_full-8      546ms ± 1%     592ms ± 6%   +8.42%  (p=0.000 n=9+10)

name                          new alloc/op   inc alloc/op   delta
BellmanFordFrom/500_tenth-8      142kB ± 0%     182kB ± 0%  +27.84%  (p=0.000 n=9+10)
BellmanFordFrom/1000_tenth-8     284kB ± 0%     363kB ± 0%  +27.94%  (p=0.000 n=10+10)
BellmanFordFrom/2000_tenth-8     624kB ± 0%     893kB ± 0%  +43.26%  (p=0.000 n=10+10)
BellmanFordFrom/500_half-8       142kB ± 0%     182kB ± 0%  +27.83%  (p=0.000 n=10+10)
BellmanFordFrom/1000_half-8      284kB ± 0%     363kB ± 0%  +27.90%  (p=0.000 n=8+10)
BellmanFordFrom/2000_half-8      624kB ± 0%     893kB ± 0%  +43.25%  (p=0.000 n=10+10)
BellmanFordFrom/500_full-8       142kB ± 0%     182kB ± 0%  +27.82%  (p=0.000 n=10+10)
BellmanFordFrom/1000_full-8      284kB ± 0%     363kB ± 0%  +27.89%  (p=0.000 n=9+10)
BellmanFordFrom/2000_full-8      624kB ± 0%     893kB ± 0%  +43.23%  (p=0.000 n=10+10)

name                          new allocs/op  inc allocs/op  delta
BellmanFordFrom/500_tenth-8      2.03k ± 0%     2.10k ± 0%   +3.50%  (p=0.000 n=8+8)
BellmanFordFrom/1000_tenth-8     4.03k ± 0%     4.12k ± 0%   +2.39%  (p=0.000 n=10+10)
BellmanFordFrom/2000_tenth-8     8.03k ± 0%     8.17k ± 0%   +1.77%  (p=0.000 n=10+10)
BellmanFordFrom/500_half-8       2.03k ± 0%     2.10k ± 0%   +3.49%  (p=0.000 n=8+10)
BellmanFordFrom/1000_half-8      4.03k ± 0%     4.12k ± 0%   +2.36%  (p=0.000 n=9+10)
BellmanFordFrom/2000_half-8      8.03k ± 0%     8.17k ± 0%   +1.77%  (p=0.000 n=8+10)
BellmanFordFrom/500_full-8       2.03k ± 0%     2.10k ± 0%   +3.50%  (p=0.000 n=10+10)
BellmanFordFrom/1000_full-8      4.03k ± 0%     4.12k ± 0%   +2.36%  (p=0.000 n=9+10)
BellmanFordFrom/2000_full-8      8.03k ± 0%     8.17k ± 0%   +1.76%  (p=0.000 n=10+10)
2021-01-07 06:43:24 +10:30

234 lines
6.3 KiB
Go

// Copyright ©2015 The Gonum Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package path
import (
"gonum.org/v1/gonum/graph"
"gonum.org/v1/gonum/graph/internal/linear"
"gonum.org/v1/gonum/graph/traverse"
)
// BellmanFordFrom returns a shortest-path tree for a shortest path from u to all nodes in
// the graph g, or false indicating that a negative cycle exists in the graph. If the graph
// does not implement Weighted, UniformCost is used.
//
// If g is a graph.Graph, all nodes of the graph will be stored in the shortest-path
// tree, otherwise only nodes reachable from u will be stored.
//
// The time complexity of BellmanFordFrom is O(|V|.|E|).
func BellmanFordFrom(u graph.Node, g traverse.Graph) (path Shortest, ok bool) {
if h, ok := g.(graph.Graph); ok {
if h.Node(u.ID()) == nil {
return Shortest{from: u}, true
}
path = newShortestFrom(u, graph.NodesOf(h.Nodes()))
} else {
if g.From(u.ID()) == graph.Empty {
return Shortest{from: u}, true
}
path = newShortestFrom(u, []graph.Node{u})
}
path.dist[path.indexOf[u.ID()]] = 0
path.negCosts = make(map[negEdge]float64)
var weight Weighting
if wg, ok := g.(Weighted); ok {
weight = wg.Weight
} else {
weight = UniformCost(g)
}
// Queue to keep track which nodes need to be relaxed.
// Only nodes whose vertex distance changed in the previous iterations
// need to be relaxed again.
queue := newBellmanFordQueue(path.indexOf)
queue.enqueue(u)
// TODO(kortschak): Consider adding further optimisations
// from http://arxiv.org/abs/1111.5414.
var loops int64
for queue.len() != 0 {
u := queue.dequeue()
uid := u.ID()
j := path.indexOf[uid]
to := g.From(uid)
for to.Next() {
v := to.Node()
vid := v.ID()
k, ok := path.indexOf[vid]
if !ok {
k = path.add(v)
}
w, ok := weight(uid, vid)
if !ok {
panic("bellman-ford: unexpected invalid weight")
}
joint := path.dist[j] + w
if joint < path.dist[k] {
path.set(k, joint, j)
if !queue.has(vid) {
queue.enqueue(v)
}
}
}
// The maximum number of edges in the relaxed subgraph is |V_r| * (|V_r|-1).
// If the queue-loop has more iterations than the maximum number of edges
// it indicates that we have a negative cycle.
maxEdges := int64(len(path.nodes)) * int64(len(path.nodes)-1)
if loops > maxEdges {
path.hasNegativeCycle = true
return path, false
}
loops++
}
return path, true
}
// BellmanFordAllFrom returns a shortest-path tree for shortest paths from u to all nodes in
// the graph g, or false indicating that a negative cycle exists in the graph. If the graph
// does not implement Weighted, UniformCost is used.
//
// If g is a graph.Graph, all nodes of the graph will be stored in the shortest-path
// tree, otherwise only nodes reachable from u will be stored.
//
// The time complexity of BellmanFordAllFrom is O(|V|.|E|).
func BellmanFordAllFrom(u graph.Node, g traverse.Graph) (path ShortestAlts, ok bool) {
if h, ok := g.(graph.Graph); ok {
if h.Node(u.ID()) == nil {
return ShortestAlts{from: u}, true
}
path = newShortestAltsFrom(u, graph.NodesOf(h.Nodes()))
} else {
if g.From(u.ID()) == graph.Empty {
return ShortestAlts{from: u}, true
}
path = newShortestAltsFrom(u, []graph.Node{u})
}
path.dist[path.indexOf[u.ID()]] = 0
path.negCosts = make(map[negEdge]float64)
var weight Weighting
if wg, ok := g.(Weighted); ok {
weight = wg.Weight
} else {
weight = UniformCost(g)
}
// Queue to keep track which nodes need to be relaxed.
// Only nodes whose vertex distance changed in the previous iterations
// need to be relaxed again.
queue := newBellmanFordQueue(path.indexOf)
queue.enqueue(u)
// TODO(kortschak): Consider adding further optimisations
// from http://arxiv.org/abs/1111.5414.
var loops int64
for queue.len() != 0 {
u := queue.dequeue()
uid := u.ID()
j := path.indexOf[uid]
for _, v := range graph.NodesOf(g.From(uid)) {
vid := v.ID()
k, ok := path.indexOf[vid]
if !ok {
k = path.add(v)
}
w, ok := weight(uid, vid)
if !ok {
panic("bellman-ford: unexpected invalid weight")
}
joint := path.dist[j] + w
if joint < path.dist[k] {
path.set(k, joint, j)
if !queue.has(vid) {
queue.enqueue(v)
}
} else if joint == path.dist[k] {
path.addPath(k, j)
}
}
// The maximum number of edges in the relaxed subgraph is |V_r| * (|V_r|-1).
// If the queue-loop has more iterations than the maximum number of edges
// it indicates that we have a negative cycle.
maxEdges := int64(len(path.nodes)) * int64(len(path.nodes)-1)
if loops > maxEdges {
path.hasNegativeCycle = true
return path, false
}
loops++
}
return path, true
}
// bellmanFordQueue is a queue for the Queue-based Bellman-Ford algorithm.
type bellmanFordQueue struct {
// queue holds the nodes which need to be relaxed.
queue linear.NodeQueue
// onQueue keeps track whether a node is on the queue or not.
onQueue []bool
// indexOf contains a mapping holding the id of a node with its index in the onQueue array.
indexOf map[int64]int
}
// enqueue adds a node to the bellmanFordQueue.
func (q *bellmanFordQueue) enqueue(n graph.Node) {
i, ok := q.indexOf[n.ID()]
switch {
case !ok:
panic("bellman-ford: unknown node")
case i < len(q.onQueue):
if q.onQueue[i] {
panic("bellman-ford: already queued")
}
case i == len(q.onQueue):
q.onQueue = append(q.onQueue, false)
case i < cap(q.onQueue):
q.onQueue = q.onQueue[:i+1]
default:
q.onQueue = append(q.onQueue, make([]bool, i-len(q.onQueue)+1)...)
}
q.onQueue[i] = true
q.queue.Enqueue(n)
}
// dequeue returns the first value of the bellmanFordQueue.
func (q *bellmanFordQueue) dequeue() graph.Node {
n := q.queue.Dequeue()
q.onQueue[q.indexOf[n.ID()]] = false
return n
}
// len returns the number of nodes in the bellmanFordQueue.
func (q *bellmanFordQueue) len() int { return q.queue.Len() }
// has returns whether a node with the given id is in the queue.
func (q bellmanFordQueue) has(id int64) bool {
idx, ok := q.indexOf[id]
if !ok || idx >= len(q.onQueue) {
return false
}
return q.onQueue[idx]
}
// newBellmanFordQueue creates a new bellmanFordQueue.
func newBellmanFordQueue(indexOf map[int64]int) bellmanFordQueue {
return bellmanFordQueue{
onQueue: make([]bool, len(indexOf)),
indexOf: indexOf,
}
}